-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathtrigger.go
executable file
·186 lines (153 loc) · 4.89 KB
/
trigger.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
package mqtt
import (
"context"
"encoding/json"
"strconv"
"time"
"github.com/TIBCOSoftware/flogo-lib/core/data"
"github.com/TIBCOSoftware/flogo-lib/core/trigger"
"github.com/TIBCOSoftware/flogo-lib/logger"
"github.com/eclipse/paho.mqtt.golang"
)
// log is the default package logger
var log = logger.GetLogger("trigger-flogo-mqtt")
// MqttTrigger is simple MQTT trigger
type MqttTrigger struct {
metadata *trigger.Metadata
client mqtt.Client
config *trigger.Config
handlers []*trigger.Handler
topicToHandler map[string]*trigger.Handler
}
//NewFactory create a new Trigger factory
func NewFactory(md *trigger.Metadata) trigger.Factory {
return &MQTTFactory{metadata: md}
}
// MQTTFactory MQTT Trigger factory
type MQTTFactory struct {
metadata *trigger.Metadata
}
//New Creates a new trigger instance for a given id
func (t *MQTTFactory) New(config *trigger.Config) trigger.Trigger {
return &MqttTrigger{metadata: t.metadata, config: config}
}
// Metadata implements trigger.Trigger.Metadata
func (t *MqttTrigger) Metadata() *trigger.Metadata {
return t.metadata
}
// Initialize implements trigger.Initializable.Initialize
func (t *MqttTrigger) Initialize(ctx trigger.InitContext) error {
t.handlers = ctx.GetHandlers()
return nil
}
// Start implements trigger.Trigger.Start
func (t *MqttTrigger) Start() error {
opts := mqtt.NewClientOptions()
opts.AddBroker(t.config.GetSetting("broker"))
opts.SetClientID(t.config.GetSetting("id"))
opts.SetUsername(t.config.GetSetting("user"))
opts.SetPassword(t.config.GetSetting("password"))
b, err := data.CoerceToBoolean(t.config.Settings["cleansess"])
if err != nil {
log.Error("Error converting \"cleansess\" to a boolean ", err.Error())
return err
}
opts.SetCleanSession(b)
if storeType := t.config.Settings["store"]; storeType != ":memory:" {
opts.SetStore(mqtt.NewFileStore(t.config.GetSetting("store")))
}
opts.SetDefaultPublishHandler(func(client mqtt.Client, msg mqtt.Message) {
topic := msg.Topic()
//TODO we should handle other types, since mqtt message format are data-agnostic
payload := string(msg.Payload())
log.Debug("Received msg:", payload)
handler, found := t.topicToHandler[topic]
if found {
t.RunHandler(handler, payload)
} else {
log.Errorf("handler for topic '%s' not found", topic)
}
})
client := mqtt.NewClient(opts)
t.client = client
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
i, err := data.CoerceToDouble(t.config.Settings["qos"])
if err != nil {
log.Error("Error converting \"qos\" to an integer ", err.Error())
return err
}
t.topicToHandler = make(map[string]*trigger.Handler)
for _, handler := range t.handlers {
topic := handler.GetStringSetting("topic")
if token := t.client.Subscribe(topic, byte(i), nil); token.Wait() && token.Error() != nil {
log.Errorf("Error subscribing to topic %s: %s", topic, token.Error())
return token.Error()
} else {
log.Debugf("Subscribed to topic: %s, will trigger handler: %s", topic, handler)
t.topicToHandler[topic] = handler
}
}
return nil
}
// Stop implements ext.Trigger.Stop
func (t *MqttTrigger) Stop() error {
//unsubscribe from topic
for _, handlerCfg := range t.config.Handlers {
log.Debug("Unsubscribing from topic: ", handlerCfg.GetSetting("topic"))
if token := t.client.Unsubscribe(handlerCfg.GetSetting("topic")); token.Wait() && token.Error() != nil {
log.Errorf("Error unsubscribing from topic %s: %s", handlerCfg.Settings["topic"], token.Error())
}
}
t.client.Disconnect(250)
return nil
}
// RunHandler runs the handler and associated action
func (t *MqttTrigger) RunHandler(handler *trigger.Handler, payload string) {
trgData := make(map[string]interface{})
trgData["message"] = payload
results, err := handler.Handle(context.Background(), trgData)
if err != nil {
log.Error("Error starting action: ", err.Error())
}
log.Debugf("Ran Handler: [%s]", handler)
var replyData interface{}
if len(results) != 0 {
dataAttr, ok := results["data"]
if ok {
replyData = dataAttr.Value()
}
}
if replyData != nil {
dataJson, err := json.Marshal(replyData)
if err != nil {
log.Error(err)
} else {
replyTo := handler.GetStringSetting("topic")
if replyTo != "" {
t.publishMessage(replyTo, string(dataJson))
}
}
}
}
func (t *MqttTrigger) publishMessage(topic string, message string) {
log.Debug("ReplyTo topic: ", topic)
log.Debug("Publishing message: ", message)
qos, err := strconv.Atoi(t.config.GetSetting("qos"))
if err != nil {
log.Error("Error converting \"qos\" to an integer ", err.Error())
return
}
if len(topic) == 0 {
log.Warn("Invalid empty topic to publish to")
return
}
token := t.client.Publish(topic, byte(qos), false, message)
sent := token.WaitTimeout(5000 * time.Millisecond)
if !sent {
// Timeout occurred
log.Errorf("Timeout occurred while trying to publish to topic '%s'", topic)
return
}
}