python链接mqtt订阅与发布
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()
消息发布
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)咨询.