gobot.io/x/gobot/platforms/mqtt
程序员文章站
2022-07-14 22:48:48
...
package main
import (
"gobot.io/x/gobot"
"gobot.io/x/gobot/platforms/mqtt"
"fmt"
"time"
)
func main() {
mqttAdaptor := mqtt.NewAdaptor("tcp://0.0.0.0:1883", "pinger")
work := func() {
mqttAdaptor.On("hello", func(msg mqtt.Message) {
fmt.Println(msg)
})
mqttAdaptor.On("hola", func(msg mqtt.Message) {
fmt.Println(msg)
})
data := []byte("o")
gobot.Every(1*time.Second, func() {
mqttAdaptor.Publish("hello", data)
})
gobot.Every(5*time.Second, func() {
mqttAdaptor.Publish("hola", data)
})
}
robot := gobot.NewRobot("mqttBot",
[]gobot.Connection{mqttAdaptor},
work,
)
robot.Start()
}
使用 mqttAdaptor.Publish可以发送消息 mqttAdaptor.On 可以订阅消息,如果有用户验证可以使用如下方式:
mqttAdaptor = mqtt.NewAdaptorWithAuth(
"EMQ.host",
"EMQ.clientID",
"EMQ.userName",
"EMQ.passWordActive",
)
断开也可以配置重连规则自动重连(默认未开启,作为服务端强烈建议开启)
mqttAdaptor.SetAutoReconnect(true)
以及消息清理机制(默认断开连接清理消息)
mqttAdaptor.SetCleanSession(false)
也可以指定使用TLS证书连接
mqttAdaptor.SetUseSSL(true)
# 下面可以指定证书(如果EMQ使用了标准的CA证书下面就不用配置了)
mqttAdaptor.SetClientKey(`/client/client-key.pem`)
mqttAdaptor.SetClientCert(`/client/client-cert.pem`)
import (
"gobot.io/x/gobot"
"gobot.io/x/gobot/platforms/mqtt"
"fmt"
"time"
)
func main() {
mqttAdaptor := mqtt.NewAdaptor("tcp://0.0.0.0:1883", "pinger")
work := func() {
mqttAdaptor.On("hello", func(msg mqtt.Message) {
fmt.Println(msg)
})
mqttAdaptor.On("hola", func(msg mqtt.Message) {
fmt.Println(msg)
})
data := []byte("o")
gobot.Every(1*time.Second, func() {
mqttAdaptor.Publish("hello", data)
})
gobot.Every(5*time.Second, func() {
mqttAdaptor.Publish("hola", data)
})
}
robot := gobot.NewRobot("mqttBot",
[]gobot.Connection{mqttAdaptor},
work,
)
robot.Start()
}
使用 mqttAdaptor.Publish可以发送消息 mqttAdaptor.On 可以订阅消息,如果有用户验证可以使用如下方式:
mqttAdaptor = mqtt.NewAdaptorWithAuth(
"EMQ.host",
"EMQ.clientID",
"EMQ.userName",
"EMQ.passWordActive",
)
断开也可以配置重连规则自动重连(默认未开启,作为服务端强烈建议开启)
mqttAdaptor.SetAutoReconnect(true)
以及消息清理机制(默认断开连接清理消息)
mqttAdaptor.SetCleanSession(false)
也可以指定使用TLS证书连接
mqttAdaptor.SetUseSSL(true)
# 下面可以指定证书(如果EMQ使用了标准的CA证书下面就不用配置了)
mqttAdaptor.SetClientKey(`/client/client-key.pem`)
mqttAdaptor.SetClientCert(`/client/client-cert.pem`)