Relay Module Modbus Management/en: различия между версиями

Материал из Wiren Board
(Новая страница: «| rowspan="2" | 16 | rowspan="2" | holding | rowspan="2" | RW | |style="text-align:left;"| * '''0''': non-locking button * '''1''': switch with lock * '…»)
 
(не показаны 34 промежуточные версии 3 участников)
Строка 2: Строка 2:
<!-- {{DISPLAYTITLE:Управление модулями реле  Wiren Board по протоколу Modbus}} -->
<!-- {{DISPLAYTITLE:Управление модулями реле  Wiren Board по протоколу Modbus}} -->


== Modbus parameters ==
{{:Modbus_control_common}}


=== Modbus address ===
== Device Setup ==
[[Файл: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 ===
Строка 34: Строка 28:
** '''Mapping-matrix''' (see detailed description below)
** '''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.
The mode set separately for each channel. To select mode, write mode number to corresponding holding register, starting with register 9 for the first channel etc. You should keep default value in register 5.


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.
There could be no registers 9 etc. in outdated firmware. You can only set mode for all their channels at once. To do so, write corresponding number to holding register 5.


==== Mapping-matrix ====
==== Mapping-matrix ====
Строка 42: Строка 36:
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 =
 
In table:
* '''x''' — number of relay outputs;  
* '''x''' — number of relay outputs;  
* '''y''' is the number of digital inputs.
* '''y''' number of digital inputs.
(for modules WB-MRM2 see registers map at the description page of [[WB-MRM2/en|this module]])
For outdated WB-MRM2 devices (not to be confused with modern WB-MRM2-mini) find register card on separate page [[WB-MRM2]].


{| border="1" class="wikitable" style="text-align:center; width:1000px;"
{| border="1" class="wikitable" style="text-align:center; width:1000px;"
Строка 67: Строка 61:
| 0  
| 0  
| style="text-align:left;" |
| style="text-align:left;" |
* '''0''': buttons without locking
default value should be kept
* '''1''': switch with lock
|| not used in modern firmware.<br>In outdated versions of firmware was used to set mode of interaction of digital inputs with relay outputs for all inputs at once.
* '''3''': disable interaction
|| not used in modern firmware.<br>In outdated versions of firmware was used to set mode of interaction of digital inputs with relay outputs for all inputs at once. Configuration values were the same as now used in registers 9 .. (9+'''x'''-1), but applied to all inputs at once.
|| 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
Строка 88: Строка 81:
| style="text-align:left;" |  
| style="text-align:left;" |  
* '''0''': non-locking buttons
* '''0''': non-locking buttons
* '''1''': switch with separate actuator
* '''1''': switch with lock
* '''3''': disable interaction  
* '''3''': disable interaction  
| rowspan="3" | single digital input interaction mode with corresponding relay output;
| rowspan="3" | mode of interaction between digital input and corresponding relay output.<br>There should be default value in register 5   
"0" should be written in register 5   
|
|
|-
|-
Строка 115: Строка 107:
* '''3''': disable interaction  
* '''3''': disable interaction  


| режим работы цифрового входа 0 для отключения всех реле
| digital input operating mode 0 to disable all relays
|
|
|-
|-
Строка 121: Строка 113:


|style="text-align:left;" |  
|style="text-align:left;" |  
* '''2''': отключать все реле при нажатии
* '''2''': disable all relays when pressed
* '''4''': управлять в соответствии с [[I/O_Mapping_Matrix|mapping-матрицей]]
* '''4''': to operate in accordance with the [[I/O_Mapping_Matrix/en|mapping-matrix]]
* '''5''': управлять в соответствии с [[I/O_Mapping_Matrix|mapping-матрицей]], через 20 минут повторно имитировать состояние ввода
* '''5''': to operate in accordance with the [[I/O_Mapping_Matrix/en|mapping-matrix]], after 20 minutes to re-simulate the input state
| режим работы цифрового входа 0; в регистре 5 должен быть записан "0"
| digital input mode 0; register 5 must be set to "0"
|Начиная с прошивки 1.9.0
|Since firmware 1.9.0
|-
|-






 
| 20 .. (20+'''x'''-1) || holdreg || RW || 50 || 0 - 100 || debouncing time in ms || Since firmware 1.13.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:
| 32 .. (32+'''y'''-1) || input || R|| 0 || 16-bit unsigned int || input counter 1 .. '''y''' ||  
 
{| class="wikitable"
! style="font-weight: bold;" | Модуль
! style="font-weight: bold;" | Сигнатура
|-
|-
 
| 384-447 || holding || RW || 0 || || [[I/O_Mapping_Matrix|Mapping Matrix]] registers || Since firmware 1.9.0
|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-го &mdash; 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:
{{:Common_Modbus_Registers}}
<syntaxhighlight lang="bash">
modbus_client --debug -mrtu -pnone -s2 /dev/ttyAPP1 -a1 -t0x06 -r5 0
</syntaxhighlight>


Инициализировать регистр при старте можно и через настройки web-интерфейса, смотрите страницу [[RS-485:Настройка_через_веб-интерфейс]].
Registers for setting data exchange parameters for RS-485 are supported since firmware 1.6.0.

Текущая версия на 23:09, 18 апреля 2020

Другие языки:

Modbus control common

Device Setup

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 set separately for each channel. To select mode, write mode number to corresponding holding register, starting with register 9 for the first channel etc. You should keep default value in register 5.

There could be no registers 9 etc. in outdated firmware. You can only set mode for all their channels at once. To do so, write corresponding number to holding register 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

In table:

  • x — number of relay outputs;
  • y — number of digital inputs.

For outdated WB-MRM2 devices (not to be confused with modern WB-MRM2-mini) find register card on separate page WB-MRM2.

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

default value should be kept

not used in modern firmware.
In outdated versions of firmware was used to set mode of interaction of digital inputs with relay outputs for all inputs at once.
not used in modern firmware.
In outdated versions of firmware was used to set mode of interaction of digital inputs with relay outputs for all inputs at once. Configuration values were the same as now used in registers 9 .. (9+x-1), but applied to all inputs at once.
6 holding RW
  • 0: do not restore relay state after power is restored
  • 1: restore relay state after power is restored
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
  • 0: non-locking buttons
  • 1: switch with lock
  • 3: disable interaction
mode of interaction between digital input and corresponding relay output.
There should be default value in register 5
  • 2: disable all relays when pressed
  • 4: to operate in accordance with the I/O mapping- matrix
  • 5: to operate in accordance with the I/O mapping-matrix, after 20 minutes to re-simulate the input state
Since firmware v.1.9.0
1 Since firmware v.1.12.0
16 holding RW
  • 0: non-locking button
  • 1: switch with lock
  • 3: disable interaction
digital input operating mode 0 to disable all relays
2
  • 2: disable all relays when pressed
  • 4: to operate in accordance with the mapping-matrix
  • 5: to operate in accordance with the mapping-matrix, after 20 minutes to re-simulate the input state
digital input mode 0; register 5 must be set to "0" Since firmware 1.9.0
20 .. (20+x-1) holdreg RW 50 0 - 100 debouncing time in ms Since firmware 1.13.0
32 .. (32+y-1) input R 0 16-bit unsigned int input counter 1 .. y
384-447 holding RW 0 Mapping Matrix registers Since firmware 1.9.0


Внимание: Отображаемое название «Таблица общих регистров» переопределяет ранее заданное отображаемое название «Relay Modules Modbus Management».

Параметры подключения, версия прошивки и другие служебные регистры
Адрес Параметры регистра Описание Значения Примечание
Dec Hex Тип Доступ Формат
Параметры подключения
110 0x006E Holding RW u16 Скорость порта RS-485.
Настройка параметров подключения по RS-485
x100, Боды
12 — 1200 бит/с,
24 — 2400 бит/с,
48 — 4800 бит/с,
96 — 9600 бит/с,
192 — 19 200 бит/с,
384 — 38 400 бит/с,
576 — 57 600 бит/с,
1152 — 115 200 бит/с
111 0x006F Holding RW u16 Настройка бита чётности порта RS-485 0 — нет бита чётности (none),
1 — нечётный,
2 — чётный
112 0x0070 Holding RW u16 Количество стоп-битов порта RS-485 1, 2
128 0x0080 Holding RW u16 Modbus-адрес устройства (подробнее)
Модель устройства и версия прошивки
200-205 0x00C8 - 0x00CD Input RO string Модель устройства
206-219 0x00CE - 0x00DB Input RO string Расширение модели устройства. Для чтения модели устройства нужно читать диапазон из 20 регистров (200 - 219) Только с «быстрым Modbus»
220-248 0x00DC - 0x00F8 Input RO string Хэш коммита и название ветки откуда собрана прошивка (2 символа в регистре)
250-265 0x00FA - 0x0109 Input RO string Версия прошивки
266-269 0x010A - 0x010D Input RO u64 Расширение серийного номера
270-271 0x010E - 0x010F Input RO u32 Серийный номер
290-301 0x0122 - 0x012D Holding RO string Сигнатура прошивки
320 0x0140 Input RO u16 Версия прошивки в числовом формате (подробнее) MAJOR Только с «быстрым Modbus»
321 0x0141 MINOR
322 0x0142 PATCH
323 0x0143 s16 SUFFIX
324-325 0x0144 - 0x0145 Input RO u32 Версия прошивки в числовом формате Только с «быстрым Modbus»
326-327 0x0146 - 0x0147 Input RO u32 Версия прошивки в Big Endian формате Только с «быстрым Modbus»
Прочее
104­-105 0x0068 - 0x0069 Input RO u32 Время работы с момента загрузки секунды
120 0x0078 Holding RW u16 Перезагрузка устройства без сохранения состояния любое, отличное от 0 перезагружает устройство
123 0x007B Input RO u16 Напряжение на микроконтроллере мВ
129 0x0081 Holding RW u16 Перевод в режим обновления прошивки на 2 минуты любое, отличное от 0 переводит устройство в режим обновления прошивки
330-336 0x014A - 0x0150 Holding RO string Версия загрузчика
131 0x0083 Holding RW u16 Перевод в режим обновления прошивки на текущих настройках соединения запись 1 переводит устройство в режим обновления прошивки
113 0x0071 Holding RW u16 Время перед отправкой ответа на modbus запрос 0 - 254 мс Только с «быстрым Modbus»
114 0x0072 Holding RW u16 Режим непрерывного чтения регистров с зазором 0 - отключен
1 - включен
2 - включение сохраняется после перезагрузки
Только с «быстрым Modbus»
121 0x0079 Input RO u16 Текущее напряжение питания мВ
125 0x007D Input RO u16 Текущее напряжение питания (без фильтра) мВ
124 0x007C Input RO u16 Внутренняя температура микроконтроллера x0.1, °C

Registers for setting data exchange parameters for RS-485 are supported since firmware 1.6.0.