码迷,mamicode.com
首页 > 编程语言 > 详细

python mqtt client publish操作

时间:2018-03-01 17:35:06      阅读:1089      评论:0      收藏:0      [点我收藏+]

标签:import   elf   scribe   word   forever   pytho   __name__   res   odi   

使用Python库paho.mqtt.client 模拟mqtt client 连接broker,publish topic。

#-*-coding:utf-8-*-
import paho.mqtt.client as mqtt

class mqttHandle(object):

    def __init__(self,mqtt_info):
        self.mqtt_info=mqtt_info

    def on_connect(client, userdata, flags, rc):
        print("Connected with result code " + str(rc))
        client.subscribe("chat")

    def on_message(client, userdata, msg):
        print("topic:" + msg.topic + " payload:" + str(msg.payload))

    def publish(self):
        client = mqtt.Client()
        client.on_connect = mqttHandle.on_connect
        client.on_message = mqttHandle.on_message
        client.username_pw_set(self.mqtt_info[username], self.mqtt_info[password])
        client.connect(self.mqtt_info[host], self.mqtt_info[port], 60)
        client.publish(self.mqtt_info[topic], str(self.mqtt_info[payload]))
        #client.loop_forever()
        client.disconnect()
        print(publish topic over)

if __name__=="__main__":
    mqtt_info={
    username:username,
    password:password,
    host:10.10.10.10,
    port:1833,
    topic:test,
    payload:hello world,
}
    mqttc=mqttHandle(mqtt_info)
    mqttc.publish()

 

python mqtt client publish操作

标签:import   elf   scribe   word   forever   pytho   __name__   res   odi   

原文地址:https://www.cnblogs.com/frost-hit/p/8488298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!