python链接mqtt订阅与发布
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import random from paho.mqtt import client as mqtt_client broker = #ip地址 port = 1883 topic = "/python/mqtt" # generate client ID with pub prefix randomly client_id = #client_id def connect_mqtt() - > mqtt_client: 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) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client def subscribe(client: mqtt_client): def on_message(client, userdata, msg): print (f "Received `{msg.payload.decode()}` from `{msg.topic}` topic" ) client.subscribe(topic) client.on_message = on_message def run(): client = connect_mqtt() subscribe(client) client.loop_forever() if __name__ = = '__main__' : run() |
消息发布
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import random import time from paho.mqtt import client as mqtt_client #基本链接数据同上 topic = "" def clicent_main(client,message: str ): """ 客户端发布消息 :param message: 消息主体 :return: """ time_now = time.strftime( '%Y-%m-%d %H-%M-%S' , time.localtime(time.time())) payload = { "msg" : "%s" % message, "data" : "%s" % time_now} # publish(主题:Topic; 消息内容) client.publish(topic, json.dumps(payload, ensure_ascii = False )) print ( "Successful send message!" ) return True |
作者: yetangjian
出处: https://www.cnblogs.com/yetangjian/p/15881295.html
关于作者: yetangjian
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(yetangjian@outlook.com)咨询.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律