当前位置:   article > 正文

Python实现MQTT订阅发布

Python实现MQTT订阅发布

1、安装

pip install paho-mqtt

2、发布消息

  1. import time
  2. import paho.mqtt.client as mqtt
  3. def on_connect(client, userdata, flags, rc):
  4. print("Connected with result code: " + str(rc))
  5. def on_message(client, userdata, msg):
  6. print(msg.topic + " " + str(msg.payload))
  7. def publish_data(jsondata):
  8. print("publish data sucess>>>>>>>>>>>>>>>>>>>>>")
  9. def on_disconnect(client, userdata, rc):
  10. print("-- Disconnection returned result:" + str(rc))
  11. def on_subscribe(client, userdata, mid, granted_qos):
  12. print("-- on_subscribe returned mid:" + str(mid))
  13. # 连接服务器的参数
  14. def publish_para():
  15. client = mqtt.Client(client_id="your_id0", clean_session=False)
  16. client.on_connect = on_connect
  17. client.on_message = on_message
  18. client.on_disconnect = on_disconnect
  19. client.connect("your_address", 1883)
  20. client.loop_start()
  21. return client
  22. def mqtt_on_publish_to_cloud(topic, message_dict):
  23. # 判断指令是否发送成功
  24. client = publish_para()
  25. while True:
  26. payload = str(message_dict)
  27. client.publish(topic, payload)
  28. print(payload)
  29. print("mqtt向云端发送指令成功")
  30. time.sleep(2)
  31. if __name__ == '__main__':
  32. topic = "mqtt向云端发送指令"
  33. message_dict = {"发送指令" :"成功"}
  34. # mqtt向云端发送指令成功函数
  35. mqtt_on_publish_to_cloud(topic, message_dict)

3、订阅信息

  1. import time
  2. import paho.mqtt.client as mqtt
  3. def on_connect(client, userdata, flags, rc):
  4. print("Connected with result code: " + str(rc))
  5. def on_disconnect(client, userdata, rc):
  6. print("-- Disconnection returned result:" + str(rc))
  7. def on_message(client, userdata, msg):
  8. message = msg.payload.decode("UTF-8")
  9. print(message)
  10. def on_subscribe(client, userdata, mid, granted_qos):
  11. print("-- on_subscribe returned mid:" + str(mid))
  12. def on_unsubscribe(client, userdata, mid, granted_qos):
  13. print("On unSubscribed: qos = %d" % granted_qos)
  14. def mqtt_on_subscribe(topic):
  15. # 判断指令是否读取成功
  16. client = mqtt.Client(client_id="your_id1", clean_session=False)
  17. client.on_connect = on_connect
  18. client.on_message = on_message
  19. client.on_disconnect = on_disconnect
  20. client.on_subscribe = on_subscribe
  21. client.connect("your_address", 1883)
  22. client.loop_start() # 开启一个单线程
  23. client.subscribe(topic)
  24. while True:
  25. print("mqtt指令监听成功")
  26. time.sleep(2)
  27. if __name__ == '__main__':
  28. topic = "mqtt向云端发送指令"
  29. # 订阅服务器指令
  30. mqtt_on_subscribe(topic)

4、注意

1.要求两个主函数设定的topic内容相同、服务器地址相同。

2.两个id名称不同。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/485787
推荐阅读
相关标签
  

闽ICP备14008679号