-
Notifications
You must be signed in to change notification settings - Fork 24
/
encoder.go
80 lines (65 loc) · 1.48 KB
/
encoder.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
package main
import (
"strings"
"time"
log "github.com/Sirupsen/logrus"
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
"github.com/influxdata/influxdb-client-go/v2/api/write"
)
type MqttSeriesEncoder struct {
Config *InfluxDBConf
matchers []TopicMatcher
}
func createTopicMatcher(topicMap []string) []TopicMatcher {
m := []TopicMatcher{}
for _, t := range topicMap {
m = append(m, *NewTopicMatcher(t))
}
return m
}
func NewMqttSeriesEncoder(conf *InfluxDBConf) *MqttSeriesEncoder {
return &MqttSeriesEncoder{
Config: conf,
matchers: createTopicMatcher(conf.TopicMap),
}
}
func (ifc *MqttSeriesEncoder) Encode(msg Message) *write.Point {
now := time.Now()
if msg.Topic == "" && len(msg.Payload) == 0 {
return nil
}
j, err := MsgParse(msg.Payload)
if err != nil {
log.Warn(err)
return nil
}
name := ifc.Config.Series
if len(name) == 0 {
name = strings.Replace(msg.Topic, "/", ".", -1)
}
tags := map[string]string{}
// Store default tag attributes
if !ifc.Config.NoTopicTag {
tags["topic"] = msg.Topic
}
// Transform user-defined JSON fields to tags
for _, tag := range ifc.Config.TagsAttributes {
if v, ok := j[tag]; ok {
if tagVal, ok := v.(string); ok {
tags[tag] = tagVal
delete(j, tag)
}
}
}
// Append first match from TopicMap
for _, m := range ifc.matchers {
b, v := m.Match(msg.Topic)
if b {
for tag, tagVal := range v {
tags[tag] = tagVal
}
break
}
}
return influxdb2.NewPoint(name, tags, j, now)
}