Перейти к содержанию

Навигация

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

Новая страница: «<syntaxhighlight lang="js"> defineVirtualDevice("vdev", { ... cells: { ... mycell: { type: "value", value: "10",…»
(Новая страница: «The updated wb-rules engine contains a number of important innovations regarding the logic of scripting.»)
(Новая страница: «<syntaxhighlight lang="js"> defineVirtualDevice("vdev", { ... cells: { ... mycell: { type: "value", value: "10",…»)
 
(не показано 38 промежуточных версий этого же участника)
Строка 2: Строка 2:
The updated wb-rules engine contains a number of important innovations regarding the logic of scripting.
The updated wb-rules engine contains a number of important innovations regarding the logic of scripting.


= Сценарии =
= Scripts =




== Изоляция сценариев ==
== Isolation of scripts ==


Начиная с версии wb-rules 1.7, локальные переменные и функции, обьявленные в файле сценария не видны в других сценариях.
Starting with wb-rules v.1.7, local variables and functions declared in the script file are not visible in other scripts.
Таким образом, каждый сценарий может определять свои функции и переменные без риска изменить поведение других сценариев.
Thus, each script can define its own functions and variables without the risk of changing the behavior of other scripts.




=== Пример ===
=== Example ===


В качестве примера приведём два сценария, одновременно запускаемых в движке правил.
As an example, here are two scenarios that run simultaneously in the rules engine.
Каждый сценарий определяет переменные и функции.
Each scenario defines variables and functions.


В предыдущих версиях wb-rules обращение к переменной, изменяемой в нескольких
In previous versions of wb-rules, refering to a global variable, that is modified in several
файлах сценариев, может привести к неопределённому поведению. В версиях, начиная с 1.7,
script files, may cause undefined behavior. Starting from v.1.7,
поведение строго определено и такое же, как будто сценарий единственный в системе.
the behavior is strictly defined and is the same as if the script is the only one in the system.


В комментариях указан вывод команд log для ранних версий и для актуальной версии. Обратите внимание на var перед переменными.
The comments indicate the output of the log commands for earlier versions and for the current version. Note the 'var' before the variables.


'''Сценарий 1 (rules1.js)'''
'''rules1.js'''
<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
var test1 = 42;
var test1 = 42;
Строка 33: Строка 33:
</syntaxhighlight>
</syntaxhighlight>


'''Сценарий 2 (rules2.js)'''
''' rules2.js'''
<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
var test1 = 84;
test1 = 84;
var test2 = "Hello";
test2 = "Hello";


setInterval(function myFuncTwo() {
setInterval(function myFuncTwo() {
Строка 45: Строка 45:




Было:
Before:
<pre>
<pre>
2019-01-05 17:29:50myFuncTwo called
2019-01-05 17:29:50myFuncTwo called
Строка 56: Строка 56:




Стало:
Now:
<pre>
<pre>
2019-01-05 17:28:42myFuncTwo called
2019-01-05 17:28:42myFuncTwo called
Строка 70: Строка 70:




=== Примечание ===
=== Note ===


В предыдущих версиях wb-rules для изоляции правил рекомендовалось использовать замыкание, т.е.  
In previous versions of wb-rules, it was recommended to use loopback to isolate rules, i.e. to isolate rules.  
оборачивание кода сценария в конструкцию:
wrapping the script code into a construct:
<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
(function() {
(function() {
     // код сценария идёт здесь
     // script code goes here
})();
})();
</syntaxhighlight>
</syntaxhighlight>


Начиная с версии 1.7, в подобной конструкции обычно нет необходимости. Тем не менее, старые сценарии,
Starting from version 1.7, such a construction is usually not necessary. However, the old scripts,
использующие эту конструкцию, продолжат работу без изменений в поведении.
using this construction, will continue to work without changes in behavior.




=== Обходные пути ===
=== workarounds ===


Если в вашей системе использовалось общее глобальное пространство для хранения общих данных и функций,
If your system used a shared global space to store shared data and functions,
есть несколько способов реализации такого поведения:
there are several ways to implement this behavior:




==== Постоянное хранилище ====
==== Permanent repository ====


Для обмена данными также можно использовать глобальные постоянные хранилища (PersistentStorage).
You can also use global persistent storages to exchange data.


'''Внимание:''' при использовании глобальных постоянных хранилищ может произойти совпадение имён, в
'''Warning:''' when using global persistent stores, a name match may occur,  
этом случае возможно труднообнаруживаемое нарушение поведения.
in this case, a hard-to-detect behavior violation is possible.


<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
Строка 102: Строка 102:
/// ...
/// ...


ps.myvar = "value"; // это значение доступно для всех пользователей хранилища с именем "my-global-storage"
ps.myvar = "value"; // this value is available for users of "my-global-storage"
</syntaxhighlight>
</syntaxhighlight>




==== Прототип глобального объекта ====
==== A prototype of the global object ====


'''ВНИМАНИЕ:''' метод считается "грязным", т.к. все переменные и функции, опубликованные таким образом,
'''WARNING:''' method is considered "dirty" because all variables and functions published in this way,
становятся доступными всем сценариям в системе. Старайтесь избегать этого способа. За неопределённое
become available to all scenarios in the system. Try to avoid this method. The programmer is solely responsible for the undefined behavior of the device when using this method
поведение при использовании этого метода несёт ответственность сам программист.


Глобальные объекты всех сценариев имеют общий объект-''прототип'', в котором определены стандартные функции
Global objects of all scenarios have a common object-"prototype", in which standard functions are defined
wb-rules (такие, как defineRule, setTimeout и т.д.). Через него можно передавать переменные или функции
wb-rules (such as defineRule, setTimeout, etc.). It can be used to pass variables or functions
в общую область видимости.
General field of view.


<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
global.__proto__.myVar = 42; // теперь myVar - общая переменная для всех сценариев
global.__proto__.myVar = 42; // now myVar - is a common variable for all scripts


// из других сценариев к переменной можно обращаться так
// the variable can be accessed from other scripts as follows
log("shared myVar: {}", myVar);
log("shared myVar: {}", myVar);


// или вот так, что чуть более аккуратно, т.к. однозначно показывает, где определена переменная
// or like this, which is a bit more accurate, because it clearly shows where the variable is defined
log("shared myVar: {}", global.__proto__.myVar);
log("shared myVar: {}", global.__proto__.myVar);
</syntaxhighlight>
</syntaxhighlight>


Правило поиска переменной в первом случае будет выглядеть так:
The variable search rule in the first case will look like this:


# Проверяем, есть ли myVar среди локальных переменных (определённой как var myVar = ...).
# Check if there is myVar among local variables (defined as var myVar = ...).
# Если нет, проверяем, есть ли myVar в глобальном объекте (определённой как myVar = ...).
# If not, check if there is myVar in the global object (defined as myVar = ...).
# Если нет, проверяем, есть ли myVar в ''прототипе'' глобального объекта (определённой как global.__proto__.myVar).
# If not, check if myVar is in the "prototype" of the global object (defined as global.__proto__.myVar).


Поиск останавливается, как только переменная найдена.
The search stops as soon as the variable is found.


Таким образом, первый способ обращения будет работать только в том случае, если myVar не определена в верхних областях видимости.
Thus, the first way of addressing will only work if myVar is not defined in the upper scopes.






== Постоянное хранилище данных ==
== Persistent Data Storage ==


В wb-rules 1.7 добавлена поддержка постоянных хранилищ. По сути, это объекты, значения в которых будут сохраняться
WB-rules 1.7 adds support for persistent storage. In fact, these are the objects in which the values will be stored
даже при потере питания контроллера. Такие хранилища удобно использовать для хранения состояний или конфигурации.
even if the controller loses power. These stores are useful for storing States or configurations.


<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
Строка 150: Строка 149:
</syntaxhighlight>
</syntaxhighlight>


Поддерживаются только глобальные хранилища, т.е. видимые по одному и тому же имени из всех файлов сценариев.
Only global repositories, that is, visible by the same name from all script files, are supported.




== Виртуальные устройства ==
== Virtual devices ==


В предыдущих версиях wb-rules значения контролов виртуальных устройств хранились только в MQTT retained, что не очень надёжно (в случае
In previous versions of wb-rules, the values of virtual device controls were stored only in MQTT retained, which is not very reliable (in the case of
потери питания данные могли быть легко утеряны). Начиная с версии 2.0, эти значения сохраняются также в специальное хранилище в постоянной
power loss data could easily be lost). Starting with version 2.0, these values are also stored in a special permanent storage
памяти и восстанавливаются при загрузке сценария.
memory and restored when the script is loaded.


Если необходимо каждый раз при перезагрузке скрипта восстанавливать строго определённое значение (т.е. не восстанавливать предыдущее сохранённое),
If it is necessary to restore a strictly defined value (i.e. not to restore the previous saved value) every time the script is restarted,
можно добавить в описание контрола поле forceDefault:
you can add the forceDefault field to the control description:


<syntaxhighlight lang="js">
<syntaxhighlight lang="js">
Строка 170: Строка 169:
             type: "value",
             type: "value",
             value: "10",
             value: "10",
             forceDefault: true // при каждой загрузке сценария поле mycell будет получать значение 10
             forceDefault: true // every time the script box mycell will receive a value of 10
         }
         }
     }
     }
});
});
</syntaxhighlight>
</syntaxhighlight>
12 063

правки