Mosquitto: 入门指南
如何开始使用Mosquitto
👋 欢迎来到 Stackhero 文档!
Stackhero 提供即用型 Mosquitto MQTT 云 解决方案,具有众多优势,包括:
- 无限制的消息交换和传输。
- 通过外部 API 进行无限制的设备认证。
- 针对主题、用户和操作的高级 ACL。
- 使用 HTTPS 保护的可定制域名(例如,https://mqtt.your-company.com)。
- 只需点击即可轻松更新。
- 由专用私有 VM提供的最佳性能和强大安全性。
节省时间并简化您的生活:只需 5 分钟即可试用 Stackhero 的 Mosquitto MQTT 云托管 解决方案!
Mosquitto是一个MQTT代理,实现了MQTT协议(消息队列遥测传输),专为物联网设备与服务器之间的轻量级通信而设计。
在Stackhero上,Mosquitto配置了TLS加密和用户认证,以提供安全的通信环境。
您可以在https://github.com/stackhero-io/mosquittoGettingStarted找到展示如何使用Mosquitto的实用代码示例。
了解MQTT主题
MQTT将通信组织为“主题”,这些主题充当发布和订阅数据的通道。设备将消息发布到特定主题或订阅这些主题以接收相关更新。
MQTT主题的结构
MQTT中的主题区分大小写,必须包含UTF-8字符,并且至少需要一个字符。主题中的层次结构使用斜杠(/)字符定义。
以下是一个用于收集温度和湿度数据的物联网设备的示例设置,通过其MAC地址进行识别:
-
对于MAC地址为
00:00:00:00:00:00的设备:- 温度:
devices/00:00:00:00:00:00/temperature - 湿度:
devices/00:00:00:00:00:00/humidity
- 温度:
-
对于MAC地址为
11:11:11:11:11:11的设备:- 温度:
devices/11:11:11:11:11:11/temperature - 湿度:
devices/11:11:11:11:11:11/humidity
- 温度:
应用程序可以订阅特定主题,例如devices/00:00:00:00:00:00/temperature,以接收来自相应物联网设备的数据。
在MQTT主题中使用通配符
MQTT支持通配符以实现高效的主题管理:
-
+通配符匹配主题层次结构中的单个级别。例如,订阅devices/+/temperature可以捕获像devices/1/temperature这样的主题,但不能捕获devices/1/2/temperature。 -
#通配符匹配多个级别。例如,devices/#可以匹配诸如devices/1/temperature、devices/2/humidity和devices/1/2/somethingElse这样的主题。
使用mosquitto_pub和mosquitto_sub进行测试
mosquitto_pub和mosquitto_sub命令行工具非常适合测试MQTT设置。在使用它们之前,请确保在Stackhero仪表板上的Mosquitto配置中禁用“允许不安全连接”选项。
以下是测试方法:
-
使用
#通配符订阅所有主题:mosquitto_sub -L -d "mqtts://admin:<PASSWORD>@<XXXXXX>.stackhero-network.com:<PORT_TLS>/#" -
打开另一个终端以向主题发布消息:
mosquitto_pub -L -d "mqtts://admin:<PASSWORD>@<XXXXXX>.stackhero-network.com:<PORT_TLS>/sensor/a" -m "It works"
在第一个控制台中,您应该看到已发布的消息以及由-d标志启用的调试日志。
通过WebSockets连接到MQTT
您可以使用WebSockets直接从Web浏览器连接到您的Mosquitto服务器。有关更多详细信息,请参阅“WebSockets”文档。
Node.js和MQTT
展示如何使用Node.js与Mosquitto的示例可在https://github.com/stackhero-io/mosquittoGettingStarted找到。
Python和MQTT
要使用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!