-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
303 lines (263 loc) · 8.4 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Craig Hesling
// May 25, 2018
//
// This is a simple OpenChirp service that outputs the windoed running average
// of a data stream.
//
// The decision has been made to allow producing startup averages with less than
// the specified window size, in order to always give the user output.
// The alternative approach would be to wait to the window to become full
// before we could generate our first average.
package main
import (
"math"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"github.com/openchirp/framework"
"github.com/openchirp/framework/rest"
"github.com/openchirp/framework/utils"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
const (
version string = "1.0"
)
const (
configKeyInputTopics = "InputTopics"
configKeyOutputTopics = "OutputTopics"
configWindowsSizes = "WindowSizes"
)
var configParams = []rest.ServiceConfigParameter{
rest.ServiceConfigParameter{
Name: configKeyInputTopics,
Description: "Comma separated list of input topics",
Example: "frequency, temp",
Required: true,
},
rest.ServiceConfigParameter{
Name: configKeyOutputTopics,
Description: "Comma separated list of corresponding output topics",
Example: "frequency_avg, temp_avg",
Required: false,
},
rest.ServiceConfigParameter{
Name: configWindowsSizes,
Description: "Comma separated list of corresponding window sizes",
Example: "2, 4",
Required: false,
},
}
const (
defaultWindowSize = 2
defaultOutputTopicSuffix = "_avg"
)
const (
// Set this value to true to have the service publish a service status of
// "Running" each time it receives a device update event
runningStatus = true
)
func commaList(str string) []string {
nospacestr := strings.Replace(str, " ", "", -1)
elements := strings.Split(nospacestr, ",")
if len(elements) == 1 && len(elements[0]) == 0 {
return []string{}
}
return elements
}
// Device holds the device specific last values and target topics for the difference.
type Device struct {
outtopics []string
lastvalues [][]float64
nextindex []int
}
// NewDevice is called by the framework when a new device has been linked.
func NewDevice() framework.Device {
d := new(Device)
return framework.Device(d)
}
func (d *Device) addLastValue(topicIndex int, value float64) {
nextIndex := d.nextindex[topicIndex]
d.lastvalues[topicIndex][nextIndex] = value
d.nextindex[topicIndex] = (nextIndex + 1) % len(d.lastvalues[topicIndex])
}
// calculateAverage will compute the average of lastvalues avaliable.
// This means that it may generate a startup average with less values than
// the specified window size.
func (d *Device) calculateAverage(topicIndex int) float64 {
var count = len(d.lastvalues[topicIndex])
var sum float64
for _, val := range d.lastvalues[topicIndex] {
if math.IsNaN(val) {
count--
continue
}
sum += val
}
return sum / float64(count)
}
// ProcessLink is called once, during the initial setup of a
// device, and is provided the service config for the linking device.
func (d *Device) ProcessLink(ctrl *framework.DeviceControl) string {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debug("Linking with config:", ctrl.Config())
// Allows space in comma seperated list
inputTopics := commaList(ctrl.Config()[configKeyInputTopics])
outputTopics := commaList(ctrl.Config()[configKeyOutputTopics])
windowSizes := commaList(ctrl.Config()[configWindowsSizes])
d.outtopics = make([]string, len(inputTopics))
d.lastvalues = make([][]float64, len(inputTopics))
d.nextindex = make([]int, len(inputTopics))
for i, intopic := range inputTopics {
var outtopic string
if i < len(outputTopics) {
outtopic = outputTopics[i]
} else {
// if no putput topic specified, simply append a _diff to the topic
outtopic = intopic + defaultOutputTopicSuffix
}
d.outtopics[i] = outtopic
var winsize int = defaultWindowSize
if i < len(windowSizes) {
val, err := strconv.ParseInt(windowSizes[i], 10, 32)
if err != nil {
logitem.Warnf("Failed to parse WindowSize. Given \"%s\".", windowSizes[i])
return "Failed to parse WindowSize"
}
if val > 0 {
winsize = int(val)
}
}
d.lastvalues[i] = make([]float64, winsize)
// Initialize to to NaN
for vali := range d.lastvalues[i] {
d.lastvalues[i][vali] = math.NaN()
}
ctrl.Subscribe(intopic, i)
}
logitem.Debug("Finished Linking")
// This message is sent to the service status for the linking device
return "Success"
}
// ProcessUnlink is called once, when the service has been unlinked from
// the device.
func (d *Device) ProcessUnlink(ctrl *framework.DeviceControl) {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debug("Unlinked:")
}
// ProcessConfigChange is ignored in this case.
func (d *Device) ProcessConfigChange(ctrl *framework.DeviceControl, cchanges, coriginal map[string]string) (string, bool) {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debug("Ignoring Config Change:", cchanges)
return "", false
}
// ProcessMessage is called upon receiving a pubsub message destined for
// this device.
func (d *Device) ProcessMessage(ctrl *framework.DeviceControl, msg framework.Message) {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debugf("Processing avg for topic %s", msg.Topic())
index := msg.Key().(int)
value, err := strconv.ParseFloat(string(msg.Payload()), 64)
if err != nil {
logitem.Warnf("Failed to convert message (\"%v\") to float64", string(msg.Payload()))
return
}
d.addLastValue(index, value)
avg := d.calculateAverage(index)
logitem.Debugf("newvalue=%s | avg=%s", utils.FormatFloat64(value), utils.FormatFloat64(avg))
ctrl.Publish(d.outtopics[index], utils.FormatFloat64(avg))
}
// run is the main function that gets called once form main()
func run(ctx *cli.Context) error {
/* Set logging level (verbosity) */
log.SetLevel(log.Level(uint32(ctx.Int("log-level"))))
log.Info("Starting Math Avg Service")
/* Start framework service client */
c, err := framework.StartServiceClientManaged(
ctx.String("framework-server"),
ctx.String("mqtt-server"),
ctx.String("service-id"),
ctx.String("service-token"),
"Unexpected disconnect!",
NewDevice)
if err != nil {
log.Error("Failed to StartServiceClient: ", err)
return cli.NewExitError(nil, 1)
}
defer c.StopClient()
log.Info("Started service")
/* Post service's global status */
if err := c.SetStatus("Starting"); err != nil {
log.Error("Failed to publish service status: ", err)
return cli.NewExitError(nil, 1)
}
log.Info("Published Service Status")
/* Updating device config parameters */
if err := c.UpdateConfigParameters(configParams); err != nil {
log.Error("Failed to update service config parameters: ", err)
return cli.NewExitError(nil, 1)
}
log.Info("Updated Service Config Parameters")
/* Setup signal channel */
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
/* Post service status indicating I started */
if err := c.SetStatus("Started"); err != nil {
log.Error("Failed to publish service status: ", err)
return cli.NewExitError(nil, 1)
}
log.Info("Published Service Status")
/* Wait on a signal */
sig := <-signals
log.Info("Received signal ", sig)
log.Warning("Shutting down")
/* Post service's global status */
if err := c.SetStatus("Shutting down"); err != nil {
log.Error("Failed to publish service status: ", err)
}
log.Info("Published service status")
return nil
}
func main() {
/* Parse arguments and environmental variable */
app := cli.NewApp()
app.Name = "math-avg-service"
app.Usage = ""
app.Copyright = "See https://github.com/openchirp/math-avg-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: "tls://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",
},
}
/* Launch the application */
app.Run(os.Args)
}