python mqtt subscribe
时间: 2023-08-17 07:13:01 浏览: 121
要在Python中使用MQTT订阅消息,你可以使用paho-mqtt库。首先,你需要安装paho-mqtt库。然后,你可以使用以下代码来订阅消息:
```python
from paho.mqtt import client as mqtt
import uuid
def on_connect(client, userdata, flags, rc):
"""一旦连接成功, 回调此方法"""
rc_status = \["连接成功", "协议版本不正确", "客户端标识符无效", "服务器不可用", "用户名或密码不正确", "未经授权"\]
print("connect:", rc_status\[rc\])
def on_message(client, userdata, msg):
"""一旦订阅到消息, 回调此方法"""
print("主题:"+msg.topic+" 消息:"+str(msg.payload.decode('gb2312')))
def mqtt_connect():
"""连接MQTT服务器"""
mqttClient = mqtt.Client(str(uuid.uuid4()))
mqttClient.on_connect = on_connect # 返回连接状态的回调函数
mqttClient.on_message = on_message # 返回订阅消息回调函数
MQTTHOST = "IP" # MQTT服务器地址
MQTTPORT = 1883 # MQTT端口
mqttClient.username_pw_set("username", "password") # mqtt服务器账号密码
mqttClient.connect(MQTTHOST, MQTTPORT, 60)
mqttClient.loop_start() # 启用线程连接
return mqttClient
def on_subscribe():
"""订阅主题:mqtt/demo"""
mqttClient = mqtt_connect()
mqttClient.subscribe("mqtt/demo", 2)
while True:
pass
if __name__ == '__main__':
on_subscribe()
```
这段代码使用paho-mqtt库创建了一个MQTT客户端,并连接到MQTT代理。然后,它订阅了主题"mqtt/demo",并在收到消息时调用了on_message函数进行处理。你可以根据需要修改主题和其他参数。
#### 引用[.reference_title]
- *1* [Python实现MQTT订阅、发布](https://blog.csdn.net/weixin_41888371/article/details/123850672)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [通过python实现MQTT发布和订阅](https://blog.csdn.net/qq_45664055/article/details/120238371)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文