请先去去看Onenet 物联网Mqtt初探(MQTT.fx模拟登陆与数据收发)文章
图文:https://www.toutiao.com/i6989991497978593805/
视频:https://www.ixigua.com/6990009680957440544
,否则可能不明被我输入的是什么消息。这里直接做Python代码的mqtt连接:
安装paho-mqtt MQTT 客户端:
GitHub仓库源码及英文文档:
https://pypi.org/project/paho-mqtt/#description
https://github.com/eclipse/paho.mqtt.python
控制台输入命令:pip3 install paho-mqtt
安装成功。
打开jupyter lab,我习惯了这个ide,你也可以选你熟悉的ide
编写代码:
#根据官方例程修改了登录部分
import paho.mqtt.client as mqtt
broker = '183.230.40.96' #onenet地址
port = 1883 #连接的端口
client_id = f'my_pc1' #设备的ID
p_id = '448854' #产品的数字ID
#密码
pwd = 'version=2018-10-31&res=products%2F448854%2Fdevices%2Fmy_pc1&et=1752940800&method=md5&sign=PefA%2BfTBddIACekb0EBvhg%3D%3D'
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("$sys/448854/my_pc1/cmd/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client(client_id)
client.username_pw_set(p_id,pwd)
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker, 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
已连接,等待消息,去onenet控制台看状态
也显示在线,好的,试试下发信息
收到了,这里没做结果回复代码,服务端会返回错误数据,后面应用到再做添加。
#发送消息到服务端
client.publish("$sys/448854/my_pc1/dp/post/json", "{ 'id': 123, 'dp': { 'data': [{ 'v':'123123asdffgg', }]}}", qos=0, retain=False)
服务端已收到。
#关于loop_forever()的用法见(中文,这哥们写的比较明白):https://www.jianshu.com/p/0ed4e59b1e8f
Ok,至此简单收发已完成。
本文暂时没有评论,来添加一个吧(●'◡'●)