-
Notifications
You must be signed in to change notification settings - Fork 3
/
wrapper.go
348 lines (290 loc) · 8.49 KB
/
wrapper.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
// Package trigger contains wrappers around system triggers.
package trigger
import (
"fmt"
"strings"
"time"
"github.com/gobwas/glob"
"github.com/pkg/errors"
"go-home.io/x/server/plugins/common"
"go-home.io/x/server/plugins/device/enums"
"go-home.io/x/server/plugins/helpers"
pluginTrigger "go-home.io/x/server/plugins/trigger"
"go-home.io/x/server/providers"
"go-home.io/x/server/systems"
"go-home.io/x/server/systems/logger"
"go-home.io/x/server/utils"
"gopkg.in/yaml.v2"
)
// Describes trigger wrapper object.
type wrapper struct {
trigger pluginTrigger.ITrigger
logger common.ILoggerProvider
validator providers.IValidatorProvider
ID string
name string
server providers.IServerProvider
timezone *time.Location
triggeredAt int64
storage providers.IStorageProvider
fanOut providers.IInternalFanOutProvider
deviceActions []*triggerActionDevice
notificationActions []*triggerActionNotification
triggerChan chan interface{}
activeWindow bool
from int
to int
}
// ConstructTrigger has data required to create a new trigger.
type ConstructTrigger struct {
Logger common.ILoggerProvider
Loader providers.IPluginLoaderProvider
Secret common.ISecretProvider
Validator providers.IValidatorProvider
Provider string
Name string
RawConfig []byte
FanOut providers.IInternalFanOutProvider
Server providers.IServerProvider
Storage providers.IStorageProvider
Timezone *time.Location
}
// NewTrigger creates a new trigger.
func NewTrigger(ctor *ConstructTrigger) (providers.ITriggerProvider, error) {
triggerID := fmt.Sprintf("%s.%s", utils.NormalizeDeviceName(ctor.Name), systems.SysTrigger.String())
logCtor := &logger.ConstructPluginLogger{
SystemLogger: ctor.Logger,
Provider: ctor.Provider,
System: systems.SysAPI.String(),
ExtraFields: map[string]string{common.LogNameToken: ctor.Name, common.LogIDToken: triggerID},
}
log := logger.NewPluginLogger(logCtor)
cfg := &trigger{}
err := yaml.Unmarshal(ctor.RawConfig, cfg)
if err != nil {
log.Error("Failed to unmarshal trigger config", err)
return nil, errors.Wrap(err, "yaml un-marshal failed")
}
w := &wrapper{
logger: log,
name: ctor.Name,
validator: ctor.Validator,
server: ctor.Server,
ID: triggerID,
timezone: ctor.Timezone,
fanOut: ctor.FanOut,
storage: ctor.Storage,
}
err = w.loadActions(cfg.Actions)
if err != nil {
log.Error("Failed to init trigger provider", err)
return nil, errors.Wrap(err, "load action failed")
}
w.loadActiveWindow(cfg.ActiveHrs)
callback := make(chan interface{}, 5)
initData := &pluginTrigger.InitDataTrigger{
FanOut: ctor.FanOut,
Logger: log,
Triggered: callback,
Secret: ctor.Secret,
Timezone: ctor.Timezone,
}
request := &providers.PluginLoadRequest{
PluginProvider: ctor.Provider,
RawConfig: ctor.RawConfig,
SystemType: systems.SysTrigger,
ExpectedType: pluginTrigger.TypeTrigger,
InitData: initData,
}
plugin, err := ctor.Loader.LoadPlugin(request)
if err != nil {
log.Error("Failed to load trigger provider", err)
return nil, errors.Wrap(err, "plugin load failed")
}
w.trigger = plugin.(pluginTrigger.ITrigger)
w.triggerChan = callback
go w.processTriggers()
return w, nil
}
// GetID returns trigger id.
// Format is name.trigger.
func (w *wrapper) GetID() string {
return w.ID
}
// GetLastTriggeredTime returns UTC timestamp of a last trigger.
func (w *wrapper) GetLastTriggeredTime() int64 {
return w.triggeredAt
}
// Loads all trigger actions.
func (w *wrapper) loadActions(data []map[string]interface{}) error {
w.deviceActions = make([]*triggerActionDevice, 0)
w.notificationActions = make([]*triggerActionNotification, 0)
for _, v := range data {
s, ok := v[system]
if !ok {
continue
}
sys, err := triggerSystemString(s.(string))
if err != nil {
w.logger.Warn("Unknown trigger system", common.LogSystemToken, s.(string))
continue
}
switch sys {
case triggerDevice:
w.loadDeviceAction(v)
case triggerScript:
w.loadScriptAction(v)
case triggerNotification:
w.loadNotificationAction(v)
}
}
if 0 == len(w.deviceActions) && 0 == len(w.notificationActions) {
return &ErrNoActions{}
}
return nil
}
// Loads single device action.
func (w *wrapper) loadDeviceAction(data map[string]interface{}) {
action := &triggerActionDevice{}
err := w.loadAction(data, action)
if err != nil {
return
}
action.prepEntity, err = glob.Compile(action.Entity)
if err != nil {
w.logger.Error("Failed to compile regexp", err)
return
}
action.cmd, err = enums.CommandString(action.Command)
if err != nil {
w.logger.Error("Failed to validate action properties: unknown command", err,
common.LogDeviceCommandToken, action.Command)
return
}
action.Args, err = helpers.CommandPropertyFixYaml(action.Args, action.cmd)
if err != nil {
w.logger.Error("Failed to validate action properties", err)
return
}
action.prepArgs = make(map[string]interface{})
if nil != action.Args {
tmp, err := yaml.Marshal(action.Args)
if err != nil {
w.logger.Error("Failed to parse device action: marshal error", err)
return
}
err = yaml.Unmarshal(tmp, action.prepArgs)
if err != nil {
w.logger.Error("Failed to parse device action: un-marshal error", err)
return
}
}
w.deviceActions = append(w.deviceActions, action)
}
// Loads notification action.
func (w *wrapper) loadNotificationAction(data map[string]interface{}) {
action := &triggerActionNotification{}
err := w.loadAction(data, action)
if err != nil {
return
}
action.prepEntity, err = glob.Compile(action.Entity)
if err != nil {
w.logger.Error("Failed to compile regexp", err)
return
}
if "" == action.Message {
action.Message = fmt.Sprintf("go-home trigger %s[%s] went on", w.name, w.ID)
}
w.notificationActions = append(w.notificationActions, action)
}
// Loads generic action.
func (w *wrapper) loadAction(data map[string]interface{}, target interface{}) error {
tmp, err := yaml.Marshal(data)
if err != nil {
w.logger.Error("Failed to parse device action: marshal error", err)
return err
}
err = yaml.Unmarshal(tmp, target)
if err != nil {
w.logger.Error("Failed to parse device action: un-marshal error", err)
return err
}
if !w.validator.Validate(target) {
err := &ErrInvalidActionConfig{}
w.logger.Error("Failed to validate action", err)
return err
}
return nil
}
// Loads single script action.
func (w *wrapper) loadScriptAction(data map[string]interface{}) {
}
// Processes trigger provider callback-channel messages.
func (w *wrapper) processTriggers() {
for msg := range w.triggerChan {
go w.triggered(msg)
}
}
// Processes actual event.
// TODO: Remove nolint after scripts implementation.
func (w *wrapper) triggered(msg interface{}) { //nolint:unparam
if !w.isInActiveTimeWindow() {
w.logger.Debug("Triggered but outside of active window")
return
}
w.storage.State(&common.MsgDeviceUpdate{
ID: w.ID,
Name: w.name,
State: map[enums.Property]interface{}{enums.PropOn: true},
FirstSeen: false,
Type: enums.DevTrigger,
})
w.triggeredAt = utils.TimeNow()
w.fanOut.ChannelInTriggerUpdates() <- w.ID
for _, v := range w.deviceActions {
w.logger.Info("Invoking trigger device action",
"target_id", v.Entity, common.LogDeviceCommandToken, v.Command)
w.server.InternalCommandInvokeDeviceCommand(v.prepEntity, v.cmd, v.prepArgs)
}
for _, v := range w.notificationActions {
w.logger.Info("Sending notification action", "target_id", v.Entity)
w.server.SendNotificationCommand(v.prepEntity, v.Message)
}
}
// Determines whether local time is within operation hours.
func (w *wrapper) isInActiveTimeWindow() bool {
if !w.activeWindow {
return true
}
nowT := time.Now().In(w.timezone)
now := nowT.Hour()*60 + nowT.Minute()
if w.from > w.to {
return now <= w.to || now >= w.from
}
return w.from <= now && now <= w.to
}
// Loads active time window.
func (w *wrapper) loadActiveWindow(window string) {
w.activeWindow = false
if len(window) > 0 {
parts := strings.Split(window, "-")
if len(parts) != 2 {
w.logger.Warn("Active windows is wrong, ignoring")
return
}
from, err := time.Parse(time.Kitchen, parts[0])
if err != nil {
w.logger.Warn("Active windows FROM is wrong, ignoring")
return
}
to, err := time.Parse(time.Kitchen, parts[1])
if err != nil {
w.logger.Warn("Active windows TO is wrong, ignoring")
return
}
w.from = from.Hour()*60 + from.Minute()
w.to = to.Hour()*60 + to.Minute()
w.activeWindow = true
}
}