1、安装
pip install paho-mqtt
2、发布消息
import time
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code: " + str(rc))
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
def publish_data(jsondata):
print("publish data sucess>>>>>>>>>>>>>>>>>>>>>")
def on_disconnect(client, userdata, rc):
print("-- Disconnection returned result:" + str(rc))
def on_subscribe(client, userdata, mid, granted_qos):
print("-- on_subscribe returned mid:" + str(mid))
# 连接服务器的参数
def publish_para():
client = mqtt.Client(client_id="your_id0", clean_session=False)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect("your_address", 1883)
client.loop_start()
return client
def mqtt_on_publish_to_cloud(topic, message_dict):
# 判断指令是否发送成功
client = publish_para()
while True:
payload = str(message_dict)
client.publish(topic, payload)
print(payload)
print("mqtt向云端发送指令成功")
time.sleep(2)
if __name__ == '__main__':
topic = "mqtt向云端发送指令"
message_dict = {"发送指令" :"成功"}
# mqtt向云端发送指令成功函数
mqtt_on_publish_to_cloud(topic, message_dict)
3、订阅信息
import time
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code: " + str(rc))
def on_disconnect(client, userdata, rc):
print("-- Disconnection returned result:" + str(rc))
def on_message(client, userdata, msg):
message = msg.payload.decode("UTF-8")
print(message)
def on_subscribe(client, userdata, mid, granted_qos):
print("-- on_subscribe returned mid:" + str(mid))
def on_unsubscribe(client, userdata, mid, granted_qos):
print("On unSubscribed: qos = %d" % granted_qos)
def mqtt_on_subscribe(topic):
# 判断指令是否读取成功
client = mqtt.Client(client_id="your_id1", clean_session=False)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.on_subscribe = on_subscribe
client.connect("your_address", 1883)
client.loop_start() # 开启一个单线程
client.subscribe(topic)
while True:
print("mqtt指令监听成功")
time.sleep(2)
if __name__ == '__main__':
topic = "mqtt向云端发送指令"
# 订阅服务器指令
mqtt_on_subscribe(topic)
4、注意
1.要求两个主函数设定的topic内容相同、服务器地址相同。
2.两个id名称不同。