-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
256 lines (225 loc) · 6.47 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
// Craig Hesling
// November 12, 2017
//
// This is an OpenChirp service that makes an http request when a certain conditions are met.
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"github.com/Knetic/govaluate"
"github.com/openchirp/framework"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
const (
version string = "1.0"
)
const (
configExpression = "expr"
configValue = "value"
configMethod = "method"
configUri = "uri"
)
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
)
type Device struct {
expr *govaluate.EvaluableExpression
value *govaluate.EvaluableExpression
uri string
values map[string]interface{}
}
func NewDevice() framework.Device {
d := &Device{}
d.ResetValues()
return framework.Device(d)
}
func (d *Device) ResetValues() {
d.values = make(map[string]interface{})
}
func (d *Device) ProcessLink(ctrl *framework.DeviceControl) string {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debug("Linking with config:", ctrl.Config())
uri := ctrl.Config()[configUri]
exprStr := ctrl.Config()[configExpression]
valueStr := ctrl.Config()[configValue]
expr, err := govaluate.NewEvaluableExpression(exprStr)
if err != nil {
logitem.Warnf("Error parsing expr: %v", err)
return fmt.Sprint(err)
}
value, err := govaluate.NewEvaluableExpression(valueStr)
if err != nil {
logitem.Warnf("Error parsing value: %v", err)
return fmt.Sprint(err)
}
d.uri = uri
d.expr = expr
d.value = value
for _, v := range d.expr.Vars() {
subtopic := "transducer/" + v
ctrl.Subscribe(subtopic, v)
}
// for _, v := range d.value.Vars() {
// subtopic := "transducer/" + v
// ctrl.Subscribe(subtopic, -1)
// }
return "Success"
}
func (d *Device) ProcessUnlink(ctrl *framework.DeviceControl) {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debug("Unlinked:")
}
func (d *Device) ProcessConfigChange(ctrl *framework.DeviceControl, cchanges, coriginal map[string]string) (string, bool) {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debug("Processing Config Change:", cchanges)
return "", false
}
func (d *Device) ProcessMessage(ctrl *framework.DeviceControl, msg framework.Message) {
logitem := log.WithField("deviceid", ctrl.Id())
logitem.Debugf("Processing Message: %v: [ % #x ]", msg.Key(), msg.Payload())
value, err := strconv.ParseFloat(string(msg.Payload()), 64)
if err != nil {
log.Warnf("Failed to parse a float64 from %v: %v", string(msg.Payload()), err)
ctrl.Publish("transducer/err", fmt.Sprint(err))
return
}
d.values[msg.Key().(string)] = value
exprResult, err := d.expr.Evaluate(d.values)
if err != nil {
log.Warnf("Failed to evaluate %v with %v", d.value, d.values)
ctrl.Publish("transducer/err", fmt.Sprint(err))
return
}
if result, ok := exprResult.(bool); result && ok {
valueResult, err := d.value.Evaluate(d.values)
if err != nil {
log.Warnf("Failed to evaluate %v with %v", d.value, d.values)
ctrl.Publish("transducer/err", fmt.Sprint(err))
return
}
log.Debugf("Evaluated %v with %v = %v", d.value, d.values, valueResult)
ctrl.Publish("transducer/out", fmt.Sprint(valueResult))
// send POST request
if len(d.uri) > 0 {
log.Debug("Sending POST request")
req, err := http.NewRequest("POST", d.uri, strings.NewReader(fmt.Sprint(valueResult)))
if err != nil {
log.Warnf("Failed to send POST to %v with value %v", d.uri, valueResult)
ctrl.Publish("transducer/err", fmt.Sprint(err))
return
}
c := &http.Client{}
resp, err := c.Do(req)
if err != nil {
log.Warnf("Failed to send POST to %v with value %v", d.uri, valueResult)
ctrl.Publish("transducer/err", fmt.Sprint(err))
return
}
defer resp.Body.Close()
}
} else {
log.Debugf("Did not evaluate value because result=%v and ok=%v", result, ok)
}
}
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.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 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 signal channel */
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 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 = "example-service"
app.Usage = ""
app.Copyright = "See https://github.com/openchirp/example-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",
},
}
app.Run(os.Args)
}