1.安裝paho-mqtt
使用Python Package Index (PyPi)
pip install paho-mqtt
使用virtualenv
virtualenv paho-mqtt
source paho-mqtt/bin/activate
pip install paho-mqtt
或者編譯源代碼
git clone https://github.com/eclipse/paho.mqtt.python
使用源碼安裝
cd paho.mqtt.python python setup.py install
2. Demo
發布數據
# import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import time
HOST = "127.0.0.1"
PORT = 61613
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
def on_message(client, userdata, msg):
print(msg.topic+" "+msg.payload.decode("utf-8"))
if __name__ == '__main__':
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
# client = mqtt.Client(client_id) # ClientId不能重復,所以使用當前時間
# client.username_pw_set("admin", "123456") # 必須設置,否則會返回「Connected with result code 4」
# client.on_connect = on_connect
# client.on_message = on_message
# client.connect(HOST, PORT, 60)
# client.publish("test", "你好 MQTT", qos=0, retain=False) # 發布消息
publish.single("test", "你好 MQTT", qos = 1,hostname=HOST,port=PORT, client_id=client_id,auth = {'username':"admin", 'password':"123456"})
接收數據
import paho.mqtt.client as mqtt
import time
HOST = "127.0.0.1"
PORT = 61613
def client_loop():
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
client = mqtt.Client(client_id) # ClientId不能重復,所以使用當前時間
client.username_pw_set("admin", "123456") # 必須設置,否則會返回「Connected with result code 4」
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, 60)
client.loop_forever()
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
def on_message(client, userdata, msg):
print(msg.topic+" "+msg.payload.decode("utf-8"))
if __name__ == '__main__':
client_loop()
client_id是必須的,並且是唯一的。否則可能會出現如下錯誤:WinError 10054] 遠程主機強迫關閉了一個現有的連接。
