-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathentitylistener.go
More file actions
277 lines (235 loc) · 6.7 KB
/
entitylistener.go
File metadata and controls
277 lines (235 loc) · 6.7 KB
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
package gomeassistant
import (
"encoding/json"
"fmt"
"time"
"github.com/golang-module/carbon"
"saml.dev/gome-assistant/internal"
"saml.dev/gome-assistant/websocket"
)
type EntityListener struct {
entityIDs []string
callback EntityListenerCallback
fromState string
toState string
throttle time.Duration
lastRan carbon.Carbon
betweenStart string
betweenEnd string
delay time.Duration
delayTimer *time.Timer
exceptionDates []time.Time
exceptionRanges []timeRange
runOnStartup bool
runOnStartupCompleted bool
ignoreAttributeChanges bool
enabledEntities []internal.EnabledDisabledInfo
disabledEntities []internal.EnabledDisabledInfo
}
type EntityListenerCallback func(*Service, State, EntityData)
type EntityData struct {
TriggerEntityID string
FromState string
FromAttributes map[string]any
ToState string
ToAttributes map[string]any
LastChanged time.Time
}
type stateChangedMessage struct {
websocket.BaseMessage
Event struct {
Data stateData `json:"data"`
EventType string `json:"event_type"`
Origin string `json:"origin"`
} `json:"event"`
}
type stateData struct {
EntityID string `json:"entity_id"`
NewState msgState `json:"new_state"`
OldState msgState `json:"old_state"`
}
type msgState struct {
EntityID string `json:"entity_id"`
LastChanged time.Time `json:"last_changed"`
State string `json:"state"`
Attributes map[string]any `json:"attributes"`
}
/* Methods */
func NewEntityListener() elBuilder1 {
return elBuilder1{EntityListener{
lastRan: carbon.Now().StartOfCentury(),
}}
}
type elBuilder1 struct {
entityListener EntityListener
}
func (b elBuilder1) EntityIDs(EntityIDs ...string) elBuilder2 {
if len(EntityIDs) == 0 {
panic("must pass at least one entityID to EntityIDs()")
} else {
b.entityListener.entityIDs = EntityIDs
}
return elBuilder2(b)
}
type elBuilder2 struct {
entityListener EntityListener
}
func (b elBuilder2) Call(callback EntityListenerCallback) elBuilder3 {
b.entityListener.callback = callback
return elBuilder3(b)
}
type elBuilder3 struct {
entityListener EntityListener
}
func (b elBuilder3) OnlyBetween(start string, end string) elBuilder3 {
b.entityListener.betweenStart = start
b.entityListener.betweenEnd = end
return b
}
func (b elBuilder3) OnlyAfter(start string) elBuilder3 {
b.entityListener.betweenStart = start
return b
}
func (b elBuilder3) OnlyBefore(end string) elBuilder3 {
b.entityListener.betweenEnd = end
return b
}
func (b elBuilder3) FromState(s string) elBuilder3 {
b.entityListener.fromState = s
return b
}
func (b elBuilder3) ToState(s string) elBuilder3 {
b.entityListener.toState = s
return b
}
func (b elBuilder3) Duration(s DurationString) elBuilder3 {
d := internal.ParseDuration(string(s))
b.entityListener.delay = d
return b
}
func (b elBuilder3) Throttle(s DurationString) elBuilder3 {
d := internal.ParseDuration(string(s))
b.entityListener.throttle = d
return b
}
func (b elBuilder3) ExceptionDates(t time.Time, tl ...time.Time) elBuilder3 {
b.entityListener.exceptionDates = append(tl, t)
return b
}
func (b elBuilder3) ExceptionRange(start, end time.Time) elBuilder3 {
b.entityListener.exceptionRanges = append(b.entityListener.exceptionRanges, timeRange{start, end})
return b
}
func (b elBuilder3) RunOnStartup() elBuilder3 {
b.entityListener.runOnStartup = true
return b
}
// IgnoreAttributeChanges causes this listener to skip firing when the entity's
// state string is unchanged (i.e. only attributes changed). By default,
// attribute-only changes will trigger the listener.
func (b elBuilder3) IgnoreAttributeChanges() elBuilder3 {
b.entityListener.ignoreAttributeChanges = true
return b
}
/*
Enable this listener only when the current state of {entityID} matches {state}.
If there is a network error while retrieving state, the listener runs if {runOnNetworkError} is true.
*/
func (b elBuilder3) EnabledWhen(entityID, state string, runOnNetworkError bool) elBuilder3 {
if entityID == "" {
panic(fmt.Sprintf("entityID is empty in EnabledWhen entityID='%s' state='%s'", entityID, state))
}
i := internal.EnabledDisabledInfo{
Entity: entityID,
State: state,
RunOnError: runOnNetworkError,
}
b.entityListener.enabledEntities = append(b.entityListener.enabledEntities, i)
return b
}
/*
Disable this listener when the current state of {entityID} matches {state}.
If there is a network error while retrieving state, the listener runs if {runOnNetworkError} is true.
*/
func (b elBuilder3) DisabledWhen(entityID, state string, runOnNetworkError bool) elBuilder3 {
if entityID == "" {
panic(fmt.Sprintf("entityID is empty in EnabledWhen entityID='%s' state='%s'", entityID, state))
}
i := internal.EnabledDisabledInfo{
Entity: entityID,
State: state,
RunOnError: runOnNetworkError,
}
b.entityListener.disabledEntities = append(b.entityListener.disabledEntities, i)
return b
}
func (b elBuilder3) Build() EntityListener {
return b.entityListener
}
func (l *EntityListener) maybeCall(app *App, entityData EntityData, data stateData) {
// Check conditions
if l.ignoreAttributeChanges && data.NewState.State == data.OldState.State {
return
}
if c := checkWithinTimeRange(l.betweenStart, l.betweenEnd); c.fail {
return
}
if c := checkStatesMatch(l.fromState, data.OldState.State); c.fail {
return
}
if c := checkStatesMatch(l.toState, data.NewState.State); c.fail {
if l.delayTimer != nil {
l.delayTimer.Stop()
}
return
}
if c := checkThrottle(l.throttle, l.lastRan); c.fail {
return
}
if c := checkExceptionDates(l.exceptionDates); c.fail {
return
}
if c := checkExceptionRanges(l.exceptionRanges); c.fail {
return
}
if c := checkEnabledEntity(app.state, l.enabledEntities); c.fail {
return
}
if c := checkDisabledEntity(app.state, l.disabledEntities); c.fail {
return
}
if l.delay != 0 {
l := l
l.delayTimer = time.AfterFunc(l.delay, func() {
go l.callback(app.service, app.state, entityData)
l.lastRan = carbon.Now()
})
return
}
// run now if no delay set
go l.callback(app.service, app.state, entityData)
l.lastRan = carbon.Now()
}
/* Functions */
func (app *App) callEntityListeners(msgBytes []byte) {
msg := stateChangedMessage{}
_ = json.Unmarshal(msgBytes, &msg)
data := msg.Event.Data
eid := data.EntityID
listeners, ok := app.entityListeners[eid]
if !ok {
// no listeners registered for this id
return
}
entityData := EntityData{
TriggerEntityID: eid,
FromState: data.OldState.State,
FromAttributes: data.OldState.Attributes,
ToState: data.NewState.State,
ToAttributes: data.NewState.Attributes,
LastChanged: data.OldState.LastChanged,
}
for _, l := range listeners {
l.maybeCall(app, entityData, data)
}
}