Relay Module Modbus Management/en: различия между версиями
Admin (обсуждение | вклад) |
(Новая страница: «| rowspan="3" | 9 .. (9+'''x'''-1) | rowspan="3" | holding | rowspan="3" | RW | rowspan="2" | 0 | style="text-align:left;" | * '''0''': non-locking butto…») |
||
(не показано 36 промежуточных версий 3 участников) | |||
Строка 2: | Строка 2: | ||
<!-- {{DISPLAYTITLE:Управление модулями реле Wiren Board по протоколу Modbus}} --> | <!-- {{DISPLAYTITLE:Управление модулями реле Wiren Board по протоколу Modbus}} --> | ||
== Modbus parameters == | |||
== | === Modbus address === | ||
[[Файл:modbus_address_mr14.png|150px|thumb|left|Modbus-address set on manufacture]] | |||
Modbus-address of the Wiren Board devices is easy to determine — it is printed on the sticker (the address is in decimal format). The new address of the device is written by the command WRITE_SINGLE_REGISTER to the storage register (holding register) with the address 128 (0x80). For details on how to determine (if the address has been changed) or change the Modbus address of the module, see [[Определение и изменение Modbus-адреса устройств Wirenboard/en|Define and change the Modbus address of Wiren Board devices]]. | |||
=== Modbus commands supported by the device === | |||
The Wirenboard relay modules support all major Modbus commands. Read more here: [[Протокол_Modbus/en#Register reading and writing function codes|Register reading and writing function codes]]. | |||
=== Safe mode === | === Safe mode === | ||
Строка 28: | Строка 34: | ||
** '''Mapping-matrix''' (see detailed description below) | ** '''Mapping-matrix''' (see detailed description below) | ||
The mode set separately for each channel. To | The mode can be set separately for each channel. To do this, register 5 must have a value of "0", and the mode for each channel is written to the storage registers starting from address 9 for the first channel, etc. | ||
There | There is an outdated method - setting the mode for all channels at the same time. To do this, write the appropriate number in the storage register with address 5. | ||
==== Mapping-matrix ==== | ==== Mapping-matrix ==== | ||
Строка 36: | Строка 42: | ||
Starting from firmware v.1.9.0, '''mode 2''' is also provided for individual channels-disable all outputs, and '''operating modes (4 and 5)''' in accordance with the mapping matrix (see below).In this and later versions of firmware versions modules have flexible settings of the interaction of inputs and outputs of relay modules using a special mapping matrix: a table in which for each input is encoded change of any relay output state when the state of this input changes. A detailed description can be found in [[I/O_Mapping_Matrix/en|I/O Mapping Matrix]]. | Starting from firmware v.1.9.0, '''mode 2''' is also provided for individual channels-disable all outputs, and '''operating modes (4 and 5)''' in accordance with the mapping matrix (see below).In this and later versions of firmware versions modules have flexible settings of the interaction of inputs and outputs of relay modules using a special mapping matrix: a table in which for each input is encoded change of any relay output state when the state of this input changes. A detailed description can be found in [[I/O_Mapping_Matrix/en|I/O Mapping Matrix]]. | ||
= Relay module register card = | === Relay module register card === | ||
* '''x''' — number of relay outputs; | * '''x''' — number of relay outputs; | ||
* '''y''' | * '''y''' is the number of digital inputs. | ||
(for modules WB-MRM2 see registers map at the description page of [[WB-MRM2/en|this module]]) | |||
{| border="1" class="wikitable" style="text-align:center; width:1000px;" | {| border="1" class="wikitable" style="text-align:center; width:1000px;" | ||
Строка 61: | Строка 67: | ||
| 0 | | 0 | ||
| style="text-align:left;" | | | style="text-align:left;" | | ||
* '''0''': buttons without locking | |||
|| | * '''1''': switch with lock | ||
|| | * '''3''': disable interaction | ||
|| mode of interaction of digital inputs with relay outputs. The input status registers and the pressure counter continue to operate in all modes. || The register was used in the old configuration mechanism. It is recommended to leave it set to 0 and the inputs are configured via the individual registers 9 .. (9+'''x'''-1) | |||
|- | |- | ||
| 6 | | 6 | ||
Строка 81: | Строка 88: | ||
| style="text-align:left;" | | | style="text-align:left;" | | ||
* '''0''': non-locking buttons | * '''0''': non-locking buttons | ||
* '''1''': switch with | * '''1''': switch with separate actuator | ||
* '''3''': disable interaction | * '''3''': disable interaction | ||
| rowspan="3" | | | rowspan="3" | single digital input interaction mode with corresponding relay output; | ||
"0" should be written in register 5 | |||
| | | | ||
|- | |- | ||
Строка 89: | Строка 97: | ||
| rowspan="2" style="text-align:left;" | | | rowspan="2" style="text-align:left;" | | ||
* '''2''': | * '''2''': отключать все реле при нажатии | ||
* '''4''': | * '''4''': управлять в соответствии с [[I/O_Mapping_Matrix|mapping-матрицей]] | ||
* '''5''': | * '''5''': управлять в соответствии с [[I/O_Mapping_Matrix|mapping-матрицей]], через 20 минут повторно имитировать состояние ввода | ||
| | |Начиная с прошивки 1.9.0 | ||
|- | |- | ||
|1 | |1 | ||
| | |Начиная с прошивки 1.12.0 | ||
|- | |- | ||
Строка 103: | Строка 111: | ||
| | | | ||
|style="text-align:left;"| | |style="text-align:left;"| | ||
* '''0''': | * '''0''': кнопки без фиксации | ||
* '''1''': | * '''1''': выключатель с фиксацией | ||
* '''3''': | * '''3''': отключить взаимодействие | ||
| | | режим работы цифрового входа 0 для отключения всех реле | ||
| | | | ||
|- | |- | ||
Строка 113: | Строка 121: | ||
|style="text-align:left;" | | |style="text-align:left;" | | ||
* '''2''': | * '''2''': отключать все реле при нажатии | ||
* '''4''': | * '''4''': управлять в соответствии с [[I/O_Mapping_Matrix|mapping-матрицей]] | ||
* '''5''': | * '''5''': управлять в соответствии с [[I/O_Mapping_Matrix|mapping-матрицей]], через 20 минут повторно имитировать состояние ввода | ||
| | | режим работы цифрового входа 0; в регистре 5 должен быть записан "0" | ||
| | |Начиная с прошивки 1.9.0 | ||
|- | |- | ||
| | |||
| 32 .. (32+'''y'''-1) || input || R || 0 || 16-bit unsigned int || счетчик срабатываний входа 1 .. '''y''' || | |||
|- | |- | ||
| 104-105 || input || R || || 32-bit unsigned int || Время работы устройства (uptime counter) в секундах || | |||
|- | |||
| | | 120 (0x78) || holding || RW || 0 || отличное от 0 || запись в регистр вызывает перезагрузку модуля без сохранения состояния || | ||
|- | |||
| 121 (0x79) || holding || R || - || мВ || текущее напряжение питания модуля || | |||
|- | |||
| 128 (0x80) || holding || RW || 1 || 1 — 247 | |||
|| Modbus-адрес устройства || | |||
|- | |||
| 129 (0x81) || holding || RW || 0 || 0 или 1 || Переход в [[WB-MCU-Flasher|режим загрузчика]] | |||
|1.10.0 | |||
|- | |||
| 200-205 || holding || R || {'X','X','X','X','X','X'} || || сигнатура устройства (см. таблицу ниже) || | |||
|- | |||
| 220-241 || holding || R || || __date__ __time__|| дата сборки прошивки || | |||
|- | |||
|250-266 | |||
|input | |||
|R | |||
| | |||
|строка, null-terminated | |||
|версия прошивки || | |||
|- | |||
|270-271 | |||
|input | |||
|R | |||
| | |||
|32-bit unsigned int | |||
|уникальный идентификатор (S/N) | |||
|- | |||
| 384-447 || holding || RW || 0 || || регистры [[I/O_Mapping_Matrix|mapping-матрицы]] || Начиная с версии прошивки 1.9.0 | |||
|- | |- | ||
|} | |} | ||
В прошивках версии 1.6.0 и позднее поддерживаются дополнительные регистры настройки параметров обмена данными по RS-485: | |||
{| border="1" class="wikitable" style="text-align:center; width:1000px;" | |||
!Регистр / адрес | |||
!Тип | |||
!Чтение/запись | |||
!Значение по умолчанию | |||
!Формат | |||
!Назначение | |||
|- | |||
| 110 || holding || RW || 96 || baud rate / 100 || скорость порта RS-485, '''делённая на 100'''. Допустимые скорости: 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 <br>([[UART_Communication_Settings|Настройка параметров обмена данными по RS-485 для modbus-устройств Wiren Board]]) | |||
|- | |||
| 111 || holding || RW || 0 || || настройка бита чётности порта RS-485. Допустимые значения: 0 - нет бита чётности (none), 1 - нечётный (odd), 2 - чётный (even) | |||
|- | |||
| 112 || holding || RW || 2 || || количество стоп-битов порта RS-485. Допустимые значения: 1, 2 | |||
|- | |||
|} | |||
По адресу 200 лежит сигнатура релейного модуля длиной 6 байт. Сигнатура уникальна для каждой модели устройств Wiren Board и позволяет идентифицировать модель по Modbus: | |||
{| class="wikitable" | |||
! style="font-weight: bold;" | Модуль | |||
! style="font-weight: bold;" | Сигнатура | |||
|- | |||
|WB-MRPS6 | |||
|MRPS6 | |||
|- | |||
| WB-MR6C | |||
| WBMR6 | |||
|- | |||
| WB-MR3xV | |||
| WBMR3 | |||
|- | |||
| WB-MR6xV | |||
| WBMR6 | |||
|- | |||
| WB-MR14 | |||
| WBMR14 | |||
|- | |||
| WB-MR11 | |||
| WBMR11 | |||
|- | |||
| WB-MRM2 | |||
| WBMR2 | |||
WBMR2m | |||
|} | |||
Для получения сигнатуры нужно выполнить команду READ_HOLDING_REGISTERS по адресу 200 (длина 6 регистров). Запись в эту область памяти не поддерживается, при попытке записи в недопустимое место возвращается ошибка 3. Пустые места в тексте сигнатуры забиваются значением 0x00. | |||
Начиная с регистра 220 записана дата сборки прошивки, в формате "число'''x00'''время'''x00'''" в виде строки (пример: 'Jan 27 2017 17:01:13'). Длина записи — 21 регистр. | |||
Значение состояния каждого реле хранится в регистрах флагов (coil). У 1-го реле адрес регистра 0, у 2-го — 1 и т.д. | |||
== Управление модулем из командной строки == | |||
Программное обеспечение контроллера Wiren Board включает в себя утилиту modbus_client для работы с устройствами, подключенными к выходам RS-485, по протоколу Modbus, подробное описание команды находится на странице [[Modbus-client]]. Доступ к командной строке описан в статье [[SSH]]. | |||
=== Пример чтения регистров === | |||
Проверим, верно ли, что мы подключились именно к модулю нужного типа. (Сервис wb-mqtt-serial должен быть предварительно остановлен). По адресу 200 хранится уникальная сигнатура длиной в 6 регистров. Прочтем 6 регистров, начиная с адреса 200, и преобразуем полученный шестнадцатеричный ответ в символьную строку: | |||
<syntaxhighlight lang="bash">echo -e `modbus_client --debug -mrtu -pnone -s2 /dev/ttyAPP1 \ | |||
-a1 -t0x03 -r200 -c 6 | \ | |||
grep Data | sed -e 's/0x00/\\\x/g' -e 's/Data://' -e 's/\s//g'` </syntaxhighlight> | |||
В результате выполнения команды получаем строку, например '''WBMR6'''. Релейный модуль WB-MR6 имеет Modbus-адрес 1. | |||
=== Выбор типа управления внешними входами === | |||
В релейных модулях предусмотрено два режима управления каналами реле: с помощью внешних входов и по протоколу RS-485. | |||
В релейных модулях можно выбрать режим 0, когда ко внешнему входу подключена кнопка (без фиксации), или режим 1, когда для управления используется обычный выключатель (с фиксацией). Режим 3 отключает внешнее управление, но при этом все равно сохраняется возможность управления по RS-485 и чтение состояния внешних входов. По умолчанию включен режим 0. | |||
В режиме внешнего управления реле срабатывает по падению логического уровня: к внешним входам подключены резисторы подтяжки к линии +5V и реле соответствующего канала срабатывает при соединении входа с GND. | |||
Состояние реле каждого канала хранится в памяти контроллера до перезагрузки, по умолчанию при включении питания все реле выключены. После инициализации модуля опрашиваются внешние входы и реле всех каналов переводятся в соответствующее состояние. | |||
Тип внешнего управления можно выбрать для каждого канала отдельно через регистры 9 — (9+x). Для этого в holding-регистре 5 должно быть записано значение 0: | |||
<syntaxhighlight lang="bash"> | |||
modbus_client --debug -mrtu -pnone -s2 /dev/ttyAPP1 -a1 -t0x06 -r5 0 | |||
</syntaxhighlight> | |||
Инициализировать регистр при старте можно и через настройки web-интерфейса, смотрите страницу [[RS-485:Настройка_через_веб-интерфейс]]. |
Версия 14:36, 16 июля 2019
Modbus parameters
Modbus address
Modbus-address of the Wiren Board devices is easy to determine — it is printed on the sticker (the address is in decimal format). The new address of the device is written by the command WRITE_SINGLE_REGISTER to the storage register (holding register) with the address 128 (0x80). For details on how to determine (if the address has been changed) or change the Modbus address of the module, see Define and change the Modbus address of Wiren Board devices.
Modbus commands supported by the device
The Wirenboard relay modules support all major Modbus commands. Read more here: Register reading and writing function codes.
Safe mode
In this mode, when the Modbus communication is terminated, the device disconnects the relay after a specified time.
To enable Safety timer, you must write a value other than 0 to the storage register with the WRITE_SINGLE_REGISTER command at 8. This value is a timeout in seconds. A value of "0" disables safe mode.
Relay operation in case of power failure
In the latest firmware versions (starting with 1.5.3) for WB-MR devices, it is now possible to remember the output status when power is off. The mode is controlled by the Modbus register 6. If the register is set to '0', the state of the outputs will not be saved and all relays will be switched off when power is supplied. If the entry in the register unit, when the power is resumed everything is included before the crash relay is switched on again.
Digital inputs
The input state can be obtained by reading the Discrete Inputs 0—x registers (where x = (number of managed channels - 1)). If the input is connected to GND, the register value is 1, if not connected - it's 0.
Modes of interaction between digital inputs and relay outputs
You can enable direct control of the relay outputs from the digital inputs in the relay module. There are several options for such management:
- Simple:
- Mode 0: managing switch without detent (click "self-released back"). You press the button (close the digital input with GND), it is "pressed back", the relay state is switched to the opposite.
- Mode 1: switch control with locking. The relay is always set according to the position of the switch. If the switch is "on" (closes the digital input with GND), the relay is also closed. If the switch is "off", the relay is open.
- Mode 3: relay output control from digital input is disabled.
- Complex:
- Mapping-matrix (see detailed description below)
The mode can be set separately for each channel. To do this, register 5 must have a value of "0", and the mode for each channel is written to the storage registers starting from address 9 for the first channel, etc.
There is an outdated method - setting the mode for all channels at the same time. To do this, write the appropriate number in the storage register with address 5.
Mapping-matrix
Starting from firmware v.1.9.0, mode 2 is also provided for individual channels-disable all outputs, and operating modes (4 and 5) in accordance with the mapping matrix (see below).In this and later versions of firmware versions modules have flexible settings of the interaction of inputs and outputs of relay modules using a special mapping matrix: a table in which for each input is encoded change of any relay output state when the state of this input changes. A detailed description can be found in I/O Mapping Matrix.
Relay module register card
- x — number of relay outputs;
- y is the number of digital inputs.
(for modules WB-MRM2 see registers map at the description page of this module)
Register / address | Type | Read-write | Default | Format | Appointment | Note |
---|---|---|---|---|---|---|
0 .. (x-1) | coil | RW | - | 1 or 0 | relay status with number 1 .. x | |
0 .. (y-1) | discrete | R | - | 1 or 0 | entry status with number 1 .. y | |
5 | holding | RW | 0 |
|
mode of interaction of digital inputs with relay outputs. The input status registers and the pressure counter continue to operate in all modes. | The register was used in the old configuration mechanism. It is recommended to leave it set to 0 and the inputs are configured via the individual registers 9 .. (9+x-1) |
6 | holding | RW |
|
relay operation mode in case of power failure | (only in firmware 1.5.3 and later) | |
8 | holding | RW | 0 | seconds | safe mode timeout | |
9 .. (9+x-1) | holding | RW | 0 |
|
single digital input interaction mode with corresponding relay output;
"0" should be written in register 5 |
|
|
Начиная с прошивки 1.9.0 | |||||
1 | Начиная с прошивки 1.12.0 | |||||
16 | holding | RW |
|
режим работы цифрового входа 0 для отключения всех реле | ||
2 |
|
режим работы цифрового входа 0; в регистре 5 должен быть записан "0" | Начиная с прошивки 1.9.0 | |||
32 .. (32+y-1) | input | R | 0 | 16-bit unsigned int | счетчик срабатываний входа 1 .. y | |
104-105 | input | R | 32-bit unsigned int | Время работы устройства (uptime counter) в секундах | ||
120 (0x78) | holding | RW | 0 | отличное от 0 | запись в регистр вызывает перезагрузку модуля без сохранения состояния | |
121 (0x79) | holding | R | - | мВ | текущее напряжение питания модуля | |
128 (0x80) | holding | RW | 1 | 1 — 247 | Modbus-адрес устройства | |
129 (0x81) | holding | RW | 0 | 0 или 1 | Переход в режим загрузчика | 1.10.0 |
200-205 | holding | R | {'X','X','X','X','X','X'} | сигнатура устройства (см. таблицу ниже) | ||
220-241 | holding | R | __date__ __time__ | дата сборки прошивки | ||
250-266 | input | R | строка, null-terminated | версия прошивки | ||
270-271 | input | R | 32-bit unsigned int | уникальный идентификатор (S/N) | ||
384-447 | holding | RW | 0 | регистры mapping-матрицы | Начиная с версии прошивки 1.9.0 |
В прошивках версии 1.6.0 и позднее поддерживаются дополнительные регистры настройки параметров обмена данными по RS-485:
Регистр / адрес | Тип | Чтение/запись | Значение по умолчанию | Формат | Назначение |
---|---|---|---|---|---|
110 | holding | RW | 96 | baud rate / 100 | скорость порта RS-485, делённая на 100. Допустимые скорости: 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 (Настройка параметров обмена данными по RS-485 для modbus-устройств Wiren Board) |
111 | holding | RW | 0 | настройка бита чётности порта RS-485. Допустимые значения: 0 - нет бита чётности (none), 1 - нечётный (odd), 2 - чётный (even) | |
112 | holding | RW | 2 | количество стоп-битов порта RS-485. Допустимые значения: 1, 2 |
По адресу 200 лежит сигнатура релейного модуля длиной 6 байт. Сигнатура уникальна для каждой модели устройств Wiren Board и позволяет идентифицировать модель по Modbus:
Модуль | Сигнатура |
---|---|
WB-MRPS6 | MRPS6 |
WB-MR6C | WBMR6 |
WB-MR3xV | WBMR3 |
WB-MR6xV | WBMR6 |
WB-MR14 | WBMR14 |
WB-MR11 | WBMR11 |
WB-MRM2 | WBMR2
WBMR2m |
Для получения сигнатуры нужно выполнить команду READ_HOLDING_REGISTERS по адресу 200 (длина 6 регистров). Запись в эту область памяти не поддерживается, при попытке записи в недопустимое место возвращается ошибка 3. Пустые места в тексте сигнатуры забиваются значением 0x00. Начиная с регистра 220 записана дата сборки прошивки, в формате "числоx00времяx00" в виде строки (пример: 'Jan 27 2017 17:01:13'). Длина записи — 21 регистр.
Значение состояния каждого реле хранится в регистрах флагов (coil). У 1-го реле адрес регистра 0, у 2-го — 1 и т.д.
Управление модулем из командной строки
Программное обеспечение контроллера Wiren Board включает в себя утилиту modbus_client для работы с устройствами, подключенными к выходам RS-485, по протоколу Modbus, подробное описание команды находится на странице Modbus-client. Доступ к командной строке описан в статье SSH.
Пример чтения регистров
Проверим, верно ли, что мы подключились именно к модулю нужного типа. (Сервис wb-mqtt-serial должен быть предварительно остановлен). По адресу 200 хранится уникальная сигнатура длиной в 6 регистров. Прочтем 6 регистров, начиная с адреса 200, и преобразуем полученный шестнадцатеричный ответ в символьную строку:
echo -e `modbus_client --debug -mrtu -pnone -s2 /dev/ttyAPP1 \
-a1 -t0x03 -r200 -c 6 | \
grep Data | sed -e 's/0x00/\\\x/g' -e 's/Data://' -e 's/\s//g'`
В результате выполнения команды получаем строку, например WBMR6. Релейный модуль WB-MR6 имеет Modbus-адрес 1.
Выбор типа управления внешними входами
В релейных модулях предусмотрено два режима управления каналами реле: с помощью внешних входов и по протоколу RS-485. В релейных модулях можно выбрать режим 0, когда ко внешнему входу подключена кнопка (без фиксации), или режим 1, когда для управления используется обычный выключатель (с фиксацией). Режим 3 отключает внешнее управление, но при этом все равно сохраняется возможность управления по RS-485 и чтение состояния внешних входов. По умолчанию включен режим 0.
В режиме внешнего управления реле срабатывает по падению логического уровня: к внешним входам подключены резисторы подтяжки к линии +5V и реле соответствующего канала срабатывает при соединении входа с GND. Состояние реле каждого канала хранится в памяти контроллера до перезагрузки, по умолчанию при включении питания все реле выключены. После инициализации модуля опрашиваются внешние входы и реле всех каналов переводятся в соответствующее состояние.
Тип внешнего управления можно выбрать для каждого канала отдельно через регистры 9 — (9+x). Для этого в holding-регистре 5 должно быть записано значение 0:
modbus_client --debug -mrtu -pnone -s2 /dev/ttyAPP1 -a1 -t0x06 -r5 0
Инициализировать регистр при старте можно и через настройки web-интерфейса, смотрите страницу RS-485:Настройка_через_веб-интерфейс.