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

Материал из Wiren Board
(Новая страница: «| digital input operating mode 0 to disable all relays | |- | 2»)
(Новая страница: «|style="text-align:left;" | * '''2''': disable all relays when pressed * '''4''': to operate in accordance with the mapping-matrix * ''…»)
Строка 121: Строка 121:


|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
|-
|-



Версия 14:45, 16 июля 2019

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

Modbus parameters

Modbus address

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 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
  • 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 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
single digital input interaction mode with corresponding relay output;

"0" should be written 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
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:Настройка_через_веб-интерфейс.