python mqtt 客户端的实现代码实例

yipeiwu_com6年前Python基础

这篇文章主要介绍了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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python射线法判断检测点是否位于区域外接矩形内

本文实例为大家分享了python射线法判断点是否位于区域内的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -...

对Python中列表和数组的赋值,浅拷贝和深拷贝的实例讲解

对Python中列表和数组的赋值,浅拷贝和深拷贝的实例讲解 列表赋值: >>> a = [1, 2, 3] >>> b = a >>&...

Python堆排序原理与实现方法详解

Python堆排序原理与实现方法详解

本文实例讲述了Python堆排序原理与实现方法。分享给大家供大家参考,具体如下: 在这里要事先说明一下我也是新手,很多东西我了解不是很深入,写算法完全是锻炼自己逻辑能力同时顺带帮助读研的...

python pandas库中DataFrame对行和列的操作实例讲解

用pandas中的DataFrame时选取行或列: import numpy as np import pandas as pd from pandas import Sereis,...

Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)

本文实例讲述了Python3的urllib.parse常用函数。分享给大家供大家参考,具体如下: 1、获取url参数 >>> from urllib import...