This repository has been archived by the owner on Apr 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
rules.js
310 lines (270 loc) · 9.76 KB
/
rules.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
/**
* Rules namespace.
* This namespace allows creation of Openhab rules.
*
* @namespace rules
*/
const GENERATED_RULE_ITEM_TAG = "GENERATED_RULE_ITEM";
const items = require('./items');
const utils = require('./utils');
const log = require('./log')('rules');
const itemhistory = require('./itemhistory');
const osgi = require('./osgi');
const triggers = require('./triggers');
const { automationManager } = require('@runtime/RuleSupport');
let RuleManager = osgi.getService("org.openhab.core.automation.RuleManager","org.eclipse.smarthome.automation.RuleManager");
let factory = require('@runtime/rules').factory;
/**
* Generates an item name given it's configuration.
*
* @memberOf rules
* @private
* @param {Object} ruleConfig The rule config
* @param {String} userInfo.name The name of the rule.
*/
const itemNameForRule = function (ruleConfig) {
return "vRuleItemFor" + items.safeItemName(ruleConfig.name);
}
/**
* Links an item to a rule. When the item is switched on or off, so will the rule be.
*
* @memberOf rules
* @private
* @param {HostRule} rule The rule to link to the item.
* @param {OHItem} item the item to link to the rule.
*/
const linkItemToRule = function (rule, item) {
JSRule({
name: "vProxyRuleFor" + rule.getName(),
description: "Generated Rule to toggle real rule for " + rule.getName(),
triggers: [
triggers.ItemStateUpdateTrigger(item.name)
],
execute: function (data) {
try {
var itemState = data.state;
log.debug("Rule toggle item state received as " + itemState);
RuleManager.setEnabled(rule.getUID(), itemState == 'OFF' ? false : true);
log.info((itemState == 'OFF' ? "Disabled" : "Enabled") + " rule " + rule.getName() + " [" + rule.getUID() + "]");
} catch (e) {
log.error("Failed to toggle rule " + rule.getName() + ": " + e);
}
}
});
};
/**
* Gets the groups that an rule-toggling-item should be a member of. Will create the group item if necessary.
*
* @memberOf rules
* @private
* @param {Object} ruleConfig The rule config describing the rule
* @param {String} ruleConfig.ruleGroup the name of the rule group to use.
* @returns {String[]} the group names to put the item in
*/
const getGroupsForItem = function (ruleConfig) {
if (ruleConfig.ruleGroup) {
var groupName = "gRules" + items.safeItemName(ruleConfig.ruleGroup);
log.debug("Creating rule group " + ruleConfig.ruleGroup);
items.replaceItem(groupName, "Group", null, ["gRules"], ruleConfig.ruleGroup, [GENERATED_RULE_ITEM_TAG]);
return [groupName];
}
return ["gRules"];
}
/**
* Creates a rule. The rule will be created and immediately available.
*
* @example
* import { rules, triggers } = require('ohj');
*
* rules.JSRule({
* name: "my_new_rule",
* description": "this rule swizzles the swallows",
* triggers: triggers.GenericCronTrigger("0 30 16 * * ? *"),
* execute: triggerConfig => { //do stuff }
* });
*
* @memberOf rules
* @param {Object} ruleConfig The rule config describing the rule
* @param {String} ruleConfig.name the name of the rule
* @param {String} ruleConfig.description a description of the rule
* @param {*} ruleConfig.execute callback that will be called when the rule fires
* @param {HostTrigger|HostTrigger[]} ruleConfig.triggers triggers which will define when to fire the rule
* @returns {HostRule} the created rule
*/
let JSRule = function (ruleConfig) {
let ruid = ruleConfig.id || ruleConfig.name.replace(/[^\w]/g, "-") + "-" + utils.randomUUID();
let ruTemplateid = ruleConfig.name.replace(/[^\w]/g, "-") + "-" + utils.randomUUID();
log.info("Adding rule: {}", ruleConfig.name ? ruleConfig.name : ruid);
let SimpleRule = Java.extend(Java.type('org.openhab.core.automation.module.script.rulesupport.shared.simple.SimpleRule'));
let doExecute = function (module, input) {
try {
return ruleConfig.execute(getTriggeredData(input));
} catch (error) {
log.error(`Failed to execute rule ${ruid}: ${error}: ${error.stack}`);
throw error;
}
};
let rule = new SimpleRule({
execute: doExecute,
getUID: () => ruid
});
let triggers = ruleConfig.triggers ? ruleConfig.triggers : ruleConfig.getEventTrigger();
if (!Array.isArray(triggers)) {
triggers = [triggers];
}
rule.setTemplateUID(ruTemplateid);
if (ruleConfig.description) {
rule.setDescription(ruleConfig.description);
}
if (ruleConfig.name) {
rule.setName(ruleConfig.name);
}
//Register rule here
if (triggers && triggers.length > 0) {
rule.setTriggers(triggers);
rule = registerRule(rule);
}
return rule;
};
let currentProvider = automationManager;
let withNewRuleProvider = function(fn) {
let cachedRules = [];
currentProvider = {
addRule:r => {
//r = factory.processRule(r);
// r.setConfigurationDescriptions(null);
// r.setConfiguration(null);
cachedRules.push(factory.processRule(r))
}
}
try {
fn();
let provider = factory.newRuleProvider(cachedRules);
osgi.registerService(provider, utils.typeBySuffix('core.automation.RuleProvider').class.getName())
} finally {
currentProvider = automationManager;
}
}
let withManagedProvider = function(fn) {
let previousProvider = currentProvider;
currentProvider = automationManager;
try {
fn();
} finally {
currentProvider = previousProvider;
}
}
let registerRule = function(rule) {
return currentProvider.addRule(rule);
}
/**
* Creates a rule, with an associated SwitchItem that can be used to toggle the rule's enabled state.
* The rule will be created and immediately available.
*
* @memberOf rules
* @param {Object} ruleConfig The rule config describing the rule
* @param {String} ruleConfig.name the name of the rule
* @param {String} ruleConfig.description a description of the rule
* @param {*} ruleConfig.execute callback that will be called when the rule fires
* @param {HostTrigger[]} ruleConfig.triggers triggers which will define when to fire the rule
* @param {String} ruleConfig.ruleGroup the name of the rule group to use.
* @returns {HostRule} the created rule
*/
let SwitchableJSRule = function (ruleConfig) {
if (!ruleConfig.name) {
throw Error("No name specified for rule!");
}
//first create a toggling item
var itemName = itemNameForRule(ruleConfig);
//then add the item
var item = items.replaceItem(itemName, "Switch", null, getGroupsForItem(ruleConfig), ruleConfig.description, [GENERATED_RULE_ITEM_TAG]);
//create the real rule
var rule = JSRule(ruleConfig);
//hook up a rule to link the item to the actual rule
linkItemToRule(rule, item);
if (item.isUninitialized) {
//possibly load item's prior state
let historicState = itemhistory.latestState(item);
if (historicState !== null) {
item.postUpdate(historicState);
} else {
item.sendCommand('ON');
}
}
}
const getTriggeredData = function (input) {
let event = input.get('event');
if(event && Java.typeName(event.class) === 'org.eclipse.smarthome.core.items.events.ItemCommandEvent') {
return {
eventType: "command",
triggerType: "ItemCommandTrigger",
receivedCommand: event.getItemCommand(),
oldState: input.get("oldState") + "",
newState: input.get("newState") + "",
itemName: event.getItemName()
}
}
var ev = event + "";
//log.debug("event",ev.split("'").join("").split("Item ").join("").split(" "));
var evArr = [];
if (ev.includes("triggered")) {
var atmp = ev.split(" triggered "); //astro:sun:local:astroDawn#event triggered START
evArr = [atmp[0], "triggered", atmp[1]];
} else {
evArr = ev.split("'").join("").split("Item ").join("").split(" "); //Item 'benqth681_switch' received command ON
}
var d = {
//size: input.size(),
oldState: input.get("oldState") + "",
newState: input.get("newState") + "",
state: input.get("state") + "", //this occurs on an ItemStateUpdateTrigger
receivedCommand: null,
receivedState: null,
receivedTrigger: null,
itemName: evArr[0]
};
try {
if (event !== null && event.getPayload()) {
d.payload = JSON.parse(event.getPayload());
log.debug("Extracted event payload {}", d.payload);
}
} catch (e) {
log.warn("Failed to extract payload: {}", e.message);
}
switch (evArr[1]) {
case "received":
d.eventType = "command";
d.triggerType = "ItemCommandTrigger";
d.receivedCommand = input.get("command") + "";
break;
case "updated":
d.eventType = "update";
d.triggerType = "ItemStateUpdateTrigger";
d.receivedState = input.get("state") + "";
break;
case "changed":
d.eventType = "change";
d.triggerType = "ItemStateChangeTrigger";
break;
case "triggered":
d.eventType = "triggered";
d.triggerType = "ChannelEventTrigger";
d.receivedTrigger = evArr[2];
break;
default:
if (input.size() == 0) {
d.eventType = "time";
d.triggerType = "GenericCronTrigger";
d.triggerTypeOld = "TimerTrigger";
} else {
d.eventType = "";
d.triggerType = "";
}
}
return d;
};
module.exports = {
withNewRuleProvider,
JSRule,
SwitchableJSRule
}