Wb-mqtt-serial templates/en: различия между версиями

м
FuzzyBot переименовал страницу Драйвер wb-mqtt-serial:Примеры написания шаблонов/en в Wb-mqtt-serial templates/en без оставления перенаправления: Часть переводимой страницы Драйвер wb-mqtt-serial:Примеры написания шаблонов.
(Новая страница: «=== Device channels === File:Channel_properties_mqtt_serial.png|450px|thumb|right|Channel parameters are described in wb-mqtt-serial.schema.json (made in app […»)
м (FuzzyBot переименовал страницу Драйвер wb-mqtt-serial:Примеры написания шаблонов/en в Wb-mqtt-serial templates/en без оставления перенаправления: Часть переводимой страницы Драйвер wb-mqtt-serial:Примеры написания шаблонов.)
 
(не показаны 34 промежуточные версии 1 участника)
Строка 1: Строка 1:
<languages/>
<languages/>
 
 
=== The general structure of the device template
=== The general structure of the device template===
===


A device template file is a [https://en.wikipedia.org/wiki/JSON JSON] structure that describes device parameters. The template allows comments. The JSON structure is written inside the space between the opening and closing braces:<code> { ... }</code>
A device template file is a [https://en.wikipedia.org/wiki/JSON JSON] structure that describes device parameters. The template allows comments. The JSON structure is written inside the space between the opening and closing braces:<code> { ... }</code>
Строка 62: Строка 61:
"channels": [
"channels": [
         {
         {
             "name": "Имя канала 1",
             "name": "Channel name1",
             ...
             ...
         },
         },
         {
         {
             "name": "Имя канала 2",
             "name": "Channel name2",
             ...
             ...
         },
         },
Строка 73: Строка 72:
</syntaxhighlight>
</syntaxhighlight>


Структура содержит следующий набор полей.
The structure contains the following set of fields.


[[File:Vartype_properties_mqtt_serial.png|450px|thumb|right|формат представления данных в Modbus-регистрах, описывается в wb-mqtt-serial.schema.json (подготовлено в [http://www.bodurov.com/JsonFormatter/ Collapsible JSON Formatter])]]
[[File:Vartype_properties_mqtt_serial.png|450px|thumb|right|the format of data representation in Modbus-registers is described in wb-mqtt-serial.schema.json (made in app [http://www.bodurov.com/JsonFormatter/ Collapsible JSON Formatter])]]


* '''name''' — имя канала, уникальное для устройство имя канала  
* '''name''' — имя канала, уникальное для устройство имя канала  
Строка 84: Строка 83:
* '''format''' — тип переменной, описывающей значение, см. рис.
* '''format''' — тип переменной, описывающей значение, см. рис.


В простейшем случае достаточно полей "name", "reg_type", "address" и "type". Описания остальных типов параметров полностью перечислены в схеме wb-mqtt-serial.schema.json.
*'''name''' — the channel name that is unique to the device
*'''reg_type''' — type of Modbus register, one of "coil", "discrete", "holding", "holding_single", "holding_multi", "input", "direct" types
*'''address''' — the address of the Modbus register associated with the channel.
*'''type''' — type of control, a virtual element for data representation in the Web-interface of the controller: "switch", "pushbutton", "range", "rgb" and others; fully listed in the scheme wb-mqtt-serial.schema.json.
*'''readonly''' — "true" if the values can only be read.
*'''format''' — '''type''' of the variable describing the value, see figure.


=== Примеры шаблонов устройств ===
In the simplest case, the fields "name", "reg_type", "address" and "type"are sufficient. Descriptions of other parameter types are fully listed in the wb-mqtt-serial.schema.json scheme.


Ниже приведены примеры файлов шаблонов для некоторых устройств Wiren Board, охватывающие основной список используемых параметров при создании шаблонов.
=== Examples of device templates===
 
The following are sample template files for some Wiren Board devices, covering a basic list of options used when creating templates.


----
----
Строка 94: Строка 100:
==== WB-MS-THLS v.2 ====
==== WB-MS-THLS v.2 ====


Устройство [[WB-MS_Modbus_Sensor|WB-MS-THLS]] — универсальный комбинированный Modbus-датчик температуры, влажности, освещённости и звукового давления. Устройство предоставляет доступ к данным через input-регистры Modbus. Первоначальные настройки устройства записаны в holding-регистры, но не используются для получения данных и управления устройством, поэтому в шаблон не входят.
The [[WB-MS_Modbus_Sensor/en|WB-MS]] device is a universal combined Modbus sensor for temperature, humidity, lighting and sound pressure. The device provides access to data via Modbus input registers. The initial settings of the device are recorded in the holding registers, but are not used to obtain data and control the device, so the template is not included.You can see the full template code via the following link.
По ссылке "Expand" можно увидеть полный код шаблона.


<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
Строка 167: Строка 172:
</div>
</div>


В настройках устройства интересен параметр <syntaxhighlight lang="JSON">    "max_read_registers": 0,</syntaxhighlight> Этот параметр описывает максимальное количество регистров, считываемых с устройства при запросе. Значение по умолчанию — 1, в нашем случае мы указываем считывать все регистры за один проход (bulk read).
There is an interesting parameter in the settings of the device: <syntaxhighlight lang="JSON">    "max_read_registers": 0,</syntaxhighlight> This parameter describes the maximum number of registers that can be read from the device when requested. The default value is 1, in our case we specify to read all registers in one pass (bulk read).
В настройках канала "Temperature" имеются три параметра, на которые стоит обратить внимание:
In the settings of the channel "Temperature" there are three parameters that are worth paying attention to:
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
     "format": "s16",
     "format": "s16",
Строка 174: Строка 179:
     "error_value": "0x7FFF"
     "error_value": "0x7FFF"
</syntaxhighlight>
</syntaxhighlight>
Параметр '''"format": "s16"''' указывает на то, что число в регистрах представлено в виде знакового 16-битного целого, '''"scale": 0.1''' — говорит о том, что полученное из регистров значение следует домножить на коэффициент масштабирования 0,1 для получения значения температуры, а параметр '''"error_value": "0x7FFF"''' задает значение, получаемое из регистра, указывающее на то, что при опросе датчика произошла ошибка. Такой параметр будет выделен красным цветом в Web-интерфейсе контроллера. Применять такой параметр следует, если вы знаете, какое значение выдает ваше устройство в случае ошибки.
Parameter'''"format": "s16"''' indicates that the number in the registers is represented as a signed 16-bit integer, '''"scale": 0.1''' — indicates that the value obtained from the registers should be multiplied by the scaling factor 0.1 to obtain the temperature value, and the parameter '''"error_value": "0x7FFF"''' sets the value sent from the register, indicating that an error occurred during the sensor poll. This parameter will be highlighted in red in the web interface of the controller. You should use this option if you know what value your device sends in case of an error.




----
----


==== WB-MRGBW-D ====
==== WB-MRGBW-D ==== [[WB-MRGBW-D/en|WB-MRGBW-D]] is a four channel dimmer to control the led strip. Can control RGB+W tape or four single color tapes independently. Brightness settings are stored in holding registers; the template describes which registers can be changed to get the desired brightness of the channels, track the dimmer button presses and get the value of the number of clicks.You can see the full template code via the following link.
Устройство [[WB-MRGBW-D|WB-MRGBW-D]] — четырехканальный диммер для управления светодиодными лентами. Может управлять лентой RGB+W либо независимо четырьмя одноцветными лентами.  
Настройки яркости хранятся в holding-регистрах; шаблон описывает, какие регистры можно менять для получения нужной яркости каналов, отслеживать нажатия на кнопки диммера и получать значения количества нажатий.По ссылке "Expand" можно увидеть полный код шаблона.


<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
Строка 271: Строка 274:
  </syntaxhighlight>
  </syntaxhighlight>
</div>
</div>
В этом шаблоне составной канал RGB задает одновременно яркости трех цветовых компонентов ленты, хранящихся в трех holding-регистрах и описывается следующим образом:
In this template, the RGB composite channel sets the brightness of three color ribbon components stored in three holding registers at the same time and is described as follows:
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
     {
     {
Строка 293: Строка 296:
</syntaxhighlight>
</syntaxhighlight>


Канал белого цвета управляется отдельно,  
The white channel is controlled separately,
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
     {
     {
Строка 303: Строка 306:
     },  
     },  
</syntaxhighlight>
</syntaxhighlight>
Здесь указано максимальное значение, которое можно установить для ползунка яркости белого — 255:<syntaxhighlight lang="JSON">"max": 255</syntaxhighlight>
The maximum value that can be set for the white brightness slider is 255:
<syntaxhighlight lang="JSON">"max": 255</syntaxhighlight>


Серийный номер устройства (канал "Serial NO") считывается как беззнаковое 32-битное целое: <syntaxhighlight lang="JSON">"format": "u32"</syntaxhighlight>
The serial number of the device (channel "Serial NO") is read as an unsigned 32-bit integer:
<syntaxhighlight lang="JSON">"format": "u32"</syntaxhighlight>


----
----


==== WBIO-DO-R10A-8 ====
==== WBIO-DO-R10A-8 ====
Устройство [[WBIO-DO-R10A-8_Relay_Module|WBIO-DO-R10A-8]] — релейный боковой модуль, который подключается непосредственно к WBIO-разъему контроллера, и не управляется по Modbus. Но при подключении его через устройство расширения WB-MIO или WB-MIO-E становится полноценным Modbus-устройством, для которого имеется соответствующий шаблон.  
Устройство [[WBIO-DO-R10A-8_Relay_Module/en|WBIO-DO-R10A-8]] — is a relay side module that connects directly to the controller's WBIO connector and is not Modbus controlled. But when it is connected via a WB-MIO or WB-MIO-E expansion device, it becomes a full-fledged Modbus device for which there is a corresponding template.You can see the full template code via the following link.
По ссылке "Expand" можно увидеть полный код шаблона.


<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
Строка 417: Строка 421:




В этом шаблоне следует обратить внимание на следующие параметры устройства.
In this template, you should pay attention to the following device settings.
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
     "protocol": "modbus_io",
     "protocol": "modbus_io",
Строка 426: Строка 430:
</syntaxhighlight>
</syntaxhighlight>


Параметр '''"protocol": "modbus_io"''' указывает, что устройство подключается оп специальному протоколу к модулю расширения. Параметры '''"stride": 1000''' и '''"shift": 500''' задают сдвиг регистров в зависимости от того, в каком порядке подключены модули к модулю расширения.  
Option ''' ''protocol'': ''modbus_io'' ''' indicates that the device connects to the extension module via special protocol. The parameters '''"stride": 1000''' and '''"shift":500''' set the shift of registers depending on the order in which the modules are connected to the extension module.
 
 
Shift = (((SlaveId.Secondary - 1) % 4) + 1) * DeviceConfig()->Stride + DeviceConfig()->Shift;
Here stride — DeviceConfig()->Stride, a shift — DeviceConfig()->Shift.
 
Register shift (the number to be added to the base register number) is calculated by the formula:<syntaxhighlight lang="C++">Shift = (((SlaveId.Secondary - 1) % 4) + 1) * DeviceConfig()->Stride + DeviceConfig()->Shift;</syntaxhighlight> Здесь stride — ''DeviceConfig()->Stride'', a shift — ''DeviceConfig()->Shift''. Each connected device has a serial number (''SlaveId.Secondary'') starting with 1 for the first device. (Here the sign "%" shows modulу division.)


Сдвиг регистров (число, которое нужно добавить к базовому номеру регистра) вычисляется по формуле: <syntaxhighlight lang="C++">Shift = (((SlaveId.Secondary - 1) % 4) + 1) * DeviceConfig()->Stride + DeviceConfig()->Shift;</syntaxhighlight> Здесь stride — ''DeviceConfig()->Stride'', a shift — ''DeviceConfig()->Shift''. Каждое подключенное устройство имеет порядковый номер (''SlaveId.Secondary''), начинающийся с 1 для первого устройства. (Здесь знаком "%" обозначается деление по модулю.)


Например, подставляя значения shift и stride в формулу, получаем: <syntaxhighlight lang="C++">Shift = ((( 1 - 1) % 4) + 1) * 500 + 1000 = (0 + 1) * 500 + 1000 = 1500</syntaxhighlight> То есть ко всем регистрам, указанным в шаблоне, надо добавить 1500.
For example, substituting the values of shift and stride in the formula: <syntaxhighlight lang="C++">Shift = ((( 1 - 1) % 4) + 1) * 500 + 1000 = (0 + 1) * 500 + 1000 = 1500</syntaxhighlight> So, you need to add 1500 to all registers specified in the template.


Еще один важный параметр — setup-секция, массив
Another important parameter — setup-section, array
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
     "setup": [    {
     "setup": [    {
Строка 442: Строка 451:
     ...]  
     ...]  
</syntaxhighlight>
</syntaxhighlight>
Он описывает регистры и значения, которые однократно заносятся в эти регистры при инициализации устройства (при запуске или перезапуске wb-mqtt-serial). Его можно использовать для конфигурирования устройств для работы в каком-то определенном режиме, задавать изначальные значения яркости, положения сервоприводов, состояния реле, режима работы с входами релейных модулей и т. п.
It describes the registers and values that are entered once in these registers when the device is initialized (when WB-mqtt-serial is started or restarted). It can be used to configure devices to operate in a particular mode, set the initial values of brightness, servo position, relay status, mode of operation with the inputs of relay modules, etc.


----
----
Строка 448: Строка 457:
==== WB-MAP3H ====
==== WB-MAP3H ====


Устройство [[WB-MAP3H_Power_Meter|WB-MAP3H]] — трехканальный счетчик электроэнергии. Он измеряет большое количество параметров электрической сети. Поскольку опрос всех регистров такого устройства может занять достаточно много времени, имеется несколько шаблонов, содержащих оптимальный набор параметров для решения текущей задачи. Мы рассмотрим базовый шаблон. По ссылке "Expand" можно увидеть полный код шаблона.
[[WB-MAP3H_Power_Meter/en|WB-MAP3H]] — three-channel electricity meter. It measures a large number of electrical network parameters. Since it can take quite a long time to poll all registers of such a device, there are several templates that contain the optimal set of parameters for the current task. We'll look at the basic pattern. You can see the full template code via the following link.


<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
<div class="mw-collapsible mw-collapsed"  style="width:500px; overflow: hidden;" >
Строка 860: Строка 869:
</div>
</div>


На что следует обратить внимание в этом шаблоне? В первую очередь в параметрах устройства мы указываем, что одновременно следует считывать не более 60 регистров, чтобы не останавливать надолго опрос остальных устройств: '''"max_read_registers": 60'''.  
What is so important in this template? First of all, we specify in the device parameters that no more than 60 registers should be read at the same time, so as not to stop for a long time the polling of other devices:  
Также показательным является параметр, описывающий накопленную реактивную энергию по фазе L1:
'''"max_read_registers" : 60'''. Also  the parameter describing the accumulated reactive energy in the phase L1 is indicative:
<syntaxhighlight lang="JSON">
<syntaxhighlight lang="JSON">
   {
   {
Строка 875: Строка 884:
</syntaxhighlight>  
</syntaxhighlight>  


Здесь стоит обратить внимание на то, что адрес регистра может задаваться и в шестнадцатеричном виде: '''"address": "0x1224"''', вещественный коэффициент масштабирования можно задавать в экспоненциальной записи: '''"scale": 3.125e-05''', при считывании значения округлять его до нужного порядка: '''"round_to": 0.0001''', а также учитывать, что число в Modbus-регистрах хранится в порядке от младшего к старшему: '''"word_order": "little_endian"'''.
Here you should pay attention to the fact that the address of the register can be set in hexadecimal form:''' "address": "0x1224" ''', the real scaling factor can be set in the exponential notation:''' "scale": 3.125 e-05'''', when reading the value round it to the desired order:''' "round_to": 0.0001''', and also take into account that the number in the Modbus-registers is stored in order from the youngest to the oldest: '''"word_order": "little_endian"'''. Storage formats for 16-bit Modbus registers are described as follows:
Форматы хранения для 16-битных Modbus регистров описываются следующим образом:
<pre>
<pre>
         big-endian    : ( [0xAA 0xBB] [0xCC 0xDD] => 0xAABBCCDD )  
         big-endian    : ( [0xAA 0xBB] [0xCC 0xDD] => 0xAABBCCDD )  
         little-endian : ( [0xAA 0xBB] [0xCC 0xDD] => 0xCCDDAABB )
         little-endian : ( [0xAA 0xBB] [0xCC 0xDD] => 0xCCDDAABB )
</pre>
</pre>
По умолчанию предполагается формат big-endian.
The default format is big-endian.


Типы переменных, используемых в шаблонах, перечислены в следующей таблице:
The types of variables used in the templates are listed in the following table:
{| class="wikitable"
{| class="wikitable"
! Обозначение !! Тип
! Designation !! Type
|-
|-
| s16 || Signed 16-bit integer
| s16 || Signed 16-bit integer
Строка 922: Строка 930:
|}
|}


=== Источники информации ===
=== Information resources ===
В этой статье описаны основные правила создания шаблонов устройств для контроллеров Wiren Board. Информация изменяется и дополняется по мере обновления ПО и выходу новых продуктов. Самая полная и актуальная информация может быть найдена в следующих источниках:
This article describes the basic rules for creating device templates for Wiren Board controllers. The information changes and is updated as the SOFTWARE is updated and new products are released. The most complete and up-to-date information can be found in the following sources:
* в описании сервиса [https://github.com/contactless/wb-mqtt-serial/ wb-mqtt-serial] на GitHub;
*in the WB-mqtt-serial service description on GitHub;
* в файлах самих шаблонов.
*in the template files
* в файле [https://github.com/contactless/wb-mqtt-serial/blob/master/wb-mqtt-serial.schema.json wb-mqtt-serial.schema.json] на GitHub.
in the [https://github.com/contactless/wb-mqtt-serial/blob/master/wb-mqtt-serial.schema.json wb-mqtt-serial.schema.json] file on GitHub.
wb_editors
14 355

правок