Python实现MQTT订阅发布

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名称不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值