gobot.io/x/gobot/v2@v2.1.0/examples/nats_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/nats_driver_ping.go <SERVER>
    10  //
    11  // EXAMPLE:
    12  //
    13  //	go run ./examples/nats_driver_ping.go tls://nats.demo.io:4443
    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/nats"
    23  )
    24  
    25  func main() {
    26  	natsAdaptor := nats.NewAdaptor(os.Args[1], 1234)
    27  
    28  	holaDriver := nats.NewDriver(natsAdaptor, "hola")
    29  	helloDriver := nats.NewDriver(natsAdaptor, "hello")
    30  
    31  	work := func() {
    32  		helloDriver.On(nats.Data, func(msg nats.Message) {
    33  			fmt.Println("hello")
    34  		})
    35  
    36  		holaDriver.On(nats.Data, func(msg nats.Message) {
    37  			fmt.Println("hola")
    38  		})
    39  
    40  		data := []byte("o")
    41  		gobot.Every(1*time.Second, func() {
    42  			helloDriver.Publish(data)
    43  		})
    44  
    45  		gobot.Every(5*time.Second, func() {
    46  			holaDriver.Publish(data)
    47  		})
    48  	}
    49  
    50  	robot := gobot.NewRobot("natsBot",
    51  		[]gobot.Connection{natsAdaptor},
    52  		[]gobot.Device{helloDriver, holaDriver},
    53  		work,
    54  	)
    55  
    56  	robot.Start()
    57  }