2023-05-20 20:25:21 +08:00
|
|
|
//go:build example
|
2017-03-13 23:01:39 +08:00
|
|
|
// +build example
|
2023-05-20 20:25:21 +08:00
|
|
|
|
2017-03-13 23:01:39 +08:00
|
|
|
//
|
|
|
|
// Do not build by default.
|
|
|
|
|
2017-01-27 02:03:32 +08:00
|
|
|
// TO RUN:
|
2023-05-20 20:25:21 +08:00
|
|
|
//
|
|
|
|
// go run ./examples/mqtt_driver_ping.go <SERVER>
|
2017-02-01 04:14:09 +08:00
|
|
|
//
|
|
|
|
// EXAMPLE:
|
|
|
|
//
|
2023-05-20 20:25:21 +08:00
|
|
|
// go run ./examples/mqtt_driver_ping.go ssl://iot.eclipse.org:8883
|
2017-01-26 03:19:15 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2017-01-27 02:03:32 +08:00
|
|
|
"os"
|
2017-01-26 03:19:15 +08:00
|
|
|
"time"
|
|
|
|
|
2023-05-20 20:25:21 +08:00
|
|
|
"gobot.io/x/gobot/v2"
|
|
|
|
"gobot.io/x/gobot/v2/platforms/mqtt"
|
2017-01-26 03:19:15 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
2017-01-27 02:03:32 +08:00
|
|
|
mqttAdaptor := mqtt.NewAdaptor(os.Args[1], "pinger")
|
2017-01-26 23:21:28 +08:00
|
|
|
mqttAdaptor.SetAutoReconnect(true)
|
|
|
|
|
2017-01-26 03:19:15 +08:00
|
|
|
holaDriver := mqtt.NewDriver(mqttAdaptor, "hola")
|
|
|
|
helloDriver := mqtt.NewDriver(mqttAdaptor, "hello")
|
|
|
|
|
|
|
|
work := func() {
|
2024-02-11 22:34:50 +08:00
|
|
|
_ = helloDriver.On(mqtt.Data, func(data interface{}) {
|
2017-01-26 03:19:15 +08:00
|
|
|
fmt.Println("hello")
|
|
|
|
})
|
|
|
|
|
2024-02-11 22:34:50 +08:00
|
|
|
_ = holaDriver.On(mqtt.Data, func(data interface{}) {
|
2017-01-26 03:19:15 +08:00
|
|
|
fmt.Println("hola")
|
|
|
|
})
|
|
|
|
|
|
|
|
data := []byte("o")
|
|
|
|
gobot.Every(1*time.Second, func() {
|
|
|
|
helloDriver.Publish(data)
|
|
|
|
})
|
|
|
|
|
|
|
|
gobot.Every(5*time.Second, func() {
|
|
|
|
holaDriver.Publish(data)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
robot := gobot.NewRobot("mqttBot",
|
|
|
|
[]gobot.Connection{mqttAdaptor},
|
2017-04-04 19:38:51 +08:00
|
|
|
[]gobot.Device{helloDriver, holaDriver},
|
2017-01-26 03:19:15 +08:00
|
|
|
work,
|
|
|
|
)
|
|
|
|
|
2024-02-11 22:34:50 +08:00
|
|
|
if err := robot.Start(); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2017-01-26 03:19:15 +08:00
|
|
|
}
|