MQTT 和 Python 完整教學


安裝 paho-mqtt 插件 ✈️

pip install paho-mqtt 

或者

pip3 install paho-mqtt

檢查 paho-mqtt 是否已安裝成功 ✈️

C:\>pip list ↩️
Package    Version
---------- -------
paho-mqtt  1.6.1  ⬅️ Successfully installed paho-mqtt-1.6.1
pip        22.3.1
setuptools 65.5.0

入門- 創建一個訂閱

使用免費的 MQTT server

import paho.mqtt.client as mqtt


# 連接到 MQTT 服務器時將執行的回調函數
def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

    # 訂閱可以在 on_connet 中設置,如果連接丟失
    # 或重連會重新訂閱
    client.subscribe("$SYS/#")


# 收到MQTT服務器發送的消息時執行的回調函數
def on_message(client, userdata, msg):
    # Convert encoding to utf-8 or not
    print(msg.topic + " " +
          str(msg.payload.decode("utf-8")))


# 初始化 my_client
my_client = mqtt.Client()

# 設置連接後的回調函數
my_client.on_connect = on_connect

# 設置接收後的回調函數
my_client.on_message = on_message

# 設置登錄賬號和密碼
my_client.username_pw_set("rw", "readwrite")

# 設置連接參數(IP、端口、連接時間)
my_client.connect("test.mosquitto.org", 1884, 60)

# 開始連接,執行設置的動作,loop_forever可以處理重連問題
# 也可以手動使用其他loop函數連接
my_client.loop_forever()

結果

Connected with result code 0
$SYS/broker/bytes/received 1534092578435
$SYS/broker/bytes/sent 32330049071821
$SYS/broker/clients/active 3489
$SYS/broker/clients/connected 3489
$SYS/broker/clients/disconnected 102900
$SYS/broker/clients/inactive 102900
$SYS/broker/clients/total 106389
$SYS/broker/connection/31d8cf14464a.famous/state 1
$SYS/broker/connection/31d8cf14464a.renningen/state 1
$SYS/broker/connection/4de57af3c5ab.mosquitto-bridge/state 0

Getting Started – Create a  Publish / Subscribe

首先, 執行以下訂閱程式碼

import paho.mqtt.client as mqtt


def on_connect(client, userdata, flags, rc):
    client.subscribe("mqtt_topic/#")


def on_message(client, userdata, msg):
    print("From > " + msg.topic + " : " +
          str(msg.payload.decode("utf-8")))


my_client = mqtt.Client()

my_client.on_connect = on_connect

my_client.on_message = on_message

my_client.username_pw_set("rw", "readwrite")

my_client.connect("test.mosquitto.org", 1884, 60)

my_client.loop_forever()

然後再執行以下的推送程式碼

import paho.mqtt.client as mqtt
import json


msg = "Hello World"

my_client = mqtt.Client()

my_client.username_pw_set("rw", "readwrite")

my_client.connect("test.mosquitto.org", 1884, 60)

# The topic and content to publish
my_client.publish("mqtt_topic", json.dumps(msg))

將在 “訂閱” 的終端機看到輸出結果

From > mqtt_topic : "Hello World"