Движок правил wb-rules/en: различия между версиями

Нет описания правки
(Новая страница: «Rule engine wb-rules»)
 
 
(не показано 111 промежуточных версий 2 участников)
Строка 1: Строка 1:
<languages/>
<languages/>
[[File:Wb rules demo.png|400px|thumb|right|Редактирование правил в веб-интерфейсе]]
[[File:Wb rules demo.png|400px|thumb|right|Editing rules in web interface]]
Для контроллера можно писать правила, например: "Если температура датчика меньше 18°С, включи нагреватель". Правила создаются через [[Special:MyLanguage/Веб-интерфейс Wiren Board|веб-интерфейс]] и пишутся на простом языке, похожем на Javascript.
You can write rules for the controller, for example: "If the sensor temperature is less than 18°C, turn on the heater." Rules are created via [[Веб-интерфейс Wiren Board/en|web interface]] and written in a simple language similar to Javascript.


Самое полное описание движка правил: https://github.com/contactless/wb-rules
The complete description of the rules engine: https://github.com/wirenboard/wb-rules






== Как создавать и редактировать правила ==
== How to create and edit rules ==


*Список файлов с правилами находится на странице ''Scripts'' веб-интерфейса.
*The list of files with rules is on the ''Scripts'' page of the web interface.
*Нажмите на название файла, чтобы открыть его для редактирования.
*Click the file name to open it for editing.
**Чтобы создать новый файл, нажмите на пункт ''New...'', вверху введите название скрипта (используйте для названия только латинские буквы и цифры, в качестве расширения укажите ''.js''), в основное поле введите текст скрипта, затем нажмите кнопку ''Save'' вверху.
**To create a new file, click ''New...'' at the top, enter the name of the script (use only Latin letters and numbers for the name, specify as an extension ''.js''), in the main field, enter the text of the script, then click the ''Save button'' at the top.
*Правило начинает работать автоматически после нажатия кнопки ''Save'', если в нём нет ошибок (смотрите ниже).
The rule starts automatically after you click ''Save'' if there are no errors (see below).
Примечания:
Notes:
#Файлы с правилами хранятся на контроллере в виде обычных текстовых файлов в папке <code>/etc/wb-rules/</code>, поэтому [[Special:MyLanguage/Просмотр файлов контроллера с компьютера|их можно редактировать и загружать напрямую с компьютера]].
#The rules files are stored on the controller as plain text files in the <code>/etc/wb-rules/</code> folder, so they [[Просмотр файлов контроллера с компьютера/en|can be edited and downloaded]] directly from your computer.
#Правила исполняются сервисом ''wb-rules'', документацию по нему смотрите [https://github.com/contactless/wb-rules странице сервиса в Github].
#The rules are executed by the ''wb-rules'' service, see the service's [https://github.com/wirenboard/wb-rules documentation on Github].






== Пишем первое правило ==
== Writing the first rule ==


[[File:Web-scripts-rule1.png|400px|thumb|Правило для управления обогревателем, записанное через веб-интерфейс]]
[[File:Web-scripts-rule1.png|400px|thumb|The rule for the heater control, written via the web interface]]


Правила бывают двух типов - непосредственно правила (начинаются со слов ''defineRule'') и виртуальные устройства (начинаются со слов ''defineVirtualDevice''). Виртуальные устройства - это появляющиеся в веб-интерфейсе новые элементы управления - например, кнопка-выключатель, которая на самом деле выключает два устройства одновременно. Она не привязана напрямую ни к какому физическому устройству, а действия при её нажатии определяются написанным вами скриптом.
There are two types of rules :the rules themselves (start with defineRule) and virtual devices (start with defineVirtualDevice). Virtual devices are new switchers that appear in the web interface - for example, a toggle button that actually turns off two devices at the same time. It is not tied directly to any physical device, and the actions when you click it are determined by the script you wrote.


