gobot.io/x/gobot/v2@v2.1.0/platforms/mqtt/mqtt_driver.go (about)

     1  package mqtt
     2  
     3  import "gobot.io/x/gobot/v2"
     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 mqtt
    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 MQTT Driver
    23  func NewDriver(a *Adaptor, topic string) *Driver {
    24  	m := &Driver{
    25  		name:       gobot.DefaultName("MQTT"),
    26  		topic:      topic,
    27  		connection: a,
    28  		Eventer:    gobot.NewEventer(),
    29  		Commander:  gobot.NewCommander(),
    30  	}
    31  
    32  	m.AddEvent(Data)
    33  	m.AddEvent(Error)
    34  
    35  	return m
    36  }
    37  
    38  // Name returns name for the Driver
    39  func (m *Driver) Name() string { return m.name }
    40  
    41  // Name sets name for the Driver
    42  func (m *Driver) SetName(name string) { m.name = name }
    43  
    44  // Connection returns Connections used by the Driver
    45  func (m *Driver) Connection() gobot.Connection {
    46  	return m.connection
    47  }
    48  
    49  func (m *Driver) adaptor() *Adaptor {
    50  	return m.Connection().(*Adaptor)
    51  }
    52  
    53  // Start starts the Driver
    54  func (m *Driver) Start() error {
    55  	return nil
    56  }
    57  
    58  // Halt halts the Driver
    59  func (m *Driver) Halt() error {
    60  	return nil
    61  }
    62  
    63  // Topic returns the current topic for the Driver
    64  func (m *Driver) Topic() string { return m.topic }
    65  
    66  // SetTopic sets the current topic for the Driver
    67  func (m *Driver) SetTopic(topic string) { m.topic = topic }
    68  
    69  // Publish a message to the current device topic
    70  func (m *Driver) Publish(data interface{}) bool {
    71  	message := data.([]byte)
    72  	return m.adaptor().Publish(m.topic, message)
    73  }
    74  
    75  // On subscribes to data updates for the current device topic,
    76  // and then calls the message handler function when data is received
    77  func (m *Driver) On(n string, f func(msg interface{})) error {
    78  	// TODO: also be able to subscribe to Error updates
    79  	f1 := func(msg Message) {
    80  		f(msg)
    81  	}
    82  	m.adaptor().On(m.topic, f1)
    83  	return nil
    84  }