-
-
Notifications
You must be signed in to change notification settings - Fork 325
/
influxdb_handler.go
451 lines (377 loc) · 10.8 KB
/
influxdb_handler.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// Package influxdbhandler implements a InfluxDB handler
package influxdbhandler
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"github.com/mmcloughlin/geohash"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/brocaar/lora-app-server/internal/handler"
)
var precisionValidator = regexp.MustCompile(`^(ns|u|ms|s|m|h)$`)
// HandlerConfig contains the configuration for a InfluxDB handler.
type HandlerConfig struct {
Endpoint string `json:"endpoint"`
DB string `json:"db"`
Username string `json:"username"`
Password string `json:"password"`
RetentionPolicyName string `json:"retentionPolicyName"`
Precision string `json:"precision"`
}
type measurement struct {
Name string
Tags map[string]string
Values map[string]interface{}
}
func (m measurement) String() string {
var tags []string
var values []string
for k, v := range m.Tags {
tags = append(tags, fmt.Sprintf("%s=%v", k, formatInfluxValue(v, false)))
}
for k, v := range m.Values {
values = append(values, fmt.Sprintf("%s=%v", k, formatInfluxValue(v, true)))
}
// as maps are unsorted the order of tags and values is random.
// this is not an issue for influxdb, but makes testing more complex.
sort.Strings(tags)
sort.Strings(values)
return fmt.Sprintf("%s,%s %s", m.Name, strings.Join(tags, ","), strings.Join(values, ","))
}
func formatInfluxValue(v interface{}, quote bool) string {
switch v := v.(type) {
case float32, float64:
return fmt.Sprintf("%f", v)
case int, uint, uint8, int8, uint16, int16, uint32, int32, uint64, int64:
return fmt.Sprintf("%di", v)
case string:
if quote {
return strconv.Quote(v)
}
return v
case bool:
return fmt.Sprintf("%t", v)
default:
return fmt.Sprintf("%v", v)
}
}
// Validate validates the HandlerConfig data.
func (c HandlerConfig) Validate() error {
if !precisionValidator.MatchString(c.Precision) {
return ErrInvalidPrecision
}
return nil
}
// Handler implements an InfluxDB handler for writing received sensor-data into
// an InfluxDB database.
type Handler struct {
config HandlerConfig
}
// NewHandler creates a new InfluxDBHandler.
func NewHandler(conf HandlerConfig) (*Handler, error) {
return &Handler{
config: conf,
}, nil
}
func (h *Handler) send(measurements []measurement) error {
var measStr []string
for _, m := range measurements {
measStr = append(measStr, m.String())
}
sort.Strings(measStr)
b := []byte(strings.Join(measStr, "\n"))
args := url.Values{}
args.Set("db", h.config.DB)
args.Set("precision", h.config.Precision)
args.Set("rp", h.config.RetentionPolicyName)
req, err := http.NewRequest("POST", h.config.Endpoint+"?"+args.Encode(), bytes.NewReader(b))
if err != nil {
return errors.Wrap(err, "new request error")
}
req.Header.Set("Content-Type", "text/plain")
if h.config.Username != "" || h.config.Password != "" {
req.SetBasicAuth(h.config.Username, h.config.Password)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return errors.Wrap(err, "http request error")
}
defer resp.Body.Close()
// check that response is in 200 range
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
b, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("expected 2xx response, got: %d (%s)", resp.StatusCode, string(b))
}
return nil
}
// Close closes the handler.
func (h *Handler) Close() error {
return nil
}
// SendDataUp stores the uplink data into InfluxDB.
func (h *Handler) SendDataUp(pl handler.DataUpPayload) error {
if pl.Object == nil {
return nil
}
var measurements []measurement
// add data-rate measurement
measurements = append(measurements, measurement{
Name: "device_uplink",
Tags: map[string]string{
"application_name": pl.ApplicationName,
"device_name": pl.DeviceName,
"dev_eui": pl.DevEUI.String(),
"dr": strconv.FormatInt(int64(pl.TXInfo.DR), 10),
"frequency": strconv.FormatInt(int64(pl.TXInfo.Frequency), 10),
},
Values: map[string]interface{}{
"value": 1,
"f_cnt": pl.FCnt,
},
})
if len(pl.RXInfo) != 0 {
var rssi int
for i, rxInfo := range pl.RXInfo {
if i == 0 || rxInfo.RSSI > rssi {
rssi = rxInfo.RSSI
}
}
var snr float64
for i, rxInfo := range pl.RXInfo {
if i == 0 || rxInfo.LoRaSNR > snr {
snr = rxInfo.LoRaSNR
}
}
measurements[0].Values["rssi"] = rssi
measurements[0].Values["snr"] = snr
}
// parse object to measurements
measurements = append(measurements, objectToMeasurements(pl, "device_frmpayload_data", pl.Object)...)
if len(measurements) == 0 {
return nil
}
if err := h.send(measurements); err != nil {
return errors.Wrap(err, "sending measurements error")
}
log.WithFields(log.Fields{
"dev_eui": pl.DevEUI,
}).Info("handler/influxdb: uplink measurements written")
return nil
}
// SendStatusNotification writes the device-status.
func (h *Handler) SendStatusNotification(pl handler.StatusNotification) error {
var measurements []measurement
measurements = append(measurements, measurement{
Name: "device_status_battery",
Tags: map[string]string{
"application_name": pl.ApplicationName,
"device_name": pl.DeviceName,
"dev_eui": pl.DevEUI.String(),
},
Values: map[string]interface{}{
"value": pl.Battery,
},
})
if !pl.ExternalPowerSource && !pl.BatteryLevelUnavailable {
measurements = append(measurements, measurement{
Name: "device_status_battery_level",
Tags: map[string]string{
"application_name": pl.ApplicationName,
"device_name": pl.DeviceName,
"dev_eui": pl.DevEUI.String(),
},
Values: map[string]interface{}{
"value": pl.BatteryLevel,
},
})
}
measurements = append(measurements, measurement{
Name: "device_status_margin",
Tags: map[string]string{
"application_name": pl.ApplicationName,
"device_name": pl.DeviceName,
"dev_eui": pl.DevEUI.String(),
},
Values: map[string]interface{}{
"value": pl.Margin,
},
})
if err := h.send(measurements); err != nil {
return errors.Wrap(err, "sending measurements error")
}
log.WithFields(log.Fields{
"dev_eui": pl.DevEUI,
}).Info("handler/influxdb: status measurements written")
return nil
}
// SendJoinNotification is not implemented.
func (h *Handler) SendJoinNotification(pl handler.JoinNotification) error {
return nil
}
// SendACKNotification is not implemented.
func (h *Handler) SendACKNotification(pl handler.ACKNotification) error {
return nil
}
// SendErrorNotification is not implemented.
func (h *Handler) SendErrorNotification(pl handler.ErrorNotification) error {
return nil
}
// SendLocationNotification is not implemented.
func (h *Handler) SendLocationNotification(pl handler.LocationNotification) error {
return nil
}
func objectToMeasurements(pl handler.DataUpPayload, prefix string, obj interface{}) []measurement {
var out []measurement
if obj == nil {
return out
}
switch o := obj.(type) {
case int, uint, float32, float64, uint8, int8, uint16, int16, uint32, int32, uint64, int64, string, bool:
out = append(out, measurement{
Name: prefix,
Tags: map[string]string{
"application_name": pl.ApplicationName,
"device_name": pl.DeviceName,
"dev_eui": pl.DevEUI.String(),
"f_port": strconv.FormatInt(int64(pl.FPort), 10),
},
Values: map[string]interface{}{
"value": o,
},
})
default:
switch reflect.TypeOf(o).Kind() {
case reflect.Map:
v := reflect.ValueOf(o)
keys := v.MapKeys()
out = append(out, mapToLocation(pl, prefix, v)...)
for _, k := range keys {
keyName := fmt.Sprintf("%v", k.Interface())
if _, ignore := map[string]struct{}{
"latitude": struct{}{},
"longitude": struct{}{},
}[keyName]; ignore {
continue
}
out = append(out, objectToMeasurements(pl, prefix+"_"+keyName, v.MapIndex(k).Interface())...)
}
case reflect.Struct:
v := reflect.ValueOf(o)
l := v.NumField()
out = append(out, structToLocation(pl, prefix, v)...)
for i := 0; i < l; i++ {
if !v.Field(i).CanInterface() {
continue
}
fieldName := v.Type().Field(i).Tag.Get("influxdb")
if fieldName == "" {
fieldName = strings.ToLower(v.Type().Field(i).Name)
}
if _, ignore := map[string]struct{}{
"latitude": struct{}{},
"longitude": struct{}{},
}[fieldName]; ignore {
continue
}
out = append(out, objectToMeasurements(pl, prefix+"_"+fieldName, v.Field(i).Interface())...)
}
case reflect.Ptr:
v := reflect.Indirect(reflect.ValueOf(o))
out = append(out, objectToMeasurements(pl, prefix, v.Interface())...)
default:
log.WithField("type_name", fmt.Sprintf("%T", o)).Warning("influxdb handler: unhandled type!")
}
}
return out
}
func mapToLocation(pl handler.DataUpPayload, prefix string, obj reflect.Value) []measurement {
var latFloat, longFloat float64
keys := obj.MapKeys()
for _, k := range keys {
if strings.ToLower(k.String()) == "latitude" {
switch v := obj.MapIndex(k).Interface().(type) {
case float32:
latFloat = float64(v)
case float64:
latFloat = v
}
}
if strings.ToLower(k.String()) == "longitude" {
switch v := obj.MapIndex(k).Interface().(type) {
case float32:
longFloat = float64(v)
case float64:
longFloat = v
}
}
}
if latFloat == 0 && longFloat == 0 {
return nil
}
return []measurement{
{
Name: prefix + "_location",
Tags: map[string]string{
"application_name": pl.ApplicationName,
"device_name": pl.DeviceName,
"dev_eui": pl.DevEUI.String(),
"f_port": strconv.FormatInt(int64(pl.FPort), 10),
},
Values: map[string]interface{}{
"latitude": latFloat,
"longitude": longFloat,
"geohash": geohash.Encode(latFloat, longFloat),
},
},
}
}
func structToLocation(pl handler.DataUpPayload, prefix string, obj reflect.Value) []measurement {
var latFloat, longFloat float64
l := obj.NumField()
for i := 0; i < l; i++ {
fieldName := strings.ToLower(obj.Type().Field(i).Name)
if fieldName == "latitude" {
switch v := obj.Field(i).Interface().(type) {
case float32:
latFloat = float64(v)
case float64:
latFloat = v
}
}
if fieldName == "longitude" {
switch v := obj.Field(i).Interface().(type) {
case float32:
longFloat = float64(v)
case float64:
longFloat = v
}
}
}
if latFloat == 0 && longFloat == 0 {
return nil
}
return []measurement{
{
Name: prefix + "_location",
Tags: map[string]string{
"application_name": pl.ApplicationName,
"device_name": pl.DeviceName,
"dev_eui": pl.DevEUI.String(),
"f_port": strconv.FormatInt(int64(pl.FPort), 10),
},
Values: map[string]interface{}{
"latitude": latFloat,
"longitude": longFloat,
"geohash": geohash.Encode(latFloat, longFloat),
},
},
}
}