forked from TIBCOSoftware/flogo-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trigger.go
executable file
·301 lines (225 loc) · 6.18 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
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
package coap
import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"strings"
"github.com/TIBCOSoftware/flogo-lib/core/trigger"
"github.com/TIBCOSoftware/flogo-lib/logger"
"github.com/dustin/go-coap"
)
const (
methodGET = "GET"
methodPOST = "POST"
methodPUT = "PUT"
methodDELETE = "DELETE"
)
// log is the default package logger
var log = logger.GetLogger("trigger-flogo-coap")
var validMethods = []string{methodGET, methodPOST, methodPUT, methodDELETE}
type StartFunc func(payload string) (string, bool)
// CoapTrigger CoAP trigger struct
type CoapTrigger struct {
metadata *trigger.Metadata
resources map[string]*CoapResource
server *Server
config *trigger.Config
}
type CoapResource struct {
path string
attrs map[string]string
handlers map[string]*trigger.Handler
}
//NewFactory create a new Trigger factory
func NewFactory(md *trigger.Metadata) trigger.Factory {
return &CoapFactory{metadata: md}
}
//CoapFactory Coap Trigger factory
type CoapFactory struct {
metadata *trigger.Metadata
}
//New Creates a new trigger instance for a given id
func (f *CoapFactory) New(config *trigger.Config) trigger.Trigger {
return &CoapTrigger{metadata: f.metadata, config: config}
}
// Metadata implements trigger.Trigger.Metadata
func (t *CoapTrigger) Metadata() *trigger.Metadata {
return t.metadata
}
func (t *CoapTrigger) Initialize(ctx trigger.InitContext) error {
if t.config.Settings == nil {
panic(fmt.Sprintf("No Settings found for trigger '%s'", t.config.Id))
}
port := t.config.Settings["port"]
if port == "" {
panic(fmt.Sprintf("No Port found for trigger '%s' in settings", t.config.Id))
}
mux := coap.NewServeMux()
mux.Handle("/.well-known/core", coap.FuncHandler(t.handleDiscovery))
t.resources = make(map[string]*CoapResource)
// Init handlers
for _, handler := range ctx.GetHandlers() {
if handlerIsValid(handler) {
method := strings.ToUpper(handler.GetStringSetting("method"))
path := handler.GetStringSetting("path")
log.Debugf("Registering handler for [%s: %s] - %s", method, path, handler)
resource, exists := t.resources[path]
if !exists {
resource = &CoapResource{path: path, attrs: make(map[string]string), handlers: make(map[string]*trigger.Handler)}
t.resources[path] = resource
}
resource.handlers[method] = handler
mux.Handle(path, newActionHandler(resource))
} else {
return fmt.Errorf("invalid endpoint: %v", handler)
}
}
log.Debugf("CoAP Trigger: Configured on port %s", port)
t.server = NewServer("udp", fmt.Sprintf(":%s", port), mux)
return nil
}
// Start implements trigger.Trigger.Start
func (t *CoapTrigger) Start() error {
return t.server.Start()
}
// Stop implements trigger.Trigger.Start
func (t *CoapTrigger) Stop() error {
return t.server.Stop()
}
// IDResponse id response object
type IDResponse struct {
ID string `json:"id"`
}
func (t *CoapTrigger) handleDiscovery(conn *net.UDPConn, addr *net.UDPAddr, msg *coap.Message) *coap.Message {
//path := msg.PathString() //handle queries
//todo add filter support
var buffer bytes.Buffer
numResources := len(t.resources)
i := 0
for _, resource := range t.resources {
i++
buffer.WriteString("<")
buffer.WriteString(resource.path)
buffer.WriteString(">")
if len(resource.attrs) > 0 {
for k, v := range resource.attrs {
buffer.WriteString(";")
buffer.WriteString(k)
buffer.WriteString("=")
buffer.WriteString(v)
}
}
if i < numResources {
buffer.WriteString(",\n")
} else {
buffer.WriteString("\n")
}
}
payloadStr := buffer.String()
res := &coap.Message{
Type: msg.Type,
Code: coap.Content,
MessageID: msg.MessageID,
Token: msg.Token,
Payload: []byte(payloadStr),
}
res.SetOption(coap.ContentFormat, coap.AppLinkFormat)
log.Debugf("Transmitting %#v", res)
return res
}
func newActionHandler(resource *CoapResource) coap.Handler {
return coap.FuncHandler(func(conn *net.UDPConn, addr *net.UDPAddr, msg *coap.Message) *coap.Message {
log.Debugf("CoAP Trigger: Recieved request")
method := toMethod(msg.Code)
uriQuery := msg.Option(coap.URIQuery)
var data map[string]interface{}
if uriQuery != nil {
//todo handle error
queryValues, _ := url.ParseQuery(uriQuery.(string))
queryParams := make(map[string]string, len(queryValues))
for key, value := range queryValues {
queryParams[key] = strings.Join(value, ",")
}
data = map[string]interface{}{
"queryParams": queryParams,
"payload": string(msg.Payload),
}
} else {
data = map[string]interface{}{
"payload": string(msg.Payload),
}
}
handler, exists := resource.handlers[method]
if !exists {
res := &coap.Message{
Type: coap.Reset,
Code: coap.MethodNotAllowed,
MessageID: msg.MessageID,
Token: msg.Token,
}
return res
}
_, err := handler.Handle(context.Background(), data)
if err != nil {
//todo determining if 404 or 500
res := &coap.Message{
Type: coap.Reset,
Code: coap.NotFound,
MessageID: msg.MessageID,
Token: msg.Token,
Payload: []byte(fmt.Sprintf("Unable to execute handler '%s'", handler)),
}
return res
}
log.Debugf("Ran: %s", handler)
if msg.IsConfirmable() {
res := &coap.Message{
Type: coap.Acknowledgement,
Code: 0,
MessageID: msg.MessageID,
Token: msg.Token,
}
//res.SetOption(coap.ContentFormat, coap.TextPlain)
log.Debugf("Transmitting %#v", res)
return res
}
return nil
})
}
////////////////////////////////////////////////////////////////////////////////////////
// Utils
func handlerIsValid(handler *trigger.Handler) bool {
method := handler.GetStringSetting("method")
if method == "" {
return false
}
if !stringInList(strings.ToUpper(method), validMethods) {
return false
}
//validate path
return true
}
func stringInList(str string, list []string) bool {
for _, value := range list {
if value == str {
return true
}
}
return false
}
func toMethod(code coap.COAPCode) string {
var method string
switch code {
case coap.GET:
method = methodGET
case coap.POST:
method = methodPOST
case coap.PUT:
method = methodPUT
case coap.DELETE:
method = methodDELETE
}
return method
}