python mqtt client publish操作

Posted frostHIT

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python mqtt client publish操作相关的知识,希望对你有一定的参考价值。

使用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操作的主要内容,如果未能解决你的问题,请参考以下文章

mqtt client python example

python 实现MQTT Client

paho.mqtt.python模块怎么安装

Python MQTT 实验

MQTT qos参数无效

paho mqtt回调python中的不同类模块