Python MQTT 简单 Demo
2022/7/16 1:20:08
本文主要是介绍Python MQTT 简单 Demo,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
依赖
下载 pahao-mqtt
:
pip install paho-mqtt
引用:
from paho.mqtt import client as MQTTClient from time import sleep
示例
非匿名连接
初始化数据:
class Config: BROKER = "[MQTT 服务器 IP 或 域名]" PORT = [MQTT 服务器端口] TOPIC = "[主题]" CLIENT_ID = "[客户端 ID]" USERNAME = "[用户名]" PASSWORD = 口令" CONNECT = None MESSAGE = "[消息]"
建立连接
def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) Config.CONNECT = MQTTClient.Client(Config.CLIENT_ID) Config.CONNECT.username_pw_set(Config.USERNAME, Config.PASSWORD) Config.CONNECT.on_connect = on_connect Config.CONNECT.connect(Config.BROKER, Config.PORT)
通过主题发布消息
def publish(): while(True): sleep(1) result = Config.CONNECT.publish(Config.TOPIC, Config.MESSAGE) status = result[0] if status == 0: print(f"Send `{Config.MESSAGE}` to topic `{Config.TOPIC}`") else: print(f"Failed to send message to topic {Config.TOPIC}") def app(): connect_mqtt() publish() Config.CONNECT.loop_forever()
通过主题订阅消息
def subscribe(): def on_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") Config.CONNECT.subscribe(Config.TOPIC) Config.CONNECT.on_message = on_message def app(): connect_mqtt() subscribe() Config.CONNECT.loop_forever()
运行
if __name__ == '__main__': app()
这篇关于Python MQTT 简单 Demo的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Python基础编程
- 2024-11-25Python编程基础:变量与类型
- 2024-11-25Python编程基础与实践
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南