之前看Mosquitto文档的时候,发现提供了一个Python的库,后来发现,他把这个库捐给了Eclipse Paho
。
Eclipse Paho 简介
The Paho project provides scalable open-source client implementations of open and standard messaging protocols aimed at new, existing, and emerging applications for Machine‑to‑Machine (M2M) and Internet of Things (IoT).
是的,最近Eclipse在搞各种物联网。MQTT协议 Python Paho
Python Mosquitto
之前的代码是这样的
import mosquitto
mqttc = mosquitto.Mosquitto("python_pub")
mqttc.connect("mqtt.phodal.com", 1883, 60, True)
mqttc.publish("hello", "Hello, World!")
于是代码变成了这样
import paho.mqtt.client as mqtt
mqttc = mqtt.Client("python_pub")
mqttc.connect("mqtt.phodal.com", 1883, 60)
mqttc.publish("lettuce", "Hello, World baby!",2)
他们是要弄怎样!!
更详细代码如下面所示:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("lettuce")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("mqtt.phodal.com", 1883, 60)
client.loop_forever()