gobot.io/x/gobot@v1.16.0/platforms/nats/nats_driver.go (about)

     1  package nats
     2  
     3  import "gobot.io/x/gobot"
     4  
     5  const (
     6  	// Data event when data is available for Driver
     7  	Data = "data"
     8  
     9  	// Error event when error occurs in Driver
    10  	Error = "error"
    11  )
    12  
    13  // Driver for NATS
    14  type Driver struct {
    15  	name       string
    16  	topic      string
    17  	connection gobot.Connection
    18  	gobot.Eventer
    19  	gobot.Commander
    20  }
    21  
    22  // NewDriver returns a new Gobot NATS Driver
    23  func NewDriver(a *Adaptor, topic string) *Driver {
    24  	m := &Driver{
    25  		name:       gobot.DefaultName("NATS"),
    26  		topic:      topic,
    27  		connection: a,
    28  		Eventer:    gobot.NewEventer(),
    29  		Commander:  gobot.NewCommander(),
    30  	}
    31  
    32  	return m
    33  }
    34  
    35  // Name returns name for the Driver
    36  func (m *Driver) Name() string { return m.name }
    37  
    38  // SetName sets name for the Driver
    39  func (m *Driver) SetName(name string) { m.name = name }
    40  
    41  // Connection returns Connections used by the Driver
    42  func (m *Driver) Connection() gobot.Connection {
    43  	return m.connection
    44  }
    45  
    46  func (m *Driver) adaptor() *Adaptor {
    47  	return m.Connection().(*Adaptor)
    48  }
    49  
    50  // Start starts the Driver
    51  func (m *Driver) Start() error {
    52  	return nil
    53  }
    54  
    55  // Halt halts the Driver
    56  func (m *Driver) Halt() error {
    57  	return nil
    58  }
    59  
    60  // Topic returns the current topic for the Driver
    61  func (m *Driver) Topic() string { return m.topic }
    62  
    63  // SetTopic sets the current topic for the Driver
    64  func (m *Driver) SetTopic(topic string) { m.topic = topic }
    65  
    66  // Publish a message to the current device topic
    67  func (m *Driver) Publish(data interface{}) bool {
    68  	message := data.([]byte)
    69  	return m.adaptor().Publish(m.topic, message)
    70  }
    71  
    72  // On subscribes to data updates for the current device topic,
    73  // and then calls the message handler function when data is received
    74  func (m *Driver) On(n string, f func(msg Message)) error {
    75  	// TODO: also be able to subscribe to Error updates
    76  	m.adaptor().On(m.topic, f)
    77  	return nil
    78  }