-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
278 lines (245 loc) · 7.6 KB
/
main.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
// Craig Hesling
// October 17, 2017
//
// This is an example OpenChirp service. It sets up arguments and the main
// runtime event loop to process new device service links
package main
import (
"os"
"os/signal"
"strings"
"syscall"
"github.com/openchirp/framework"
"github.com/openchirp/framework/utils"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
const (
version string = "1.2"
)
const (
// Set this value to true to have the service publish a service status of
// "Running" each time it receives a device update event
//
// This could be used as a service alive pulse if enabled
// Otherwise, the service status will indicate "Started" at the time the
// service "Started" the client
runningStatus = true
)
/*
"serviceconfig": {
"rxconfig": "\"temp,sint32,1\", \"humidity,uint32,2\", \"light,uint32,3\", \"pir,uint32,4\", \"mic,uint32,5\", \"accX,uint32,6\", \"accY,uint32,7\", \"accZ,uint32,8\"",
"txconfig": "\"duty,uint32,9\""
}
OR
"serviceconfig": {
"rxconfig": ["temp,sint32,1", "humidity,uint32,2", "light,uint32,3", "pir,uint32,4", "mic,uint32,5", "accX,uint32,6", "accY,uint32,7", "accZ,uint32,8"],
"txconfig": ["duty,uint32,9"]
}
*/
type ServiceConfig struct {
RxData []string `json:"rxmap"`
TxData []string `json:"txmap"`
// should add a TXBuffering time
}
const (
deviceRxData = "rawrx"
deviceTxData = "rawtx"
rxConfigLabel = "rxconfig"
txConfigLabel = "txconfig"
)
func run(ctx *cli.Context) error {
/* Set logging level */
log.SetLevel(log.Level(uint32(ctx.Int("log-level"))))
log.Info("Starting Example Service ")
/* Start framework service client */
c, err := framework.StartServiceClientStatus(
ctx.String("framework-server"),
ctx.String("mqtt-server"),
ctx.String("service-id"),
ctx.String("service-token"),
"Unexpected disconnect!")
if err != nil {
log.Error("Failed to StartServiceClient: ", err)
return cli.NewExitError(nil, 1)
}
defer c.StopClient()
log.Info("Started service")
/* Post service status indicating I am starting */
err = c.SetStatus("Starting")
if err != nil {
log.Error("Failed to publish service status: ", err)
return cli.NewExitError(nil, 1)
}
log.Info("Published Service Status")
/* Setup master table of registered devices */
var devices = make(map[string]*Device)
/* Start service main device updates stream */
log.Info("Starting Device Updates Stream")
updates, err := c.StartDeviceUpdatesSimple()
if err != nil {
log.Error("Failed to start device updates stream: ", err)
return cli.NewExitError(nil, 1)
}
defer c.StopDeviceUpdates()
/* Setup signal channel */
log.Info("Processing device updates")
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
/* Post service status indicating I started */
err = c.SetStatus("Started")
if err != nil {
log.Error("Failed to publish service status: ", err)
return cli.NewExitError(nil, 1)
}
log.Info("Published Service Status")
for {
select {
case update := <-updates:
/* If runningStatus is set, post a service status as an alive msg */
if runningStatus {
err = c.SetStatus("Running")
if err != nil {
log.Error("Failed to publish service status: ", err)
return cli.NewExitError(nil, 1)
}
log.Info("Published Service Status")
}
logitem := log.WithFields(
log.Fields{"type": update.Type, "deviceid": update.Id},
)
switch update.Type {
case framework.DeviceUpdateTypeRem:
logitem.Info("Removing device with id ", update.Id, " and config ", update.Config)
d, ok := devices[update.Id]
if !ok {
logitem.Errorf("Asked to remove device %s that was not registered", update.Id)
continue
}
err = d.Deregister(c)
if err != nil {
logitem.Errorf("Failed to deregister Device %s: %v", d.ID, err)
}
delete(devices, d.ID)
case framework.DeviceUpdateTypeUpd:
logitem.Info("Removing device for update with id", update.Id, " and config ", update.Config)
d, ok := devices[update.Id]
if !ok {
logitem.Errorf("Asked to remove device %s that was not registered", update.Id)
} else {
err = d.Deregister(c)
if err != nil {
logitem.Errorf("Failed to deregister Device %s: %v", d.ID, err)
}
delete(devices, d.ID)
}
fallthrough
case framework.DeviceUpdateTypeAdd:
logitem.Info("Adding device")
// var dev rest.ServiceDeviceListItem
// dev.Id = event.Id
// dev.Config = event.Config
var config ServiceConfig
/* Extract rx and tx configs */
rx := update.Config[rxConfigLabel]
if rx == "" {
logitem.Warnf("Device %s did not specify an %s", update.Id, rxConfigLabel)
}
tx := update.Config[txConfigLabel]
if tx == "" {
logitem.Warnf("Device %s did not specify an %s", update.Id, txConfigLabel)
}
/* For compatibility, allow configs to be encased in [] and whitespace */
const cutset = " \t\n[]"
rx = strings.Trim(rx, cutset)
tx = strings.Trim(tx, cutset)
/* Parse rxconfig and txconfig */
config.RxData, err = utils.ParseCSVConfig(rx)
if err != nil {
logitem.Warnf("Error parsing %s for device with ID %s", rxConfigLabel, update.Id)
c.SetDeviceStatus(update.Id, "Failed to parse "+rxConfigLabel+" as CSV")
continue // ignore device
}
config.TxData, err = utils.ParseCSVConfig(tx)
if err != nil {
logitem.Warnf("Error parsing %s for device with ID %s", txConfigLabel, update.Id)
c.SetDeviceStatus(update.Id, "Failed to parse "+txConfigLabel+" as CSV")
continue // ignore device
}
/* Lookup full device info */
fulldev, err := c.FetchDeviceInfo(update.Id)
if err != nil {
logitem.Warnf("Error fetching device info for device with ID %s", update.Id)
continue // ignore device
}
/* Build Two-Way FieldID-Name Map */
d := NewDevice(fulldev.NodeDescriptor)
err = d.SetMapping(config)
if err != nil {
logitem.Warnf("Error setting map for Device %s: %v", update.Id, err)
c.SetDeviceStatus(update.Id, "Failed to set mapping: "+err.Error())
continue
}
logitem.Info("Registering device ", update.Id)
err = d.Register(c)
if err != nil {
logitem.Warnf("Error registering Device %s: %v", update.Id, err)
c.SetDeviceStatus(update.Id, "Failed to set register: "+err.Error())
continue
}
devices[fulldev.NodeDescriptor.ID] = d
c.SetDeviceStatus(update.Id, "Success")
}
case sig := <-signals:
log.WithField("signal", sig).Info("Received signal")
goto cleanup
}
}
cleanup:
log.Warning("Shutting down")
err = c.SetStatus("Shutting down")
if err != nil {
log.Error("Failed to publish service status: ", err)
}
log.Info("Published service status")
return nil
}
func main() {
app := cli.NewApp()
app.Name = "easybits-service"
app.Usage = ""
app.Copyright = "See https://github.com/openchirp/easybits-service for copyright information"
app.Version = version
app.Action = run
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "framework-server",
Usage: "OpenChirp framework server's URI",
Value: "http://localhost:7000",
EnvVar: "FRAMEWORK_SERVER",
},
cli.StringFlag{
Name: "mqtt-server",
Usage: "MQTT server's URI (e.g. scheme://host:port where scheme is tcp or tls)",
Value: "tcp://localhost:1883",
EnvVar: "MQTT_SERVER",
},
cli.StringFlag{
Name: "service-id",
Usage: "OpenChirp service id",
EnvVar: "SERVICE_ID",
},
cli.StringFlag{
Name: "service-token",
Usage: "OpenChirp service token",
EnvVar: "SERVICE_TOKEN",
},
cli.IntFlag{
Name: "log-level",
Value: 4,
Usage: "debug=5, info=4, warning=3, error=2, fatal=1, panic=0",
EnvVar: "LOG_LEVEL",
},
}
app.Run(os.Args)
}