mqtt-python客户端

配置环境

pip install paho-mqtt

或者从Github源码安装

git clone https://github.com/eclipse/paho.mqtt.python.git
cd paho.mqtt.python
python setup.py install

创建python文件

import context # Ensures paho is in PYTHONPATH
import paho.mqtt.client as mqtt
def on_connect(mqttc, obj, flags, rc): print("rc: " + str(rc))
def on_message(mqttc, obj, msg): print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
def on_publish(mqttc, obj, mid): print("mid: " + str(mid))
def on_subscribe(mqttc, obj, mid, granted_qos): print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(mqttc, obj, level, string): print(string)
# If you want to use a specific client id, use
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = mqtt.Client("client_id")
mqttc.username_pw_set("username", "password")
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
# mqttc.on_log = on_log
mqttc.connect("host", 1883, 60)
mqttc.subscribe("topic", 0)
mqttc.loop_forever()

你可能感兴趣的:(mqtt-python客户端)