Любое количество разных правил можно хранить в одном файле. Обычно в одном файле хранятся правила, отвечающие за близкие функции.
Any number of different rules can be stored in a single file. Typically, rules responsible for close functions are stored in a single file.






=== Первое правило ===
=== The first rule ===


Для начала разберём простое правило - при превышении температуры выключи обогреватель. Температуру получаем с датчика [[Special:MyLanguage/1-Wire|1-Wire]], обогреватель подключён к Реле 1 внешнего релейного модуля [[Special:MyLanguage/WB-MRM2|WB-MRM2]].
To begin with, we will analyze a simple rule - when the temperature is exceeded, turn off the heater. The temperature is obtained from the  [[1-Wire/en|1-Wire]] sensor, the heater is connected to the Relay 1 of external  [[WB-MRM2/en|WB-MRM2]] relay module.
<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">


defineRule("heater_control", { //название правила - "контроль обогревателя", может быть произвольным
defineRule("heater_control", { //rule name is arbitrary
   whenChanged: "wb-w1/28-0115a48fcfff", //при изменении состояния датчика 1-Wire с идентификатором 28-0115a48fcfff
   whenChanged: "wb-w1/28-0115a48fcfff", //when the state of 1-Wire sensor with ID 28-0115a48fcfff changes
   then: function (newValue, devName, cellName) { //выполняй следующие действия
   then: function (newValue, devName, cellName) { //execute
     if ( newValue > 30) { //если температура датчика больше 30 градусов
     if ( newValue > 30) { //if the sensor temperature value is more than 30 degrees
       dev["wb-mrm2_130"]["Relay 1"] = 0; //установи Реле 1 модуля WB-MRM2 с адресом 130 в состояние "выключено"
       dev["wb-mrm2_130"]["Relay 1"] = 0; //set the Relay 1 of WB-MRM2 module with address 130 in "off" state
     } else {
     } else {
       dev["wb-mrm2_130"]["Relay 1"] = 1; //установи Реле 1 модуля WB-MRM2 с адресом 130 в состояние "включено"
       dev["wb-mrm2_130"]["Relay 1"] = 1; //set Relay 1 of WB-MRM2 module with address 130 in "on" state
     }
     }
   }
   }
Строка 46: Строка 46:


</syntaxhighlight>
</syntaxhighlight>
*Первая строка - кодовое слово ''defineRule'' и название правила
*The first line is the code word ''defineRule'' and the name of the rule
*Вторая строка - кодовое слово для определения, когда выполняется правило, - ''whenChanged'' - "при изменении параметра", далее название параметра, при изменении которого запустится правило - температура с датчика 1-Wire. Название параметра записывается в виде "Device/Control", где названия ''Device'' и ''Control'' для каждого параметра можно найти на странице ''Settings'' веб-интерфейса в таблице ''MQTT Channels''.
*The second line is the code word for determining when the rule is executed-whenChanged - "when the parameter changes", then the name of the parameter, when changing which the rule will start - the temperature from the 1-Wire sensor. The parameter name is written as "Device/Control", where the device and Control names for each parameter can be found on the Settings page of the web interface in the ''MQTT Channels'' table.
*Третья строка - начало функции, которая будет исполняться
*The third line is the beginning of the function to be executed
*Затем идёт условие - "если значение температуры больше порогового, то ...". Значение параметра записывается в виде ''dev[Device][Control]'' - заметьте, оно отличается от вида записи параметра, при изменении которого запускается правило, потому что там речь идёт о ''параметре'', а здесь - о ''значении'' того же параметра.
*Then there is a condition - "if the temperature is greater than the threshold, then ...". The value of the parameter is written as dev[Device][Control] - note that it differs from the type of parameter recording, when changing which the rule is run, because there it is a parameter, and here - the value of the same parameter.
*Затем мы выставляем значения для реле в каждом случае - ''0'' - "выключено", ''1'' - "включено". Названия ''Device'' и ''Control'' для реле смотрим всё в той же таблице ''MQTT Channels'' на странице ''Settings'' веб-интерфейса.
*Then we set the values for the relay in each case - 0 - "off", 1 - "on". The names of the Device and Control for the relay look all in the same table MQTT Channels on the ''Settings'' page of the web interface.






=== Первое правило с виртуальным устройством ===
=== The first rule with a virtual device ===


Создаём виртуальный переключатель, при нажатии на который переключаются сразу два реле.
Create a virtual switch, by clicking on which two relays are switched at once.


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 80: Строка 80:




=== Пишем сложные правила ===
=== Write on complex rules ===


Чтобы начать писать сложные правила, нужно посмотреть примеры правил и полную документацию по движку правил:
To start writing complex rules, you need to see examples of rules and complete documentation on the rules engine:
#Примеры правил:
#Examples of rules:
#* на этой же странице ниже;
#* on the same page below;
#* в [http://forums.contactless.ru/t/dvizhok-pravil-primery-koda/483 специальной теме на нашем форуме ].
#* in [http://forums.contactless.ru/t/dvizhok-pravil-primery-koda/483 a special topic on our forum(ru)].
#[https://github.com/contactless/wb-rules Полное описание движка правил].
#[https://github.com/wirenboard/wb-rules Full description of the rules engine].






== Примеры правил ==
== Examples of rules ==




=== Слежение за контролом ===
=== Control tracking ===


Это простейшее правило следит за контролом и устанавливает другой контрол в такое же состояние.
This simple rule monitors the control and sets the other control in the same state.


Например правило может включать сирену и лампу, если датчик движения заметил движение.  
For example, a rule can include a siren and a lamp if the motion sensor has noticed movement.  


В примере датчик движения подключен к входу "сухой контакт", контрол типа "switch". Сирена подключена к встроеному реле Wiren Board, а лампа - через релейный блок по Modbus. Когда вход типа "сухой контакт" (выход датчика движения) замкнут, то на лампу и реле подаётся "1", когда выключен - "0".
In the example, the motion sensor is connected to the input "dry contact", control type "switch". The siren is connected to the built-in relay Wiren Board, and the lamp - through the relay unit by Modbus. When the input type "dry contact" (output motion sensor) is closed, the lamp and the relay get "1", when off - "0".




Правило срабатывает каждый раз при изменении значения контрола "D1_IN" у устройства "wb-gpio". В код правила передаётся новое значение этого контрола в виде переменной newValue.
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 newValue variable.


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 118: Строка 118:




То же самое, но с виртуальным девайсом в качестве источника событий. Пример использования: сценарная кнопка, которая включает/выключает сирену и лампочку.
The same, but with a virtual device as a source of events. Example of use: scenario button that turns on/off the siren and light bulb.


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 145: Строка 145:




=== Детектор движения c таймаутом ===
=== Motion detection with timeout ===


На вход D2 подключен детектор движения с выходом типа "сухой контакт", который замыкает D2 и GND при обнаружении движения.
The motion detector with the "dry contact" output type is connected to the D2 input, which closes the D2 and GND when motion is detected. At the same time, the status "1" appears on the "wb-gpio/D2_IN" channel.
При этом, на канале "wb-gpio/D2_IN" появляется статус "1".


Правило включает свет при обнаружении движения и выключает свет, спустя 30 секунд после пропадания сигнала с датчика движения.
The rule turns on the light when motion is detected and turns off the light 30 seconds after the motion sensor signal disappears.


Освещение подключено через встроенное реле, канал wb-gpio/Relay_1.
Lighting is connected via built-in relay, wb-gpio/Relay_1 channel.


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 181: Строка 180:




=== Создание однотипных правил ===
=== Creating similar rules ===


Если таких детекторов движения нужно несколько, то, чтобы не копировать код, можно обернуть создание правила и переменных в функцию:
If you need several such motion detectors, you can wrap the creation of rules and variables into a function to avoid copying the code:


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 213: Строка 212:




=== Активация правила только в определённое время ===
=== Activate a rule only at a specific time ===


Правило как в предыдущем разделе, но выполняется только с 9:30 до 17:10 по UTC.
The rule is as in the previous section, but runs only from 9:30 to 17:10 UTC.


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 258: Строка 257:




=== Роллеты ===
=== Rolling shutters ===


Одно реле включает двигатель, поднимающий шторы, второе реле - включает двигатель, опускающий шторы.
One relay includes the engine, raising the curtains, the second relay - includes the engine, lowering the curtains. The rule ensures that both relays are not switched on at the same time.
Правило следит за тем, чтобы оба реле не были включены одновременно.


Кроме этого, правило отключает двигатели спустя заданное время после включения.
In addition, the rule turns off the engines after a specified time after switching on.


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 338: Строка 336:




Более старая версия того же сценария демонстрирует использование alias-ов:
An older version of the same script demonstrates the use of aliases:
<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">


Строка 384: Строка 382:




=== Системные правила ===
=== System rules ===


Некоторые правила поставляются с системой правил по умолчанию в пакете wb-rules-system.  
Some rules come with the default rule system in the wb-rules-system package.  


Полный список правил [https://github.com/contactless/wb-rules-system/tree/master/rules в репозитории].
Full list of rules is [https://github.com/wirenboard/wb-rules-system/tree/master/rules in the repository.].


Некоторые примеры:
Some examples:






==== Правило для пищалки ====
==== The rule for the buzzer====


[https://github.com/contactless/wb-rules-system/blob/master/rules/buzzer.js Правило] создаёт виртуальное устройство buzzer с ползунками для регулировки громкости и частоты, а также кнопкой включения звука.
The [https://github.com/wirenboard/wb-rules-system/blob/master/rules/buzzer.js rule] creates a virtual buzzer device with sliders to adjust the volume and frequency, as well as a button to turn on the sound.




Строка 469: Строка 467:




==== Правило для статуса питания ====
==== Power status rule ====


[https://github.com/contactless/wb-rules-system/blob/master/rules/power_status.js Правило] создаёт виртуальное устройство, которое сообщает текущий статус питания. В качестве входных данных используется два канала АЦП: измерение напряжения на аккумуляторе и измерение входного напряжения.
[https://github.com/wirenboard/wb-rules-system/blob/master/rules/power_status.js The 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. Если входное напряжение меньше напряжение на аккумуляторе, то значит плата питается от аккумулятора. В этом случае, также отображается 0V в качестве входного напряжения.
1. If the input voltage is less than the voltage on the battery, then the Board is powered by the battery. In this case, 0V is also displayed as the input voltage.


2. Если входное напряжение  больше напряжения на аккумуляторе, то плата работает от внешнего источника питания. В качестве входонго напряжения отображается измерение с канала Vin.
2. If the input voltage is greater than the battery voltage, the Board is powered by an external power supply. The measurement from the Vin channel is displayed as the input voltage.




Для иллюстрации правила используют два разных способа срабатывания: по изменению значения контрола (правило _system_track_vin) и по изменению значения выражения (два других).
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).


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 539: Строка 537:




=== Отправка команд по RS-485 ===
=== Sending commands via RS-485 ===


Для примера отправим команду устройству на порт ''/dev/ttyNSC0'' (соответствует аппаратному порту RS-485-ISO на [[Special:MyLanguage/Wiren Board 4|Wiren Board 4]]).
For example, send a command to the device on the port /dev/ttys0 (corresponds to the hardware port RS-485-ISO on the [[Special:MyLanguage/Wiren Board 4|Wiren Board 4]]). To do this, we will use the rules engine and the ability to execute arbitrary shell commands. See [https://github.com/wirenboard/wb-rules#%D0%94%D1%80%D1%83%D0%B3%D0%B8%D0%B5-%D0%BF%D1%80%D0%B5%D0%B4%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D1%91%D0%BD%D0%BD%D1%8B%D0%B5-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B8-%D0%B8-%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5 documentation] for details.
Для этого будем использовать движок правил и возможность выполнения произвольных shell-команд. Подробнее см. [https://github.com/contactless/wb-rules#%D0%94%D1%80%D1%83%D0%B3%D0%B8%D0%B5-%D0%BF%D1%80%D0%B5%D0%B4%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D1%91%D0%BD%D0%BD%D1%8B%D0%B5-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B8-%D0%B8-%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5 в документации].


С помощью движка правил создадим виртуальное устройство с контролом типа switch (переключатель).  
Create a virtual device with switch type control via rules engine.  


При включении переключателя будем отправлять команду (уст. Яркость кан. 00=0xff) для Uniel UCH-M141:
When you turn on the switch a command will be sent: (Set Brightness ch. 00=0xff) for Uniel UCH-M141:
<pre>
<pre>
FF FF 0A 01 FF 00 00 0A
FF FF 0A 01 FF 00 00 0A
Строка 552: Строка 549:




При выключении переключателя будем отправлять команду (уст. Яркость кан. 00=0x00) для Uniel UCH-M141:
When you turn off the switch  a command will be sent: (set channel brightness 00=0x00) for Uniel UCH-M141:
<pre>
<pre>
FF FF 0A 01 00 00 00 0B
FF FF 0A 01 00 00 00 0B
Строка 561: Строка 558:




1. Настройка порта
1. Port setting


Для настройки порта /dev/ttyNSC0 на скорость 9600 надо выполнить следующую команду
To configure the / dev/ttyNSC0 port to 9600 speed, run the following command


<pre>
<pre>
Строка 569: Строка 566:
</pre>
</pre>


2. Отправка команды
2. Sending a command


Отправка данных делается следующей шелл-командой:
You can send data  by the following shell command:


<pre>
<pre>
/usr/bin/printf '\xFF\xFF\x0A\x01\xD1\x06\x00\xE2' >/dev/ttyNSC0
/usr/bin/printf '\xFF\xFF\x0A\x01\xD1\x06\x00\xE2' >/dev/ttyNSC0
</pre>
</pre>
где "\xFF\xFF\x0A\x01\xD1\x06\x00\xE2" - это запись команды "FF FF 0A 01 D1 06 00 E2".
where "\xFF\xFF\x0A\x01\xD1\x06\x00\xE2" - is the entry of a "FF FF 0A 01 D1 06 00 E2" command.




3. Создадим в движке правил новый файл с правилами <code>/etc/wb-rules/rs485_cmd.js</code>
3. Create the new rules file <code>/etc/wb-rules/rs485_cmd.js</code> in the rules engine


Файл можно редактировать с помощью vim, nano или mcedit в сеансе ssh на устройстве, либо залить его с помощью SCP.
The file can be edited with vim, nano, or mcedit in an ssh session on the device, or it can be downloaded with SCP.


<pre>
<pre>
Строка 588: Строка 585:




4. Описываем в файле виртуальный девайс
4. Describe the virtual device in the file


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 603: Строка 600:




5. Перезапускаем wb-rules и проверяем работу
5. Restart wb-rules and check the operation


<pre>
<pre>
Строка 610: Строка 607:
</pre>
</pre>


В логе не должно быть сообщений об ошибке (выход через control-c)
There should be no error messages in the log (exit via control-c)




В веб-интерфейсе в разделе Devices должно появиться новое устройство "Send custom command to RS-485 port".
A new device "Send custom command to RS-485 port"should appear in the Devices section of the web interface.




6. Добавим функцию для конфигурирования порта.
6. Add a function to configure the port.




Строка 627: Строка 624:




7. Опишем правила на включение и выключение переключателя
7. Let's describe the rules for switching on and off the switch


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 651: Строка 648:




Обратите внимание на двойное экранирование.
Note the double shielding.








7. Собираем всё вместе
8. Putting it all together


Полное содержимое файла с правилами:
Full contents of the rules file:


<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
Строка 694: Строка 691:
});
});


setTimeout(setup_port, 1000); // запланировать выполнение setup_port() через 1 секунду после старта правил.
setTimeout(setup_port, 1000); // set setup_port() running 1 second after starting.


</syntaxhighlight>
</syntaxhighlight>
Строка 700: Строка 697:




=== Пользовательские поля в интерфейсе ===
=== User fields in the interface ===


Чтобы дать пользователю возможность вводить точные значения параметров (уставки) из интерфейса, можно воспользоваться [https://wirenboard.com/wiki/index.php/%D0%A1%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5_%D1%80%D0%B5%D0%B4%D0%B0%D0%BA%D1%82%D0%B8%D1%80%D1%83%D0%B5%D0%BC%D1%8B%D1%85_%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D1%85_%D0%BF%D0%BE%D0%BB%D0%B5%D0%B9_%D0%B2_%D0%B2%D0%B5%D0%B1-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D1%84%D0%B5%D0%B9%D1%81%D0%B5 инструкцией].
To enable the user to enter exact parameter values (setpoints) from the interface, you can use the [https://wirenboard.com/wiki/index.php/%D0%A1%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5_%D1%80%D0%B5%D0%B4%D0%B0%D0%BA%D1%82%D0%B8%D1%80%D1%83%D0%B5%D0%BC%D1%8B%D1%85_%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D1%85_%D0%BF%D0%BE%D0%BB%D0%B5%D0%B9_%D0%B2_%D0%B2%D0%B5%D0%B1-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D1%84%D0%B5%D0%B9%D1%81%D0%B5 instruction].


Более подробно и с примером - в [https://support.wirenboard.com/t/kak-na-wb5-wb6-sozdat-pole-dlya-vvoda-ustavok-i-peredat-znachenie-v-pravila/2180 теме на портале техподдержки].
More detailed and with example - in the topic on the technical support [https://support.wirenboard.com/t/kak-na-wb5-wb6-sozdat-pole-dlya-vvoda-ustavok-i-peredat-znachenie-v-pravila/2180 forum].






=== Сложные правила с расписаниями ===
=== Complex scheduled rules ===


Объект - продуктовый магазин. Различные системы магазина управляются по обратной связи от датчиков температуры и с учётом расписания работы магазина.
Object - grocery store. Various store systems are controlled by feedback from temperature sensors and taking into account the schedule of the store.


Для расписаний используются не cron-правила, а обёртка над ними. Обёртка включает и выключает правила, которые, в отличие от cron-правил, выполняются постоянно, будучи включенными.
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.


Например, мы хотим, чтобы освещение было включено с 10 до 17ч. Обёртка (libschedule) будет выполнять правило "включить освещение" раз в минуту с 10 утра до 17 вечера.
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.


Это значит, что даже если контроллер работает с перерывами и пропустил время перехода между расписаниями (10 утра), то контроллер всё равно включит освещение при первой возможности.
This means that even if the controller works intermittently and missed the transition time between schedules (10 am), the controller will still turn on the lighting as soon as possible.




Строка 724: Строка 721:
global.__proto__.Schedules = {};
global.__proto__.Schedules = {};


(function(Schedules) { // замыкание
(function(Schedules) { // closing


   function todayAt(now, hours, minutes) {
   function todayAt(now, hours, minutes) {
Строка 864: Строка 861:
</syntaxhighlight>
</syntaxhighlight>


Пример правил, с использованием Schedules:
An example of a rule using Schedules:
<syntaxhighlight lang="ecmascript">
<syntaxhighlight lang="ecmascript">
(function() { // замыкание
(function() { // closing


   defineAlias("countersTemperature", "wb-msw2_30/Temperature");
   defineAlias("countersTemperature", "wb-msw2_30/Temperature");
Строка 918: Строка 915:
   Schedules.initSchedules();
   Schedules.initSchedules();


   // Вывеска и фасадное освещение
   // signboard and facade illumination
   defineRule("signboardOnOff", {
   defineRule("signboardOnOff", {
     when: function() {
     when: function() {
Строка 934: Строка 931:




   // Освещение торгового зала
   // sales area illumination
   defineRule("lightingFrontshopOnOff", {
   defineRule("lightingFrontshopOnOff", {
     when: function() {
     when: function() {
Строка 941: Строка 938:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("lightingFrontshopOnOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("lightingFrontshopOnOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       dev["wb-gpio/EXT1_R3A1"] = ! dev._schedules.frontshop_lighting; //инвертированный контактор
       dev["wb-gpio/EXT1_R3A1"] = ! dev._schedules.frontshop_lighting; //inverted contactor
     }
     }
   });
   });




   // Вентиляция подсобного помещения
   // backstoreroom ventilation
   defineRule("ventBackstoreOnOff", {
   defineRule("ventBackstoreOnOff", {
     when: function() {
     when: function() {
Строка 954: Строка 951:
       log("ventBackstoreOnOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("ventBackstoreOnOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       var on = dev._schedules.ext_working_hours_15m;
       var on = dev._schedules.ext_working_hours_15m;
       dev["wb-mr6c_81/K1"] = ! on; //инвертированный контактор
       dev["wb-mr6c_81/K1"] = ! on; //inverted contactor
       dev["wb-mr6c_81/K5"] = ! on; //инвертированный контактор
       dev["wb-mr6c_81/K5"] = ! on; //inverted contactor
     }
     }
   });
   });


   // Освещение холодильных горок
   // Freezer showcase illumination
   defineRule("lightingCoolingshelfsOnOff", {
   defineRule("lightingCoolingshelfsOnOff", {
     when: function() {
     when: function() {
Строка 968: Строка 965:
       var on = dev._schedules.working_hours_15m;
       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_60/Relay 1"] = !on;
       dev["wb-mrm2-old_61/Relay 1"] = !on;
       dev["wb-mrm2-old_61/Relay 1"] = !on;
Строка 981: Строка 979:




   //Брендовые холодильники (пиво, лимонады)
   //Display fridges
   defineRule("powerBrandFridgesOnOff", {
   defineRule("powerBrandFridgesOnOff", {
     when: function() {
     when: function() {
Строка 990: Строка 988:
       var on = dev._schedules.working_hours;
       var on = dev._schedules.working_hours;
        
        
       dev["wb-gpio/EXT1_R3A5"] = !on; // инвертировано
       dev["wb-gpio/EXT1_R3A5"] = !on; // inverted
     }
     }
   });
   });




   // ========= Котлы и приточная вентиляция ТЗ  ===========
   // ========= Boilers and supply ventilation ===========
   // обратная связь по температуре овощной зоны
   // feedback by the temperature of the vegetable  zone


   // днём работает позиционный регулятор
   // position controller works daily
   defineRule("heatersDayOff", {
   defineRule("heatersDayOff", {
     when: function() {
     when: function() {
Строка 1005: Строка 1003:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("heatersDayOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("heatersDayOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       heater1EnableInverted = !false; // инвертировано
       heater1EnableInverted = !false; // inverted
     }
     }
   });
   });
Строка 1015: Строка 1013:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("heatersDayOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("heatersDayOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       heater1EnableInverted = !true; // инвертировано
       heater1EnableInverted = !true; // inverted
     }
     }
   });
   });


   // ночью работает позиционный регулятор
   // position controller works at night
   defineRule("heatersNightOff", {
   defineRule("heatersNightOff", {
     when: function() {
     when: function() {
Строка 1026: Строка 1024:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("heatersNightOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("heatersNightOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       heater1EnableInverted = !false; // инвертировано
       heater1EnableInverted = !false; // inverted
     }
     }
   });
   });
Строка 1036: Строка 1034:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("heatersNightOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("heatersNightOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       heater1EnableInverted = !true; // инвертировано
       heater1EnableInverted = !true; // inverted
     }
     }
   });
   });




   // приточная и вытяжная вентиляция принудительно выключены
   // supply and exhaust ventilation are forcibly switched off
    
    
   defineRule("ventFrontshopAlwaysOff", {
   defineRule("ventFrontshopAlwaysOff", {
Строка 1052: Строка 1050:
    
    
    
    
   // ==================  Кассовая зона =================
   // ==================  The cash register area =================


   // в кассовой зоне в рабочее время температура поддерживается кондиционерами (позиционный регулятор)
   // in the cash area during working hours the temperature is maintained by air conditioning (position controller)


   defineRule("countersACOn", {
   defineRule("countersACOn", {
Строка 1062: Строка 1060:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("countersACOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("countersACOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       dev["wb-mir_75/Play from ROM7"] = true; // кондиционер кассовой зоны на нагрев
       dev["wb-mir_75/Play from ROM7"] = true; // air conditioning cash area for heating
     }
     }
   });
   });


   // в нерабочее время кондиционер выключен
   // after working hours, the air conditioning is off
   defineRule("countersACOff", {
   defineRule("countersACOff", {
     when: function() {
     when: function() {
Строка 1073: Строка 1071:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("countersACOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("countersACOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       dev["wb-mir_75/Play from ROM2"] = true; // кондиционер кассовой зоны выключить
       dev["wb-mir_75/Play from ROM2"] = true; // shut down air conditioning cash area
     }
     }
   });
   });


   // =============== Овощная зона ==============
   // =============== Vegetable zone ==============
   // Охлаждение овощей кондиционером только при температуре воздуха выше 18.5C  
   // Cooling vegetables air-conditioned only when the air temperature is above 18.5 C  


   defineRule("acVegOn", {
   defineRule("acVegOn", {
Строка 1086: Строка 1084:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("acVegOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("acVegOn  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       dev["wb-mir_76/Play from ROM3"] = true; // Охлаждение +18
       dev["wb-mir_76/Play from ROM3"] = true; // Cooling +18
     }
     }
   });
   });
Строка 1096: Строка 1094:
     then: function (newValue, devName, cellName) {
     then: function (newValue, devName, cellName) {
       log("acVegOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       log("acVegOff  newValue={}, devName={}, cellName={}", newValue, devName, cellName);
       dev["wb-mir_76/Play from ROM2"] = true; // выключить
       dev["wb-mir_76/Play from ROM2"] = true; // shutdown
     }
     }
   });
   });
Строка 1104: Строка 1102:




== Полное описание возможностей движка правил ==
== A full description of the capabilities of the rules engine ==


Самое полное описание движка правил: https://github.com/contactless/wb-rules/blob/master/README.md
The most complete description of the rules engine: https://github.com/wirenboard/wb-rules/blob/master/README.md






== Новые возможности последних версий ==
== What's new in the latest versions ==


* [[Special:MyLanguage/Движок_правил_wb-rules_1.7|Движок правил wb-rules 1.7]]
* [[Special:MyLanguage/Движок_правил_wb-rules_1.7/en|wb-rules 1.7 rules engine]]






== В разработке ==
== under development ==


Описание возможностей будущих версий движка правил можно прочесть здесь:
A description of the features of future versions of the rules engine can be found here:
* [[Special:MyLanguage/Движок_правил_wb-rules_2.0|Движок правил wb-rules 2.0]]
* [[Special:MyLanguage/Движок_правил_wb-rules_2.0/en|Rules engine wb-rules 2.0]]
wb_editors
33

правки