python mqtt 客户端的实现代码实例
作者:疯狂的小萝卜头 时间:2021-11-05 16:04:09
这篇文章主要介绍了python mqtt 客户端代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
安装paho-mqtt
pip install paho-mqtt -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
python消息收发实现
import paho.mqtt.client as mqtt
from multiprocessing import Process
import camera_person_num
MQTTHOST = "172.19.4.4"
MQTTPORT = 1883
mqttClient = mqtt.Client()
# 连接MQTT服务器
def on_mqtt_connect():
mqttClient.connect(MQTTHOST, MQTTPORT, 60)
mqttClient.loop_start()
# 消息处理函数
def on_message_come(lient, userdata, msg):
print(msg.topic + ":" + str(msg.payload.decode("utf-8")))
# 消息处理开启多进程
p = Process(target=talk, args=("/camera/person/num/result", msg.payload.decode("utf-8")))
p.start()
# subscribe 消息订阅
def on_subscribe():
mqttClient.subscribe("test", 1) # 主题为"test"
mqttClient.on_message = on_message_come # 消息到来处理函数
# publish 消息发布
def on_publish(topic, msg, qos):
mqttClient.publish(topic, msg, qos);
# 多进程中发布消息需要重新初始化mqttClient
def talk(topic, msg):
cameraPsersonNum = camera_person_num.CameraPsersonNum(msg)
t_max, t_mean = cameraPsersonNum.personNum()
mqttClient = mqtt.Client()
mqttClient.connect(MQTTHOST, MQTTPORT, 60)
mqttClient.loop_start()
mqttClient.publish(topic, '{"max":' + str(t_max) + ',"mean:"' + str(t_mean) + '}', 1)
def main():
on_mqtt_connect()
on_subscribe()
while True:
pass
if __name__ == '__main__':
main()
来源:https://www.cnblogs.com/gmhappy/p/9472371.html
标签:python,mqtt,客户端
0
投稿
猜你喜欢
Python遗传算法Geatpy工具箱使用介绍
2021-11-02 02:21:16
SQLServer数据库密码短时间强制过期的解决
2024-01-18 09:40:01
SQL Server 数据库基本操作语句总结
2024-01-18 05:12:06
sql脚本查询数据库表,数据,结构,约束等操作的方法
2024-01-19 17:23:26
vue+canvas实现数据实时从上到下刷新瀑布图效果(类似QT的)
2024-05-09 09:16:28
Nuxt3+ElementPlus构建打包部署全过程
2023-07-02 16:28:51
MySQL不使用order by实现排名的三种思路总结
2024-01-17 13:43:46
JavaScript 关于引用那点事
2009-11-28 18:44:00
PHP详解ASCII码对照表与字符转换
2023-11-07 01:16:55
python调用摄像头的示例代码
2021-10-11 02:18:09
Python去除、替换字符串空格的处理方法
2022-07-17 05:38:25
Python温度转换实例分析
2023-08-21 22:48:32
Python 函数基础知识汇总
2021-12-22 15:47:09
使用AJAX和Django获取数据的方法实例
2021-11-14 20:40:20
编码问题引起的折腾
2009-07-03 12:43:00
pycharm中venv文件夹自定义处理方式图解
2022-06-28 22:46:53
空行不空格式排版组织原理
2010-05-03 14:46:00
浅析JavaScript中的常用算法与函数
2024-05-03 15:32:53
Go语言中内存管理逃逸分析详解
2024-05-08 10:13:48
pytorch下的unsqueeze和squeeze的用法说明
2023-07-16 14:01:41