Mosquitto: Python和MQTT

本文件是入门指南指南的一部分。您可以在这里查看完整指南:如何开始使用Mosquitto

👋 欢迎来到 Stackhero 文档!

Stackhero 为您提供一个全托管的 Mosquitto MQTT cloud 环境,专为高可靠性和灵活性设计:

  • 无限制的消息吞吐量和数据传输,确保您的工作流程不会受到人为限制。
  • 通过您自己的外部 API 实现无限制的设备认证,让设备接入和访问管理变得简单高效。
  • 高级 ACLs,可对主题、用户和操作进行精细化权限控制。
  • 提供自定义域名,并内置HTTPS,为您的终端提供安全且具品牌形象的访问入口(例如:https://mqtt.your-company.com)。
  • 一键更新,轻松应用功能改进或安全补丁,无需繁琐操作。
  • 始终如一的高性能强安全性,每个实例都运行在专属私有基础设施上。

加速您的 IoT 项目,大幅降低运维负担。只需几分钟,您就可以拥有一个安全、可用于生产环境的 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!