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

Навигация

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

Нет описания правки
(Новая страница: «| 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_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   
|
|
|-
|-
Строка 97: Строка 89:


| rowspan="2" style="text-align:left;" |  
| rowspan="2" 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|I/O mapping- matrix]]
* '''5''': управлять в соответствии с [[I/O_Mapping_Matrix|mapping-матрицей]], через 20 минут повторно имитировать состояние ввода
* '''5''': to operate in accordance with the [[I/O_Mapping_Matrix/en|I/O mapping-matrix]], after 20 minutes to re-simulate the input state
|Начиная с прошивки 1.9.0
|Since firmware v.1.9.0
|-
|-
|1
|1
|Начиная с прошивки 1.12.0
|Since firmware v.1.12.0
|-
|-


Строка 111: Строка 103:
|   
|   
|style="text-align:left;"|  
|style="text-align:left;"|  
* '''0''': кнопки без фиксации
* '''0''': non-locking button
* '''1''': выключатель с фиксацией
* '''1''': switch with lock
* '''3''': отключить взаимодействие
* '''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 || запись в регистр вызывает перезагрузку модуля без сохранения состояния ||
| 32 .. (32+'''y'''-1) || input || R|| 0 || 16-bit unsigned int || input counter 1 .. '''y''' ||  
|-
| 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
|-
|-
| 384-447 || holding || RW || 0 ||  ||  [[I/O_Mapping_Matrix|Mapping Matrix]] registers || Since firmware 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-го &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.