-
Notifications
You must be signed in to change notification settings - Fork 9
/
automations-extension.js
372 lines (372 loc) · 13.3 KB
/
automations-extension.js
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
const stringify = require("json-stable-stringify-without-jsonify");
const crypto = require("crypto");
const yaml_1 = require("../util/yaml");
const data_1 = require("../util/data");
function toArray(item) {
return Array.isArray(item) ? item : [item];
}
var ConfigPlatform;
(function (ConfigPlatform) {
ConfigPlatform["ACTION"] = "action";
ConfigPlatform["STATE"] = "state";
ConfigPlatform["NUMERIC_STATE"] = "numeric_state";
ConfigPlatform["TIME"] = "time";
})(ConfigPlatform || (ConfigPlatform = {}));
var StateOnOff;
(function (StateOnOff) {
StateOnOff["ON"] = "ON";
StateOnOff["OFF"] = "OFF";
})(StateOnOff || (StateOnOff = {}));
var ConfigService;
(function (ConfigService) {
ConfigService["TOGGLE"] = "toggle";
ConfigService["TURN_ON"] = "turn_on";
ConfigService["TURN_OFF"] = "turn_off";
ConfigService["CUSTOM"] = "custom";
})(ConfigService || (ConfigService = {}));
const WEEK = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const TIME_STRING_REGEXP = /^[0-9]{2}:[0-9]{2}:[0-9]{2}$/;
class Time {
constructor(time) {
if (!time) {
const now = new Date();
this.h = now.getHours();
this.m = now.getMinutes();
this.s = now.getSeconds();
}
else if (!TIME_STRING_REGEXP.test(time)) {
throw new Error(`Wrong time string: ${time}`);
}
else {
[this.h, this.m, this.s] = time.split(':').map(Number);
}
}
isEqual(time) {
return this.h === time.h
&& this.m === time.m
&& this.s === time.s;
}
isGreater(time) {
if (this.h > time.h) {
return true;
}
if (this.h < time.h) {
return false;
}
if (this.m > time.m) {
return true;
}
if (this.m < time.m) {
return false;
}
return this.s > time.s;
}
isLess(time) {
return !this.isGreater(time) && !this.isEqual(time);
}
isInRange(after, before) {
if (before.isEqual(after)) {
return false;
}
if (this.isEqual(before) || this.isEqual(after)) {
return true;
}
let inverse = false;
if (after.isGreater(before)) {
const tmp = after;
after = before;
before = tmp;
inverse = true;
}
const result = this.isGreater(after) && this.isLess(before);
return inverse ? !result : result;
}
}
class InternalLogger {
constructor(logger) {
this.logger = logger;
}
log(level, ...args) {
const data = args.map((item) => typeof item === 'string' ? item : stringify(item)).join(' ');
this.logger[level](`[AutomationsExtension] ${data}`);
}
debug(...args) {
this.log('debug', ...args);
}
warning(...args) {
this.log('warning', ...args);
}
info(...args) {
this.log('info', ...args);
}
error(...args) {
this.log('error', ...args);
}
}
class AutomationsExtension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus, settings, baseLogger) {
this.zigbee = zigbee;
this.mqtt = mqtt;
this.state = state;
this.publishEntityState = publishEntityState;
this.eventBus = eventBus;
this.settings = settings;
this.logger = new InternalLogger(baseLogger);
this.mqttBaseTopic = settings.get().mqtt.base_topic;
this.automations = this.parseConfig(settings.get().automations || {});
this.timeouts = {};
this.logger.info('Plugin loaded');
this.logger.debug('Registered automations', this.automations);
}
parseConfig(automations) {
if (typeof automations === 'string') {
automations = (yaml_1.default.readIfExists(data_1.default.joinPath(automations)) || {});
}
const services = Object.values(ConfigService);
const platforms = Object.values(ConfigPlatform);
return Object.values(automations).reduce((result, automation) => {
const platform = automation.trigger.platform;
if (!platforms.includes(platform)) {
this.logger.warning(`Config validation error: unknown trigger platform '${platform}'`);
return result;
}
if (!automation.trigger.entity) {
this.logger.warning('Config validation error: trigger entity not specified');
return result;
}
const actions = toArray(automation.action);
for (const action of actions) {
if (!services.includes(action.service)) {
this.logger.warning(`Config validation error: unknown service '${action.service}'`);
return result;
}
}
const conditions = automation.condition ? toArray(automation.condition) : [];
for (const condition of conditions) {
if (!platforms.includes(condition.platform)) {
this.logger.warning(`Config validation error: unknown condition platform '${condition.platform}'`);
return result;
}
}
const entities = toArray(automation.trigger.entity);
for (const entityId of entities) {
if (!result[entityId]) {
result[entityId] = [];
}
result[entityId].push({
id: crypto.randomUUID(),
trigger: automation.trigger,
action: actions,
condition: conditions,
});
}
return result;
}, {});
}
checkTrigger(configTrigger, update, from, to) {
let trigger;
let attribute;
switch (configTrigger.platform) {
case ConfigPlatform.ACTION:
if (!update.hasOwnProperty('action')) {
return null;
}
trigger = configTrigger;
const actions = toArray(trigger.action);
return actions.includes(update.action);
case ConfigPlatform.STATE:
trigger = configTrigger;
attribute = trigger.attribute || 'state';
if (!update.hasOwnProperty(attribute) || !from.hasOwnProperty(attribute) || !to.hasOwnProperty(attribute)) {
return null;
}
if (from[attribute] === to[attribute]) {
return null;
}
const states = toArray(trigger.state);
return states.includes(update[attribute]);
case ConfigPlatform.NUMERIC_STATE:
trigger = configTrigger;
attribute = trigger.attribute;
if (!update.hasOwnProperty(attribute) || !from.hasOwnProperty(attribute) || !to.hasOwnProperty(attribute)) {
return null;
}
if (from[attribute] === to[attribute]) {
return null;
}
if (typeof trigger.above !== 'undefined') {
if (to[attribute] < trigger.above) {
return false;
}
if (from[attribute] >= trigger.above) {
return null;
}
}
if (typeof trigger.below !== 'undefined') {
if (to[attribute] > trigger.below) {
return false;
}
if (from[attribute] <= trigger.below) {
return null;
}
}
return true;
}
return false;
}
checkCondition(condition) {
if (condition.platform === ConfigPlatform.TIME) {
return this.checkTimeCondition(condition);
}
return this.checkEntityCondition(condition);
}
checkTimeCondition(condition) {
const beforeStr = condition.before || '23:59:59';
const afterStr = condition.after || '00:00:00';
const weekday = condition.weekday || WEEK;
try {
const after = new Time(afterStr);
const before = new Time(beforeStr);
const current = new Time();
const now = new Date();
const day = now.getDay();
return current.isInRange(after, before) && weekday.includes(WEEK[day]);
}
catch (e) {
this.logger.warning(e);
return true;
}
}
checkEntityCondition(condition) {
if (!condition.entity) {
this.logger.warning('Config validation error: condition entity not specified');
return true;
}
const entity = this.zigbee.resolveEntity(condition.entity);
if (!entity) {
this.logger.warning(`Condition not found for entity '${condition.entity}'`);
return true;
}
let currentCondition;
let currentState;
let attribute;
switch (condition.platform) {
case ConfigPlatform.STATE:
currentCondition = condition;
attribute = currentCondition.attribute || 'state';
currentState = this.state.get(entity)[attribute];
if (currentState !== currentCondition.state) {
return false;
}
break;
case ConfigPlatform.NUMERIC_STATE:
currentCondition = condition;
attribute = currentCondition.attribute;
currentState = this.state.get(entity)[attribute];
if (typeof currentCondition.above !== 'undefined' && currentState < currentCondition.above) {
return false;
}
if (typeof currentCondition.below !== 'undefined' && currentState > currentCondition.below) {
return false;
}
break;
}
return true;
}
runActions(actions) {
for (const action of actions) {
const destination = this.zigbee.resolveEntity(action.entity);
if (!destination) {
this.logger.debug(`Destination not found for entity '${action.entity}'`);
continue;
}
const currentState = this.state.get(destination).state;
let newState;
switch (action.service) {
case ConfigService.TURN_ON:
newState = StateOnOff.ON;
break;
case ConfigService.TURN_OFF:
newState = StateOnOff.OFF;
break;
case ConfigService.TOGGLE:
newState = currentState === StateOnOff.ON ? StateOnOff.OFF : StateOnOff.ON;
break;
}
let data;
if (action.service === ConfigService.CUSTOM) {
data = action.data;
}
else if (currentState === newState) {
continue;
}
else {
data = { state: newState };
}
this.logger.debug(`Run automation for entity '${action.entity}':`, action);
this.mqtt.onMessage(`${this.mqttBaseTopic}/${destination.name}/set`, stringify(data));
}
}
runActionsWithConditions(conditions, actions) {
for (const condition of conditions) {
if (!this.checkCondition(condition)) {
return;
}
}
this.runActions(actions);
}
stopTimeout(automationId) {
const timeout = this.timeouts[automationId];
if (timeout) {
clearTimeout(timeout);
delete this.timeouts[automationId];
}
}
startTimeout(automation, time) {
this.logger.debug('Start timeout for automation', automation.trigger);
const timeout = setTimeout(() => {
delete this.timeouts[automation.id];
this.runActionsWithConditions(automation.condition, automation.action);
}, time * 1000);
timeout.unref();
this.timeouts[automation.id] = timeout;
}
runAutomationIfMatches(automation, update, from, to) {
const triggerResult = this.checkTrigger(automation.trigger, update, from, to);
if (triggerResult === false) {
this.stopTimeout(automation.id);
return;
}
if (triggerResult === null) {
return;
}
this.logger.debug('Start automation', automation);
const timeout = this.timeouts[automation.id];
if (timeout) {
return;
}
if (automation.trigger.for) {
this.startTimeout(automation, automation.trigger.for);
return;
}
this.runActionsWithConditions(automation.condition, automation.action);
}
findAndRun(entityId, update, from, to) {
const automations = this.automations[entityId];
if (!automations) {
return;
}
for (const automation of automations) {
this.runAutomationIfMatches(automation, update, from, to);
}
}
async start() {
this.eventBus.onStateChange(this, (data) => {
this.findAndRun(data.entity.name, data.update, data.from, data.to);
});
}
async stop() {
this.eventBus.removeListeners(this);
}
}
module.exports = AutomationsExtension;