MQTT是一种基本发布/订阅形式的消息协议
本次用的锁控板是控制快递柜的锁,共16路,需要插一张电话卡提供流量,用商家提供的工具将锁控板连接的服务器IP改成了自己搭建的MQTT,用GOLANG做后端控制开锁。
下载&安装应用:下载链接
1.将安装目录下的pwfile.example修改为pwfile
2.创建应用内的用户
mosquitto_passwd.exe pwfile super #假设添加的用户名为super
然后会要求输入二次密码,输入完后用户就添加好了
修改aclfile.example,这个文件是定义客户端对主题的访问权限
例如:
#下面的配置只对用户super有效
user super
topic readwrite YJIOT/YJLOCK/HOST/+
topic readwrite YJIOT/YJLOCK/DEVICE/+
目前我开发用的这个锁控板发送命令的主题就是YJIOT/YJLOCK/HOST/+设备IMEI,根据设备卖家提供的文档来改
最后改配置文件,mosquitto.conf
allow_anonymous true
password_file C:\Program Files\mosquitto\passwd #存放用户列表的位置和文件名,passwd 就是文件名
acl_file C:\Program Files\mosquitto\acl_file #ACL的位置和文件名
listener 1883 0.0.0.0 #监听1883端口,0.0.0.0表示所有人可以连接
最后运行
mosquitto.exe -c mosquitto.conf -v
使用指定的配置文件并启用verbose模式显示详细日志
额外
golang中连接mqtt并发送命令。下面是发送开单路锁的命令
import (
"fmt"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
opts := MQTT.NewClientOptions().AddBroker("tcp://43.156.130.245:1883")
opts.SetClientID("jyb_mqtt_2024")
opts.SetUsername("super") // 可选
opts.SetPassword("123455") // 可选
client := MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
token := client.Publish("YJIOT/YJLOCK/HOST/"+imei, 0, false, `{"head":{"method":"singleControl","msgId":"`+uuid.New().String()+`","ack":1},"body":{"action":1,"channel":`+index+`}}`)
token.Wait()