MosquittoMqtt服务器
MQTT服务器的搭建
https://blog.csdn.net/weixin_42181686/article/details/146358417
检查服务状态
sudo systemctl status mosquitto
启动服务
sudo systemctl start mosquitto
停止服务
sudo systemctl stop mosquitto
重启服务
sudo systemctl restart mosquitto
设置开机自启动
sudo systemctl enable mosquitto
禁用开机自启动
sudo systemctl disable mosquitto
重新加载配置(不重启服务)
sudo systemctl reload mosquitto
连接MQTT 客户端
命令行连接(如 mosquitto_sub / mosquitto_pub)
mosquitto_sub 订阅 MQTT 主题并接收消息 mosquitto_sub -h localhost -t "topic"
mosquitto_pub 发布消息到 MQTT 主题 mosquitto_pub -h localhost -t "topic" -m "msg"
mosquitto_sub -h "服务器IP" -t "主题名" -u "username" -P "password"
mosquitto_pub -h "服务器IP" -t "主题名" -m "消息内容" -u "username" -P "password"
用户名,密码,主题配置文件
/etc/mosquitto/aclfile
aclfile配置文件
1.1 简单配好的标准模样
# This affects access control for clients with no username.
topic read $SYS/#
# This only affects clients with username "roger".
user changchang
topic readwrite SCM/#
user changchang
topic readwrite test/abc
pattern write $SYS/broker/connection/%c/state
1.2 如何新增主题
user 用户名 topic 权限 home/#
1.3 权限类型
| 权限关键词 | 描述 | 示例 |
|---|---|---|
| topic read | 仅允许订阅主题 | user client1 topic read home/# |
| topic write | 仅允许发布到主题 | user client2 topic write cmd/# |
| topic readwrite | 允许同时发布和订阅 | user admin topic readwrite sys/# |
1.4 通配符规则
| 通配符 | 匹配范围 | 示例 | 限制条件 |
|---|---|---|---|
| + | 单级通配符 | (一级目录) | sensor/+/data 匹配 sensor/room1/data |
| # | 多级通配符 | (任意层级) | home/# 匹配 home/floor1/light |
Python连接
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client = mqtt.Client()
client.username_pw_set("username", "password") # 设置用户名和密码
client.on_connect = on_connect
client.connect("服务器IP", 1883, 60)
client.subscribe("主题名")
client.loop_forever()

浙公网安备 33010602011771号