2017-01-26 03:19:15 +08:00
|
|
|
package mqtt
|
|
|
|
|
|
|
|
import "gobot.io/x/gobot"
|
|
|
|
|
2017-01-26 14:14:43 +08:00
|
|
|
const (
|
|
|
|
// Data event when data is available for Driver
|
|
|
|
Data = "data"
|
|
|
|
|
|
|
|
// Error event when error occurs in Driver
|
|
|
|
Error = "error"
|
|
|
|
)
|
|
|
|
|
2017-01-26 03:19:15 +08:00
|
|
|
// Driver for mqtt
|
|
|
|
type Driver struct {
|
|
|
|
name string
|
|
|
|
topic string
|
|
|
|
connection gobot.Connection
|
|
|
|
gobot.Eventer
|
|
|
|
gobot.Commander
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewDriver returns a new Gobot MQTT Driver
|
|
|
|
func NewDriver(a *Adaptor, topic string) *Driver {
|
|
|
|
m := &Driver{
|
2017-02-02 22:29:56 +08:00
|
|
|
name: gobot.DefaultName("MQTT"),
|
2017-01-26 03:19:15 +08:00
|
|
|
topic: topic,
|
|
|
|
connection: a,
|
|
|
|
Eventer: gobot.NewEventer(),
|
|
|
|
Commander: gobot.NewCommander(),
|
|
|
|
}
|
|
|
|
|
2017-02-02 22:29:56 +08:00
|
|
|
m.AddEvent(Data)
|
|
|
|
m.AddEvent(Error)
|
|
|
|
|
2017-01-26 03:19:15 +08:00
|
|
|
return m
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns name for the Driver
|
|
|
|
func (m *Driver) Name() string { return m.name }
|
|
|
|
|
|
|
|
// Name sets name for the Driver
|
|
|
|
func (m *Driver) SetName(name string) { m.name = name }
|
|
|
|
|
|
|
|
// Connection returns Connections used by the Driver
|
|
|
|
func (m *Driver) Connection() gobot.Connection {
|
|
|
|
return m.connection
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Driver) adaptor() *Adaptor {
|
|
|
|
return m.Connection().(*Adaptor)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start starts the Driver
|
|
|
|
func (m *Driver) Start() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Halt halts the Driver
|
|
|
|
func (m *Driver) Halt() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Topic returns the current topic for the Driver
|
|
|
|
func (m *Driver) Topic() string { return m.topic }
|
|
|
|
|
|
|
|
// SetTopic sets the current topic for the Driver
|
|
|
|
func (m *Driver) SetTopic(topic string) { m.topic = topic }
|
|
|
|
|
|
|
|
// Publish a message to the current device topic
|
2017-01-26 16:13:35 +08:00
|
|
|
func (m *Driver) Publish(data interface{}) bool {
|
|
|
|
message := data.([]byte)
|
2017-01-26 03:19:15 +08:00
|
|
|
return m.adaptor().Publish(m.topic, message)
|
|
|
|
}
|
|
|
|
|
2017-01-26 14:14:43 +08:00
|
|
|
// On subscribes to data updates for the current device topic,
|
|
|
|
// and then calls the message handler function when data is received
|
2017-04-19 01:49:17 +08:00
|
|
|
func (m *Driver) On(n string, f func(msg interface{})) error {
|
2017-01-26 16:13:35 +08:00
|
|
|
// TODO: also be able to subscribe to Error updates
|
2017-04-19 01:49:17 +08:00
|
|
|
f1 := func(msg Message) {
|
|
|
|
f(msg)
|
2017-01-26 16:13:35 +08:00
|
|
|
}
|
|
|
|
m.adaptor().On(m.topic, f1)
|
|
|
|
return nil
|
2017-01-26 03:19:15 +08:00
|
|
|
}
|