Rule Examples
Control tracking
This simplest rule keeps track of a control and sets another control to the same state.
For example, a rule can turn on a siren and a lamp if a motion sensor detects movement.
In the example, the motion sensor is connected to the «dry contact» input, control type «switch». The siren is connected to the built-in Wiren Board relay, and the lamp is connected to the relay box via Modbus. When the «dry contact» input (motion sensor output) is closed, «1» is supplied to the lamp and the relay, and «0» when it is off.
The rule is triggered every time the control value «D1_IN» of the device «wb-gpio» is changed. The new value of this control is passed to the rule code as a variable newValue.
defineRule({
whenChanged: "wb-gpio/D1_IN",
then: function (newValue, devName, cellName) {
dev["wb-gpio/Relay_2"] = newValue;
dev["wb-mrm2_6/Relay 1"] = newValue;
}
});
The same, but with a virtual device as an event source. Usage example: scripted button that turns on/off the siren and light bulb.
defineVirtualDevice("simple_test", {
title: "Simple switch",
cells: {
enabled: {
type: "switch",
value: false
},
}
});
defineRule("simple_switch", {
whenChanged: "simple_test/enabled",
then: function (newValue, devName, cellName) {
dev["wb-gpio/Relay_2"] = newValue;
dev["wb-mrm2_6/Relay 1"] = newValue;
}
});
Motion detection with timeout
A motion detector with a «dry contact» output is connected to input D2. When motion is detected, it shorts D2 and GND and status «1» appears on the corresponding wb-gpio/D2_IN
channel.
The lighting is connected via a built-in relay corresponding to the wb-gpio/Relay_1
channel.
The rule works like this:
- when movement appears, the light turns on. If a thirty-second «off» timer was previously started, this timer is disabled;
- when motion is lost, a thirty second «off» timer is started. If he manages to reach the end, the light turns off.
var motion_timer_1_timeout_ms = 30 * 1000;
var motion_timer_1_id = null;
defineRule("motion_detector_1", {
whenChanged: "wb-gpio/D2_IN",
then: function (newValue, devName, cellName) {
if (newValue) {
dev["wb-gpio/Relay_1"] = true;
if (motion_timer_1_id) {
clearTimeout(motion_timer_1_id);
}
motion_timer_1_id = setTimeout(function () {
dev["wb-gpio/Relay_1"] = false;
motion_timer_1_id = null;
}, motion_timer_1_timeout_ms);
}
},
});
Creating similar rules
If you need several such motion detectors, then in order not to copy the code, you can wrap the creation of the rule and variables in a function:
function makeMotionDetector(name, timeout_ms, detector_control, relay_control) {
var motion_timer_id = null;
defineRule(name, {
whenChanged: "wb-gpio/" + detector_control,
then: function(newValue, devName, cellName) {
if (!newValue) {
dev["wb-gpio/relay_control"] = true;
if (motion_timer_id) {
clearTimeout(motion_timer_id);
}
motion_timer_id = setTimeout(function() {
dev["wb-gpio/relay_control"] = false;
motion_timer_id = null;
}, timeout_ms);
}
}
});
}
makeMotionDetector("motion_detector_1", 20000, "EXT1_DR1", "EXT2_R3A1");
makeMotionDetector("motion_detector_2", 10000, "EXT1_DR2", "EXT2_R3A2");
makeMotionDetector("motion_detector_3", 10000, "EXT1_DR3", "EXT2_R3A3");
Activate the rule only at a certain time
The rule is the same as in the previous section, but only runs from 9:30 am to 5:10 pm UTC.
var motion_timer_1_timeout_ms = 5 * 1000;
var motion_timer_1_id = null;
defineRule("motion_detector_1", {
whenChanged: "wb-gpio/A1_IN",
then: function (newValue, devName, cellName) {
var date = new Date();
// time point marking the beginning of the interval
// i.e. "today, at HH:MM". All dates are in UTC!
var date_start = new Date(date);
date_start.setHours(9);
date_start.setMinutes(30);
// time point marking the end of the interval
var date_end = new Date(date);
date_end.setHours(17);
date_end.setMinutes(10);
// if time is between 09:30 and 17:10 UTC
if ((date > date_start) && (date < date_end)) {
if (newValue) {
dev["wb-gpio/EXT1_R3A1"] = 1;
if (motion_timer_1_id) {
clearTimeout(motion_timer_1_id);
}
motion_timer_1_id = setTimeout(function () {
dev["wb-gpio/EXT1_R3A1"] = 0;
motion_timer_1_id = null;
}, motion_timer_1_timeout_ms);
}
}
}
});
Rolling shutters
One relay turns on the motor that raises the curtains, the second relay turns on the motor that lowers the curtains. The rule ensures that both relays are not turned on at the same time.
In addition, the rule turns off the engines after a specified time after being turned on.
(function() { //don't touch this line
var suffix = "1"; // must be different in different JS files
var relay_up_device = "lc103_4";
var relay_up_control = "Relay 1";
var relay_down_device = "lc103_4";
var relay_down_control = "Relay 2";
var timeout_s = 15;
// End of settings
var relay_up_timer_id = null;
var relay_down_timer_id = null;
defineRule( "roller_shutter_up_on" + suffix, {
asSoonAs: function() {
return dev["relay_up_device/relay_up_control"];
},
then: function () {
if (relay_up_timer_id) {
relay_up_timer_id = clearTimeout(relay_up_timer_id);
};
relay_up_timer_id = setTimeout(function() {
return dev["relay_up_device/relay_up_control"] = 0;
}, timeout_s * 1000);
}
});
defineRule("roller_shutter_down_on" + suffix, {
asSoonAs: function() {
return dev[relay_down_device][relay_down_control];
},
then: function () {
if (relay_down_timer_id) {
relay_down_timer_id = clearTimeout(relay_down_timer_id);
};
relay_down_timer_id = setTimeout(function() {
dev["relay_down_device/relay_down_control"] = 0;
}, timeout_s * 1000);
}
});
defineRule("roller_shutter_both_on" + suffix, {
asSoonAs: function() {
return dev[relay_up_device][relay_up_control] && dev["relay_down_device/relay_down_control"];
},
then: function () {
if (relay_up_timer_id) {
relay_up_timer_id = clearTimeout(relay_up_timer_id);
};
if (relay_down_timer_id) {
relay_down_timer_id = clearTimeout(relay_down_timer_id);
};
dev[relay_up_device][relay_up_control] = 0;
dev["relay_down_device/relay_down_control"] = 0;
log("Both roller shutter relays on, switching them off");
}
});
})();
An older version of the same script demonstrates the use of aliases:
(function() {
defineAlias("relay_up_1", "lc103_4/Relay 1");
defineAlias("relay_down_1", "lc103_4/Relay 2");
var timeout_s = 15;
defineRule("roller_shutter_1_up_on", {
asSoonAs: function() {
return relay_up_1;
},
then: function () {
setTimeout(function() {
relay_up_1 = 0;
}, timeout_s * 1000);
}
});
defineRule("roller_shutter_1_down_on", {
asSoonAs: function() {
return relay_down_1;
},
then: function () {
setTimeout(function() {
relay_down_1 = 0;
}, timeout_s * 1000);
}
});
defineRule("roller_shutter_1_both_on", {
asSoonAs: function() {
return relay_up_1 && relay_down_1;
},
then: function () {
relay_up_1 = 0;
relay_down_1 = 0;
log("Both roller shutter relays on, switching them off");
}
});
})();
Impulse counters
Pulse counter connected to WB-MCM8. Gives out 1 pulse per 10 liters of water. When connected, the meter showed readings of 123.120 m³, which is equal to 123120 liters of water. The WB-MCM8 had 7 pulses when plugged in.
var meterCorrection = 123120 // Кcorrection value of the meter in liters
var counterCorrection = 7 // WB-MCM8 correction value in pulses
var inpulseValue = 10 // Number of liters per impulse
defineVirtualDevice("water_meters", { //
We create a virtual device for display in the web interface.
title: "Water meters",
cells: {
water_meter_1: {
type: "value",
value: 0
},
}
});
defineRule("water_meter_1", {
whenChanged: "wb-mcm8_29/Input 1 counter",
then: function(newValue, devName, cellName) {
if(newValue){
dev["water_meters/water_meter_1"] = ((parseInt(newValue) - counterCorrection) * inpulseValue) + meterCorrection; // We multiply the value of the counter by the number of liters / pulse and add the correction value.
}
}
});
Handling click counters
Description
The latest firmware versions of Wiren Board devices can recognize the types of button presses connected to the inputs and broadcast them via Modbus to the Wiren Board controller. For information on how the device recognizes types of clicks, read its documentation.
To process clicks, you need to track the state of the counter of the desired type of click on the controller and, when it changes, perform an action.
Handling counters is conveniently done on wb-rules, but you can use any automation tool like Node-RED. To speed up meter polling, configure poll period.
Examples
In the example, we are using the WB-MCM8 to control the first dimmer channel WB-MDM3:
- Short press turns on the channel.
- Double - turns off the channel.
- Long - increases brightness.
- Short, then long - reduces brightness.
Since changing the brightness requires a time-consuming action, we use a timer. We also control the state of the input with the button and stop the action when the button is released.
/* ---------------------------- */
/* 1. Single Press Counter: On action*/
/* ---------------------------- */
defineRule({
whenChanged: "wb-mcm8_20/Input 1 Single Press Counter",
then: function (newValue, devName, cellName) {
dev["wb-mdm3_58/K1"] = true;
}
});
/* ---------------------------- */
/* 2. Double Press Counter: Off action*/
/* ---------------------------- */
defineRule({
whenChanged: "wb-mcm8_20/Input 1 Double Press Counter",
then: function (newValue, devName, cellName) {
dev["wb-mdm3_58/K1"] = false;
}
});
/* --------------------------------------- */
/* 3. Long Press Counter: Increase brightness */
/* --------------------------------------- */
defineRule({
whenChanged: "wb-mcm8_20/Input 1 Long Press Counter",
then: function (newValue, devName, cellName) {
// Start a timer that will increase the value of the control
startTicker("input1_long_press", 75);
}
});
// A rule that will increase the brightness on a timer
defineRule({
when: function () { return timers["input1_long_press"].firing; },
then: function () {
var i = dev["wb-mdm3_58/Channel 1"];
if (i < 100 && dev["wb-mcm8_20/Input 1"]) {
i++
dev["wb-mdm3_58/Channel 1"] = i
} else {
timers["input1_long_press"].stop();
}
}
});
/* -------------------------------------------- */
/* 4. Shortlong Press Counter: Decrease brightness */
/* -------------------------------------------- */
defineRule({
whenChanged: "wb-mcm8_20/Input 1 Shortlong Press Counter",
then: function (newValue, devName, cellName) {
// Start a timer that will decrease the value of the control
startTicker("input1_shortlong_press", 75);
}
});
// A rule that will decrease the brightness on a timer
defineRule({
when: function () { return timers["input1_shortlong_press"].firing; },
then: function () {
var i = dev["wb-mdm3_58/Channel 1"];
if (i > 0 && dev["wb-mcm8_20/Input 1"]) {
i--
dev["wb-mdm3_58/Channel 1"] = i
} else {
timers["input1_shortlong_press"].stop();
}
}
});
Generic module for wb-rules
We wrote a module for wb-rules wb-press-actions that makes it easy to handle clicks in your scripts.
Sensor MSW v.3
When connecting the WB-MSW v.3 sensor to the Wiren Board controller, it is possible to create interesting scenarios using data from the sensor. For example, turn on the light when moving, signal with LEDs when the CO2 or VOC value is exceeded, turn on the air conditioner if it is hot or the air humidifier if the air is too dry. Rules are created individually for tasks. Here we will give some examples to understand the principle of working with the sensor. More examples of writing rules can be found in the Rules engine wb-rules documentation.
CO2
When the CO2 concentration is less than 650, we flash green once every 10 seconds.
When the CO2 concentration is over 651, but less than 1000, we flash yellow once every 5 seconds.
When the CO2 concentration is over 1001, we flash red once a second.
Max Motion
"Max Motion" - the maximum value of the motion sensor for N time. Time from 1 to 60 seconds can be set in register 282. The default is 10 seconds. When the Max Motion value reaches 50, we check whether the room is sufficiently lit, if not, turn on the light. As soon as the Max Motion value drops below 50, turn off the light.
defineRule("msw3_Motion", {
whenChanged: "wb-msw-v3_97/Max Motion",
then: function(newValue, devName, cellName) {
if (newValue > 50) {
if (dev["wb-msw-v3_97/Illuminance"] < 50) {
dev["wb-mr3_11/K1"] = true;
}
} else {
dev["wb-mr3_11/K1"] = false;
}
}
});
System rules
Many of the indications that are visible in the web interface of the controller out of the box are also created by rules on the wb-rules engine. Their code is here: https://github.com/wirenboard/wb-rules-system. The system rules are collected in the wb-rules-system
package, the script files on the controller are located in the /usr/share/wb-rules-system/
folder.
A few examples of system rules are below.
Rule for tweeters
Rule creates a virtual buzzer device with volume and frequency sliders and a mute button.
defineVirtualDevice("buzzer", {
title: "Buzzer", //
cells: {
frequency : {
type : "range",
value : 3000,
max : 7000,
},
volume : {
type : "range",
value : 10,
max : 100,
},
enabled : {
type : "switch",
value : false,
},
}
});
// setup pwm2
runShellCommand("echo 2 > /sys/class/pwm/pwmchip0/export");
function _buzzer_set_params() {
var period = parseInt(1.0 / dev.buzzer.frequency * 1E9);
var duty_cycle = parseInt(dev.buzzer.volume * 1.0 / 100 * period * 0.5);
runShellCommand("echo " + period + " > /sys/class/pwm/pwmchip0/pwm2/period");
runShellCommand("echo " + duty_cycle + " > /sys/class/pwm/pwmchip0/pwm2/duty_cycle");
};
defineRule("_system_buzzer_params", {
whenChanged: [
"buzzer/frequency",
"buzzer/volume",
],
then: function (newValue, devName, cellName) {
if ( dev.buzzer.enabled) {
_buzzer_set_params();
}
}
});
defineRule("_system_buzzer_onof", {
whenChanged: "buzzer/enabled",
then: function (newValue, devName, cellName) {
if ( dev.buzzer.enabled) {
_buzzer_set_params();
runShellCommand("echo 1 > /sys/class/pwm/pwmchip0/pwm2/enable");
} else {
runShellCommand("echo 0 > /sys/class/pwm/pwmchip0/pwm2/enable");
}
}
});
Power status rule
Rule creates a virtual device that reports the current power status. Two ADC channels are used as input data: battery voltage measurement and input voltage measurement.
The following logic is implemented:
1. If the input voltage is less than the battery voltage, then the board is powered by the battery. In this case, 0V is also displayed as the input voltage.
2. If the input voltage is greater than the battery voltage, then the board is powered by an external power source. The measurement from the Vin channel is displayed as the input voltage.
To illustrate, the rules use two different ways of triggering: by changing the value of the control (rule _system_track_vin) and by changing the value of the expression (the other two).
defineVirtualDevice("power_status", {
title: "Power status", //
cells: {
'working on battery' : {
type : "switch",
value : false,
readonly : true
},
'Vin' : {
type : "voltage",
value : 0
}
}
});
defineRule("_system_track_vin", {
whenChanged: "wb-adc/Vin",
then: function() {
if (dev["wb-adc/Vin"] < dev["wb-adc/BAT"] ) {
dev["power_status/Vin"] = 0;
} else {
dev["power_status/Vin"] = dev["wb-adc/Vin"] ;
}
}
});
defineRule("_system_dc_on", {
asSoonAs: function () {
return dev["wb-adc/Vin"] > dev["wb-adc/BAT"];
},
then: function () {
dev["power_status/working on battery"] = false;
}
});
defineRule("_system_dc_off", {
asSoonAs: function () {
return dev["wb-adc/Vin"] <= dev["wb-adc/BAT"];
},
then: function () {
dev["power_status/working on battery"] = true;
}
});
Thermostat
An example of a simple thermostat from the topic on the support portal.
defineVirtualDevice("Termostat", {
title: "Termostat",
cells: {
// =============== hallway underfloor heating
"R01-TS16-1-mode": {//mode 0-manual 1-scheduled
type: "switch",
value: false,
},
"R01-TS16-1-setpoint": {//setting
type: "range",
value: 25,
max: 30,
readonly: false
},
"R01-TS16-1-lock": {//blockage in visualization 0-unlocked 1-blocked
type: "switch",
value: false,
},.......
var hysteresis = 0.5;
function Termostat(name, temp, setpoint, TS, TS_onoff) {
defineRule(name, {
whenChanged: temp, //when the sensor state changes
then: function (newValue, devName, cellName) { // do the following
if (dev[TS_onoff]) {
if ( newValue < dev[setpoint] - hysteresis) { //if the sensor temperature is less than the setpoint - hysteresis
dev[TS] = true;
}
if ( newValue > dev[setpoint] + hysteresis) { //if the sensor temperature is greater than the virtual setpoint + hysteresis
dev[TS] = false;
}
}
else dev[TS] = false;
}
});
}
Termostat("R01-TS16-1", "A60-M1W3/External Sensor 1", "Termostat/R01-TS16-1-setpoint", "wb-gpio/EXT4_R3A1", "Termostat/R01-TS16-1-onoff"); //
Hallway underfloor heating
Sending commands via RS-485
For example, send a command to the device on the port /dev/ttys0 (corresponds to the hardware port RS-485-ISO on the Wiren Board 4). To do this, we will use the rules engine and the ability to execute arbitrary shell commands. See documentation for details.
Create a virtual device with switch type control via rules engine.
When you turn on the switch a command will be sent: (Set Brightness ch. 00=0xff) for Uniel UCH-M141:
FF FF 0A 01 FF 00 00 0A
When you turn off the switch a command will be sent: (set channel brightness 00=0x00) for Uniel UCH-M141:
FF FF 0A 01 00 00 00 0B
1. Port setting
To configure the / dev/ttyNSC0 port to 9600 speed, run the following command
stty -F /dev/ttyNSC0 ospeed 9600 ispeed 9600 raw clocal -crtscts -parenb -echo cs8
2. Sending a command
Sending data is done with the following shell command:
/usr/bin/printf '\xFF\xFF\x0A\x01\xD1\x06\x00\xE2' >/dev/ttyNSC0
where "\xFF\xFF\x0A\x01\xD1\x06\x00\xE2" - is the entry of a "FF FF 0A 01 D1 06 00 E2" command.
3. Create the new rules file /etc/wb-rules/rs485_cmd.js
in the rules engine
The file can be edited with vim, nano, or mcedit in an ssh session on the device, or it can be downloaded with SCP.
root@wirenboard:~# mcedit /etc/wb-rules/rs485_cmd.js
4. Describe the virtual device in the file
defineVirtualDevice("rs485_cmd", {
title: "Send custom command to RS-485 port",
cells: {
enabled: {
type: "switch",
value: false
},
}
});
5. Restart wb-rules and check the operation
root@wirenboard:~# /etc/init.d/wb-rules restart root@wirenboard:~# tail -f /var/log/messages
There should be no error messages in the log (exit via control-c)
A new device "Send custom command to RS-485 port" should appear in the Devices section of the web interface.
6. Add a function to configure the port.
function setup_port() {
runShellCommand("stty -F /dev/ttyNSC0 ospeed 9600 ispeed 9600 raw clocal -crtscts -parenb -echo cs8");
}
7. Let's describe the rules for turning the switch on and off
defineRule("_rs485_switch_on", {
asSoonAs: function () {
return dev.rs485_cmd.enabled;
},
then: function() {
runShellCommand("/usr/bin/printf '\\xff\\xff\\x0a\\x01\\xff\\x00\\x00\\x0a' > /dev/ttyNSC0");
}
});
defineRule("_rs485_switch_off", {
asSoonAs: function () {
return !dev.rs485_cmd.enabled;
},
then: function() {
runShellCommand("/usr/bin/printf '\\xff\\xff\\x0a\\x01\\x00\\x00\\x00\\x0b' >/dev/ttyNSC0");
}
});
Note the double shielding.
7. Putting it all together
The full contents of the file with the rules:
defineVirtualDevice("rs485_cmd", {
title: "Send custom command to RS-485 port",
cells: {
enabled: {
type: "switch",
value: false
},
}
});
function setup_port() {
runShellCommand("stty -F /dev/ttyNSC0 ospeed 9600 ispeed 9600 raw clocal -crtscts -parenb -echo cs8");
}
defineRule("_rs485_switch_on", {
asSoonAs: function () {
return dev.rs485_cmd.enabled;
},
then: function() {
runShellCommand("/usr/bin/printf '\\xff\\xff\\x0a\\x01\\xff\\x00\\x00\\x0a' > /dev/ttyNSC0");
}
});
defineRule("_rs485_switch_off", {
asSoonAs: function () {
return !dev.rs485_cmd.enabled;
},
then: function() {
runShellCommand("/usr/bin/printf '\\xff\\xff\\x0a\\x01\\x00\\x00\\x00\\x0b' >/dev/ttyNSC0");
}
});
setTimeout(setup_port, 1000); // set setup_port() running 1 second after starting.
Sending a message via Telegram bot
Messages are sent using Telegram API via curl
.
varmessage = "Text"; // write your message text
var token = "TOKEN"; // replace with bot token
var chat_id = CHATID; // replace with your chat_id
var command = 'curl -s -X POST https://api.telegram.org/bot{}/sendMessage -d chat_id={} -d text="{}"'.format(token, chat_id, message);
runShellCommand(command);
Handling errors when working with serial devices
Implemented by subscribing to all meta/error topics.
defineVirtualDevice("meta_error_test", {
title: "Metaerordisplay",
cells: {
topic: {
type: "text",
value: "",
readonly: true
},
value: {
type: "text",
value: "",
readonly: true
},
}
});
trackMqtt("/devices/+/controls/+/meta/error", function(message){
log.info("name: {}, value: {}".format(message.topic, message.value))
if (message.value=="r"){
dev["meta_error_test/topic"] = message.topic;
dev["meta_error_test/value"] = message.value;
}
});
Custom fields in web interface
If you need to manually enter temperature and humidity settings in the interface of the Wiren Board controller.
An easy way is to do in the defineVirtualDevice() field, make it readonly: false. And it will appear in the web interface in Devices as editable, and the value will be saved in the rules engine. But a complex setup with menus and options cannot be done this way.
The correct but tricky way is to create a new tab in the Configs section with editable settings options fields.
Three files are required:
1. The output scheme of the html page in the Configs
section: /usr/share/wb-mqtt-confed/schemas/test-config.schema.json
{
"type":"object",
"title":"Test configuration",
"description":"Long description configuration",
"configFile": {
"path":"/etc/test-config.conf",
"service":"wb-rules"
},
"properties": {
"temperature_setpoint": {
"type":"number",
"title":"Temperature Setpoint (Degrees C)",
"default": 25,
"propertyOrder": 1,
"minimum": 5,
"maximum": 40
},
"humidity_setpoint": {
"type":"number",
"title":"Humidity Setpoint (RH, %)",
"default": 60,
"propertyOrder": 2,
"minimum": 10,
"maximum": 95
}
},
"required": ["temperature_setpoint", "humidity_setpoint"]
}
2. Description of the default configuration (when saving the form in the web interface, the values will be written to this file) : /etc/test-config.conf
{
"temperature_setpoint": 60,
"humidity_setpoint": 14
}
3. Script that updates config : /mnt/data/etc/wb-rules/test-config-script.js
var config = readConfig("/etc/test-config.conf");
log("temperature setpoint is: {}".format(config.temperature_setpoint));
The last file can also be edited from the web interface on the Scripts tab.
In the json file describes the schema of the output html page browser, according to generally accepted mapping standard. Description of keys here: json-schema.org ahhh!
After creating the files, you need to restart the services
service wb-mqtt-confed restart
service wb-rules restart
When you click Save in the web interface, the wb-rules service will be restarted, and the values of the settings will be written to the rules.
Complex rules with schedules
The object is a grocery store. Various store systems are controlled by feedback from temperature sensors and taking into account the store's work schedule.
Not cron-rules are used for schedules, but the libschedule. The libschedule enables and disables rules, which, unlike cron rules, are executed continuously when enabled.
For example, we want the lighting to be on from 10 to 17h. The libschedule will follow the «turn on the lights» rule once a minute from 10 am to 17 PM.
This means that even if the controller is running intermittently and missed the transition time between schedules (10 am), the controller will still turn on the lights at the first opportunity.
lib_schedules.js:
global.__proto__.Schedules = {};
(function(Schedules) { // closing
function todayAt(now, hours, minutes) {
var date = new Date(now);
// i.e. "today, at HH:MM". All dates are in UTC!
date.setHours(hours);
date.setMinutes(minutes);
return date;
}
function checkScheduleInterval(now, start_time, end_time) {
var start_date = todayAt(now, start_time[0], start_time[1]);
var end_date = todayAt(now, end_time[0], end_time[1]);
log("checkScheduleInterval {} {} {}".format(now, start_date, end_date));
if (end_date >= start_date) {
if ((now >= start_date) && (now < end_date)) {
return true;
}
} else {
// end date is less than start date,
// assuming they belong to a different days (e.g. today and tomorrow)
// option 1: what if it's now the day of "end" date?
// in this case the following is enough:
if (now < end_date) {
return true;
}
// well, that seems not to be the case. ok,
// option 2: it's the day of "start" date:
if (now >= start_date) {
return true;
}
}
return false;
}
function checkSchedule(schedule, now) {
if (now == undefined) {
now = new Date();
}
for (var i = 0; i < schedule.intervals.length; ++i) {
var item = schedule.intervals[i];
if (checkScheduleInterval(now, item[0], item[1])) {
log("found matching schedule interval at {}".format(item));
return true;
}
}
return false;
}
function updateSingleScheduleDevStatus(schedule) {
log("updateSingleScheduleDevStatus {}".format(schedule.name));
dev["_schedules"][schedule.name] = checkSchedule(schedule);
};
function addScheduleDevCronTasks(schedule) {
for (var i = 0; i < schedule.intervals.length; ++i) {
var interval = schedule.intervals[i];
for (var j = 0; j < 2; ++j) { // either start or end of the interval
var hours = interval[j][0];
var minutes = interval[j][1];
log("cron at " + "0 " + minutes + " " + hours + " * * *");
defineRule("_schedule_dev_{}_{}_{}".format(schedule.name, i, j), {
when: cron("0 " + minutes + " " + hours + " * * *"),
then: function () {
log("_schedule_dev_ {}_{}_{}".format(schedule.name, i, j));
updateSingleScheduleDevStatus(schedule);
}
});
}
}
}
function addScheduleAutoUpdCronTask(schedule) {
defineRule("_schedule_auto_upd_{}".format(schedule.name), {
when: cron("@every " + schedule.autoUpdate),
then: function() {
dev._schedules[schedule.name] = dev._schedules[schedule.name];
}
});
}
var _schedules = {};
Schedules.registerSchedule = function(schedule) {
_schedules[schedule.name] = schedule;
};
Schedules.initSchedules = function() {
var params = {
title: "Schedule Status",
cells: {}
};
for (var schedule_name in _schedules) {
if (_schedules.hasOwnProperty(schedule_name)) {
var schedule = _schedules[schedule_name];
params.cells[schedule_name] = {type: "switch", value: false, readonly: true};
}
};
defineVirtualDevice("_schedules", params);
for (var schedule_name in _schedules) {
if (_schedules.hasOwnProperty(schedule_name)) {
var schedule = _schedules[schedule_name];
// setup cron tasks which updates the schedule dev status at schedule
// interval beginings and ends
addScheduleDevCronTasks(schedule);
// if needed, setup periodic task to trigger rules which use this schedule
if (schedule.autoUpdate) {
addScheduleAutoUpdCronTask(schedule);
}
// set schedule dev status as soon as possible at startup
(function(schedule) {
setTimeout(function() {
updateSingleScheduleDevStatus(schedule);
}, 1);
})(schedule);
};
};
};
})(Schedules);
An example of a rule using Schedules:
(function() { // closing
defineAlias("countersTemperature", "wb-msw2_30/Temperature");
defineAlias("vegetablesTemperature", "wb-msw2_31/Temperature");
defineAlias("heater1EnableInverted", "wb-mrm2-old_70/Relay 1");
defineAlias("frontshopVentInverted", "wb-gpio/EXT1_R3A3");
Schedules.registerSchedule({
"name" : "signboard", // signboard
"autoUpdate" : "1m",
"intervals" : [
[ [12, 30], [20, 30] ], // in UTC, 15:30 - 23:30 MSK
[ [3, 30], [5, 20] ], // in UTC, 6:30 - 8:20 MSK
]
});
Schedules.registerSchedule({
"name" : "ext_working_hours_15m",
"autoUpdate" : "1m",
"intervals" : [
[ [4, 45], [20, 15] ], // still UTC, 07:45 - 23:15 MSK
]
});
Schedules.registerSchedule({
"name" : "working_hours",
"autoUpdate" : "1m",
"intervals" : [
[ [5, 0], [19, 0] ], // still UTC, 8:00 - 22:00 MSK
]
});
Schedules.registerSchedule({
"name" : "working_hours_15m",
"autoUpdate" : "1m",
"intervals" : [
[ [4, 45], [19, 15] ], // still UTC, 7:45 - 22:15 MSK
]
});
Schedules.registerSchedule({
"name" : "frontshop_lighting",
"autoUpdate" : "1m",
"intervals" : [
[ [4, 20], [20, 45] ], // still UTC, 7:20 -23:45 MSK
]
});
Schedules.registerSchedule({
"name" : "heaters_schedule",
"intervals" : [
[ [4, 0], [17, 0] ], // still UTC, 07:00 - 20:00 MSK дневной режим
]
});
Schedules.initSchedules();
// signboard and facade illumination
defineRule("signboardOnOff", {
when: function() {
return dev._schedules.signboard || true;
},
then: function (newValue, devName, cellName) {
log("signboardOnOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
var on = dev._schedules.signboard; //
dev["wb-mr6c_80/K2"] = !on;
dev["wb-mr6c_80/K1"] = !on;
dev["wb-mr6c_80/K3"] = !on;
}
});
// sales area illumination
defineRule("lightingFrontshopOnOff", {
when: function() {
return dev._schedules.frontshop_lighting || true;
},
then: function (newValue, devName, cellName) {
log("lightingFrontshopOnOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
dev["wb-gpio/EXT1_R3A1"] = ! dev._schedules.frontshop_lighting; //inverted contactor
}
});
// backstoreroom ventilation
defineRule("ventBackstoreOnOff", {
when: function() {
return dev._schedules.ext_working_hours_15m || true;
},
then: function (newValue, devName, cellName) {
log("ventBackstoreOnOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
var on = dev._schedules.ext_working_hours_15m;
dev["wb-mr6c_81/K1"] = ! on; //inverted contactor
dev["wb-mr6c_81/K5"] = ! on; //inverted contactor
}
});
// Freezer showcase illumination
defineRule("lightingCoolingshelfsOnOff", {
when: function() {
return dev._schedules.frontshop_lighting || true;
},
then: function (newValue, devName, cellName) {
log("lightingCoolingshelfsOnOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
var on = dev._schedules.working_hours_15m;
//
the lighting in the freezer showcases via the normally-closed relays (inverted)
dev["wb-mrm2-old_60/Relay 1"] = !on;
dev["wb-mrm2-old_61/Relay 1"] = !on;
dev["wb-mrm2-old_62/Relay 1"] = !on;
dev["wb-mrm2-old_63/Relay 1"] = !on;
dev["wb-mrm2-old_64/Relay 1"] = !on;
dev["wb-mrm2-old_65/Relay 1"] = !on;
dev["wb-mrm2-old_66/Relay 1"] = !on;
dev["wb-mrm2-old_67/Relay 1"] = !on;
}
});
//Display fridges
defineRule("powerBrandFridgesOnOff", {
when: function() {
return dev._schedules.working_hours || true;
},
then: function (newValue, devName, cellName) {
log("powerBrandFridgesOnOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
var on = dev._schedules.working_hours;
dev["wb-gpio/EXT1_R3A5"] = !on; // inverted
}
});
// ========= Boilers and supply ventilation ТЗ ===========
// feedback on the temperature of the vegetable zone
// position controller works daily
defineRule("heatersDayOff", {
when: function() {
return (dev._schedules.heaters_schedule) && (vegetablesTemperature > 17.0);
},
then: function (newValue, devName, cellName) {
log("heatersDayOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
heater1EnableInverted = !false; // inverted
}
});
defineRule("heatersDayOn", {
when: function() {
return (dev._schedules.heaters_schedule) && (vegetablesTemperature < 16.7);
},
then: function (newValue, devName, cellName) {
log("heatersDayOn newValue={}, devName={}, cellName={}", newValue, devName, cellName);
heater1EnableInverted = !true; // inverted
}
});
// position controller works at night
defineRule("heatersNightOff", {
when: function() {
return (!dev._schedules.heaters_schedule) && (vegetablesTemperature > 11.6);
},
then: function (newValue, devName, cellName) {
log("heatersNightOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
heater1EnableInverted = !false; // inverted
}
});
defineRule("heatersNightOn", {
when: function() {
return (!dev._schedules.heaters_schedule) && (vegetablesTemperature < 11.3);
},
then: function (newValue, devName, cellName) {
log("heatersNightOn newValue={}, devName={}, cellName={}", newValue, devName, cellName);
heater1EnableInverted = !true; // inverted
}
});
// supply and exhaust ventilation are forcibly switched off
defineRule("ventFrontshopAlwaysOff", {
when: cron("@every 1m"),
then: function() {
dev["wb-gpio/EXT1_R3A3"] = !false;
dev["wb-gpio/EXT1_R3A4"] = !false;
}
});
// ================== The cash register area =================
// in the checkout area during working hours, the temperature is maintained by air conditioners (position controller)
defineRule("countersACOn", {
when: function() {
return (dev._schedules.working_hours_15m) && (countersTemperature < 17.7);
},
then: function (newValue, devName, cellName) {
log("countersACOn newValue={}, devName={}, cellName={}", newValue, devName, cellName);
dev["wb-mir_75/Play from ROM7"] = true; // air conditioning cash area for heating
}
});
// after working hours, the air conditioning is off
defineRule("countersACOff", {
when: function() {
return (!dev._schedules.working_hours_15m) || (countersTemperature > 18.0);
},
then: function (newValue, devName, cellName) {
log("countersACOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
dev["wb-mir_75/Play from ROM2"] = true; // shut down air conditioning cash area
}
});
// =============== Vegetable Zone ==============
// Refrigeration of vegetables with air conditioning only when the air temperature is above 18.5C
defineRule("acVegOn", {
when: function() {
return vegetablesTemperature >= 18.5
},
then: function (newValue, devName, cellName) {
log("acVegOn newValue={}, devName={}, cellName={}", newValue, devName, cellName);
dev["wb-mir_76/Play from ROM3"] = true; // Cooling +18
}
});
defineRule("acVegOff", {
when: function() {
return vegetablesTemperature < 17.8
},
then: function (newValue, devName, cellName) {
log("acVegOff newValue={}, devName={}, cellName={}", newValue, devName, cellName);
dev["wb-mir_76/Play from ROM2"] = true; // turn off
}
});
})()