hybridgroup.gobot/examples/mqtt_ping.go

45 lines
774 B
Go

//go:build example
// +build example
//
// Do not build by default.
package main
import (
"fmt"
"time"
"gobot.io/x/gobot/v2"
"gobot.io/x/gobot/v2/platforms/mqtt"
)
func main() {
mqttAdaptor := mqtt.NewAdaptor("tcp://test.mosquitto.org:1883", "pinger")
work := func() {
_ = mqttAdaptor.On("hello", func(msg mqtt.Message) {
fmt.Println("hello")
})
_ = mqttAdaptor.On("hola", func(msg mqtt.Message) {
fmt.Println("hola")
})
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,
)
if err := robot.Start(); err != nil {
panic(err)
}
}