您好,登錄后才能下訂單哦!
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 mqtt 客戶端的實現問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。