-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtrigger.go
230 lines (176 loc) · 4.85 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
package coap
import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"strings"
"github.com/dustin/go-coap"
"github.com/project-flogo/core/data/metadata"
"github.com/project-flogo/core/support/log"
"github.com/project-flogo/core/trigger"
)
var triggerMd = trigger.NewMetadata(&Settings{}, &HandlerSettings{}, &Output{})
func init() {
_ = trigger.Register(&Trigger{}, &Factory{})
}
type Factory struct {
}
// Metadata implements trigger.Factory.Metadata
func (*Factory) Metadata() *trigger.Metadata {
return triggerMd
}
// New implements trigger.Factory.New
func (*Factory) New(config *trigger.Config) (trigger.Trigger, error) {
s := &Settings{}
err := metadata.MapToStruct(config.Settings, s, true)
if err != nil {
return nil, err
}
return &Trigger{id: config.Id, settings: s}, nil
}
// Trigger CoAp trigger struct
type Trigger struct {
server *Server
settings *Settings
resources map[string]*CoapResource
id string
logger log.Logger
}
type CoapResource struct {
path string
attrs map[string]string
handlers map[coap.COAPCode]trigger.Handler
}
func (t *Trigger) Initialize(ctx trigger.InitContext) error {
t.logger = ctx.Logger()
mux := coap.NewServeMux()
mux.Handle("/.well-known/core", coap.FuncHandler(t.handleDiscovery))
// Init handlers
for _, handler := range ctx.GetHandlers() {
s := &HandlerSettings{}
err := metadata.MapToStruct(handler.Settings(), s, true)
if err != nil {
return err
}
path := s.Path
method := strings.ToUpper(s.Method)
t.logger.Debugf("Registering handler [%s]", path)
resource, exists := t.resources[path]
if !exists {
resource = &CoapResource{path: path, attrs: make(map[string]string), handlers: make(map[coap.COAPCode]trigger.Handler)}
t.resources[path] = resource
t.logger.Debugf("Registering handler for [%s-%s]", method, path)
mux.Handle(path, newActionHandler(t, resource))
}
resource.handlers[toCoapCode(method)] = handler
t.logger.Debugf("Registering handler for [%s-%s]", method, path)
}
t.server = NewServer("udp", t.settings.Port, mux)
return nil
}
func (t *Trigger) Start() error {
return t.server.Start()
}
// Stop implements util.Managed.Stop
func (t *Trigger) Stop() error {
return t.server.Stop()
}
func newActionHandler(t *Trigger, resource *CoapResource) coap.Handler {
return coap.FuncHandler(func(conn *net.UDPConn, addr *net.UDPAddr, msg *coap.Message) *coap.Message {
t.logger.Debugf("CoAP Trigger: Recieved request")
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[msg.Code]
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
}
t.logger.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)
t.logger.Debugf("Transmitting %#v", res)
return res
}
return nil
})
}
func (t *Trigger) handleDiscovery(conn *net.UDPConn, addr *net.UDPAddr, msg *coap.Message) *coap.Message {
//todo add filter support
if msg.Code == coap.GET {
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)
t.logger.Debugf("Transmitting %#v", res)
return res
}
return nil
}