-
Notifications
You must be signed in to change notification settings - Fork 80
/
homie.go
282 lines (231 loc) · 7 KB
/
homie.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package server
import (
"fmt"
"log"
"sort"
"strings"
"sync"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/volkszaehler/mbmd/meters"
)
const (
specVersion = "4.0"
nodeTopic = "meter"
timeout = 500 * time.Millisecond
)
// HomieRunner publishes query results as homie mqtt topics
type HomieRunner struct {
options *MQTT.ClientOptions
qos byte
verbose bool
rootTopic string
qe DeviceInfo
cc <-chan ControlSnip
meters map[string]*homieMeter
}
type homieMeter struct {
*MqttClient
rootTopic string
meter string
online bool
observed map[meters.Measurement]bool
}
// NewHomieRunner create new runner for homie IoT spec
func NewHomieRunner(qe DeviceInfo, cc <-chan ControlSnip, options *MQTT.ClientOptions, qos byte, rootTopic string, verbose bool) *HomieRunner {
hr := &HomieRunner{
options: options,
qos: qos,
verbose: verbose,
rootTopic: rootTopic,
qe: qe,
cc: cc,
meters: make(map[string]*homieMeter),
}
return hr
}
// cloneOptions creates a copy of the relevant mqtt options
func (hr *HomieRunner) cloneOptions() *MQTT.ClientOptions {
opt := MQTT.NewClientOptions()
opt.SetUsername(hr.options.Username)
opt.SetPassword(hr.options.Password)
opt.SetClientID(hr.options.ClientID)
opt.SetCleanSession(hr.options.CleanSession)
opt.SetAutoReconnect(hr.options.AutoReconnect)
for _, b := range hr.options.Servers {
opt.AddBroker(b.String())
}
return opt
}
// Run MQTT client publisher
func (hr *HomieRunner) Run(in <-chan QuerySnip) {
defer hr.unregister() // cleanup topics
for {
select {
case snip, chanOpen := <-in:
if !chanOpen {
return // channel closed
}
meter, ok := hr.meters[snip.Device]
if !ok {
meter = hr.createMeter(snip)
}
// publish actual message
meter.publishMessage(snip)
case snip := <-hr.cc:
if meter, ok := hr.meters[snip.Device]; ok {
meter.status(snip.Status.Online)
}
}
}
}
// createMeter creates new homie device
func (hr *HomieRunner) createMeter(snip QuerySnip) *homieMeter {
// new client with unique id
options := hr.cloneOptions()
clientID := fmt.Sprintf("%s-%s", options.ClientID, mqttDeviceTopic(snip.Device))
options.SetClientID(clientID)
lwt := fmt.Sprintf("%s/%s/$state", hr.rootTopic, mqttDeviceTopic(snip.Device))
options.SetWill(lwt, "lost", hr.qos, true)
client := NewMqttClient(options, hr.qos, hr.verbose)
// add meter and publish
meter := newHomieMeter(client, hr.rootTopic, snip.Device)
hr.meters[snip.Device] = meter
d := hr.qe.DeviceDescriptorByID(snip.Device)
meter.publishMeter(d)
return meter
}
// unregister unpublishes device information
func (hr *HomieRunner) unregister() {
for _, meter := range hr.meters {
meter.unregister()
}
}
// newHomieMeter creates meter on given mqtt client
func newHomieMeter(client *MqttClient, rootTopic string, meter string) *homieMeter {
hm := &homieMeter{
MqttClient: client,
rootTopic: rootTopic,
meter: meter,
observed: make(map[meters.Measurement]bool),
}
return hm
}
// unregister clears meter's retained messages
func (hr *homieMeter) unregister() {
subTopic := mqttDeviceTopic(hr.meter)
hr.publish(subTopic+"/$state", "disconnected")
hr.MqttClient.Client.Disconnect(uint(timeout.Milliseconds()))
}
func (hr *homieMeter) publishMeter(descriptor meters.DeviceDescriptor) {
subTopic := mqttDeviceTopic(hr.meter)
// device
hr.publish(subTopic+"/$homie", specVersion)
hr.publish(subTopic+"/$name", hr.meter)
hr.publish(subTopic+"/$state", "init")
hr.publish(subTopic+"/$implementation", "MBMD")
// node
hr.publish(subTopic+"/$nodes", nodeTopic)
hr.unpublish(subTopic, nodeTopic, "$homie", "$name", "$state", "$nodes")
subTopic = fmt.Sprintf("%s/%s", subTopic, nodeTopic)
hr.publish(subTopic+"/$name", descriptor.Manufacturer)
hr.publish(subTopic+"/$type", descriptor.Model)
}
// status updates a meter's $state attibute when its online status changes
func (hr *homieMeter) status(online bool) {
if hr.online != online {
subTopic := mqttDeviceTopic(hr.meter)
msg := "alert"
if online {
msg = "ready"
}
hr.publish(subTopic+"/$state", msg)
hr.online = online
}
}
func (hr *homieMeter) publishMessage(snip QuerySnip) {
// make sure property is published before publishing data
if _, ok := hr.observed[snip.Measurement]; !ok {
hr.observed[snip.Measurement] = true
hr.publishProperties()
}
// publish data
topic := fmt.Sprintf("%s/%s/%s/%s",
hr.rootTopic,
mqttDeviceTopic(snip.Device),
nodeTopic,
strings.ToLower(snip.Measurement.String()),
)
message := fmt.Sprintf("%.3f", snip.Value)
go hr.Publish(topic, false, message)
}
func (hr *homieMeter) publishProperties() {
subtopic := fmt.Sprintf("%s/%s", mqttDeviceTopic(hr.meter), nodeTopic)
measurements := make([]meters.Measurement, 0)
for k := range hr.observed {
measurements = append(measurements, k)
}
// sort by measurement type
sort.Slice(measurements, func(a, b int) bool {
return measurements[a].String() < measurements[b].String()
})
properties := make([]string, len(measurements))
for i, m := range measurements {
property := strings.ToLower(m.String())
properties[i] = property
description, unit := m.DescriptionAndUnit()
propertySubtopic := fmt.Sprintf("%s/%s", subtopic, property)
hr.publish(propertySubtopic+"/$name", description)
hr.publish(propertySubtopic+"/$unit", unit)
hr.publish(propertySubtopic+"/$datatype", "float")
}
hr.publish(subtopic+"/$properties", strings.Join(properties, ","))
// unpublish remains attributes if any
exceptions := []string{"$name", "$unit", "$datatype", "$properties"}
exceptions = append(exceptions, properties...)
hr.unpublish(subtopic, exceptions...)
}
func (hr *homieMeter) publish(subtopic string, message string) {
topic := hr.rootTopic + "/" + subtopic
hr.Publish(topic, true, message)
}
// unpublish retained message hierarchy
func (hr *homieMeter) unpublish(subtopic string, exceptions ...string) {
topic := fmt.Sprintf("%s/%s/#", hr.rootTopic, subtopic)
if hr.verbose {
log.Printf("mqtt: unpublish %s", topic)
}
var mux sync.Mutex
tokens := make([]MQTT.Token, 0)
mux.Lock()
tokens = append(tokens, hr.Client.Subscribe(topic, hr.qos, func(c MQTT.Client, msg MQTT.Message) {
if len(msg.Payload()) == 0 {
return // ignore received unpublish messages
}
topic := msg.Topic()
// don't unpublish if in exception list
for _, exception := range exceptions {
exceptionTopic := fmt.Sprintf("%s/%s/%s", hr.rootTopic, subtopic, exception)
if topic == exceptionTopic || strings.HasPrefix(topic, exceptionTopic+"/") {
// log.Printf("unpublish %s -> retain (%s)", topic, exception)
return
}
}
// log.Printf("unpublish %s", topic)
token := hr.Client.Publish(topic, hr.qos, true, []byte{})
mux.Lock()
defer mux.Unlock()
tokens = append(tokens, token)
}))
mux.Unlock()
// wait for timeout according to specification
<-time.After(timeout)
mux.Lock()
defer mux.Unlock()
// stop listening
hr.Client.Unsubscribe(topic)
// wait for tokens
for _, token := range tokens {
hr.WaitForToken(token)
}
}