Mosquitto: Python 和 MQTT
此文件屬於入門指南指南的一部分。請在此處查看完整指南:如何開始使用 Mosquitto。
👋 歡迎來到 Stackhero 文件!
Stackhero 提供即用型 Mosquitto MQTT cloud 解決方案,帶來多項優勢,包括:
- 無限的消息交換和傳輸。
- 通過外部 API 進行 無限 的設備認證。
- 在主題、用戶和操作上提供 高級 ACLs。
- 使用 HTTPS 保護的 可自訂域名(例如,https://mqtt.your-company.com)。
- 只需點擊即可輕鬆 更新。
- 由 專用私有 VM 提供的最佳 性能 和強大 安全性。
節省時間 並 簡化您的生活:只需 5 分鐘 即可嘗試 Stackhero 的 Mosquitto MQTT cloud hosting 解決方案!
要使用 Python 與 Mosquitto,建議使用 Paho MQTT Python 客戶端庫。使用以下命令安裝:
pip install paho-mqtt
以下是一個使用 TLS 加密和身份驗證連接到 Mosquitto 伺服器的 Python 腳本示例:
import paho.mqtt.client as mqtt
import random
import string
from paho.mqtt.client import CallbackAPIVersion
def on_connect(client, userdata, flags, reason_code, properties=None):
if reason_code == 0:
print("Connected successfully")
else:
print(f"Connection failed with reason {reason_code}")
def on_message(client, userdata, msg, properties=None):
print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")
def generate_client_id(length=8):
characters = string.ascii_letters + string.digits
return "client_" + ''.join(random.choice(characters) for _ in range(length))
client_id = generate_client_id()
client = mqtt.Client(
client_id=client_id,
callback_api_version=CallbackAPIVersion.VERSION2
)
client.on_connect = on_connect
client.on_message = on_message
host = "<XXXXXX>.stackhero-network.com"
port = <PORT_TLS>
client.username_pw_set("<USER>", "<PASSWORD>")
client.tls_set()
try:
print(f"Connecting to {host} with client ID: {client_id}")
client.connect(host, port)
client.loop_start()
client.subscribe("$SYS/#")
try:
while True:
pass
except KeyboardInterrupt:
print("\nDisconnecting...")
client.loop_stop()
client.disconnect()
except Exception as e:
print(f"Error: {e}")
有了這些指引,您應該能夠順利開始在 Stackhero 上使用 Mosquitto。祝您愉快地探索 MQTT!