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

Навигация

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

Новая страница: «<syntaxhighlight lang="js"> defineVirtualDevice("vdev", { ... cells: { ... mycell: { type: "value", value: "10",…»
(Новая страница: «'''WARNING:''' method is considered "dirty" because all variables and functions published in this way, become available to all scenarios in the system. Try to avo…»)
(Новая страница: «<syntaxhighlight lang="js"> defineVirtualDevice("vdev", { ... cells: { ... mycell: { type: "value", value: "10",…»)
 
(не показано 15 промежуточных версий этого же участника)
Строка 111: Строка 111:
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
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">
Строка 149: Строка 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">
Строка 169: Строка 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

правки