-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
mqtt_driver.go
86 lines (69 loc) · 1.91 KB
/
mqtt_driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package mqtt
import "gobot.io/x/gobot/v2"
const (
// Data event when data is available for Driver
Data = "data"
// Error event when error occurs in Driver
Error = "error"
)
// 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{
name: gobot.DefaultName("MQTT"),
topic: topic,
connection: a,
Eventer: gobot.NewEventer(),
Commander: gobot.NewCommander(),
}
m.AddEvent(Data)
m.AddEvent(Error)
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 {
//nolint:forcetypeassert // ok here
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
func (m *Driver) Publish(data interface{}) bool {
//nolint:forcetypeassert // ok here
message := data.([]byte)
return m.adaptor().Publish(m.topic, message)
}
// On subscribes to data updates for the current device topic,
// and then calls the message handler function when data is received
func (m *Driver) On(n string, f func(msg interface{})) error {
// TODO: also be able to subscribe to Error updates
f1 := func(msg Message) {
f(msg)
}
m.adaptor().On(m.topic, f1)
return nil
}