gobot.io/x/gobot/v2@v2.1.0/examples/mqtt_driver_ping.go (about)

     1  //go:build example
     2  // +build example
     3  
     4  //
     5  // Do not build by default.
     6  
     7  // TO RUN:
     8  //
     9  //	go run ./examples/mqtt_driver_ping.go <SERVER>
    10  //
    11  // EXAMPLE:
    12  //
    13  //	go run ./examples/mqtt_driver_ping.go ssl://iot.eclipse.org:8883
    14  package main
    15  
    16  import (
    17  	"fmt"
    18  	"os"
    19  	"time"
    20  
    21  	"gobot.io/x/gobot/v2"
    22  	"gobot.io/x/gobot/v2/platforms/mqtt"
    23  )
    24  
    25  func main() {
    26  	mqttAdaptor := mqtt.NewAdaptor(os.Args[1], "pinger")
    27  	mqttAdaptor.SetAutoReconnect(true)
    28  
    29  	holaDriver := mqtt.NewDriver(mqttAdaptor, "hola")
    30  	helloDriver := mqtt.NewDriver(mqttAdaptor, "hello")
    31  
    32  	work := func() {
    33  		helloDriver.On(mqtt.Data, func(data interface{}) {
    34  			fmt.Println("hello")
    35  		})
    36  
    37  		holaDriver.On(mqtt.Data, func(data interface{}) {
    38  			fmt.Println("hola")
    39  		})
    40  
    41  		data := []byte("o")
    42  		gobot.Every(1*time.Second, func() {
    43  			helloDriver.Publish(data)
    44  		})
    45  
    46  		gobot.Every(5*time.Second, func() {
    47  			holaDriver.Publish(data)
    48  		})
    49  	}
    50  
    51  	robot := gobot.NewRobot("mqttBot",
    52  		[]gobot.Connection{mqttAdaptor},
    53  		[]gobot.Device{helloDriver, holaDriver},
    54  		work,
    55  	)
    56  
    57  	robot.Start()
    58  }