Modbus RTU/TCP Slave/en: различия между версиями

Материал из Wiren Board
(Новая страница: «==== MQTT connection ==== Here you can configure the parameters to connect to the MQTT message broker. By default, the gateway uses the controller's MQTT broker.…»)
м (FuzzyBot переименовал страницу Шлюз Modbus TCP/en в Modbus RTU/TCP Slave/en без оставления перенаправления: Часть переводимой страницы Шлюз Modbus TCP.)
 
(не показано 20 промежуточных версий 1 участника)
Строка 30: Строка 30:
Here you can configure the parameters to connect to the MQTT message broker. By default, the gateway uses the controller's MQTT broker. It is possible to configure authentication.
Here you can configure the parameters to connect to the MQTT message broker. By default, the gateway uses the controller's MQTT broker. It is possible to configure authentication.


Обязательные параметры:
Required parameters:
* '''Address''' - адрес брокера сообщений. По умолчанию - localhost - подключение к брокеру контроллера.
* '''Port''' - номер порта, по которому доступен брокер. По умолчанию - 1883.


Дополнительные параметры:
*'''Address''' - the address of the message broker. By default - localhost - connection to the controller broker.
* '''Keep-alive interval'''
*'''Port''' - the port number on which the broker is available. By default it is 1883.
* '''Enable username+password authentification''' - установите этот флаг в случае, если брокер требует аутентификации с помощью логина и пароля.
 
* '''Login''' - имя пользователя для подключения к брокеру. Обязательный параметр, если установлен флаг '''Enable username+password authentification'''.
Advanced settings:
* '''Password''' - пароль для подключения к брокеру. Обязательный параметр, если установлен флаг '''Enable username+password authentification'''.
 
*'''Keep-alive interval'''
*'''Enable username+password authentication''' - set this flag if the broker requires login and password authentication.
*'''Login''' - user name to connect to the broker. Required if the Enable username+password authentication flag is set.
*'''Password''' - password to connect to the broker. Required if the '''Enable username+password authentication''' flag is set.


==== Register bindings ====
==== Register bindings ====
В этом разделе настраиваются соответствия топиков и регистров.  
In this section, you can configure topic and register matches.
 
This section contains a list of all found channels in the MQTT message queue, distributed by type. Channels are identified by the name of a topic: made a list of all the topics that match the pattern /devices/+/controls/+, while in the list they are shown as +/+. For example, if a message with the /devices/alarms/controls/alarm_test  topic is found in the message broker, the channel will be recorded as alarms/alarm_test in this list.
 
If new channels appear in the message broker (for example, when a new device is connected), they will be added to the list when the service is restarted (this happens when the configuration file is saved or when the controller is restarted).


Раздел содержит список всех найденных каналов в очереди сообщений MQTT, распределённых по типу. Каналы определяются по имени топика: в список вносятся все топики, соответствующие шаблону /devices/+/controls/+, при этом в списке они отображаются как +/+. Например, если в брокере сообщений обнаружено сообщение с топиком /devices/alarms/controls/alarm_test, то в этом списке канал будет записан как alarms/alarm_test.
The channels are divided into 4 groups - register types in Modbus:


Если в брокере сообщений появились новые каналы (например, при подключении нового устройства), они будут добавлены в список при перезапуске службы (это происходит при сохранении конфигурационного файла или при перезапуске контроллера).
*'''Discrete inputs'''- binary values (1/0) that are read-only (for example, GPIO input States);
*'''Coils''' - registers flags - binary values available for reading and writing (for example, switches state relay);
*'''Input registers''' - read-only numeric values (e.g. value from temperature sensor);
*'''Holding registers''' - storage registers - numeric values available for reading and writing (for example, brightness).


Каналы распределены по 4 группам - типам регистров в Modbus:
The distribution takes place automatically on the basis of the description of the channel (in topics /devices/+/controls/+/meta/+).
* '''Discrete inputs''' - дискретные входы - двоичные значения (1/0), доступные только на чтение (например, состояния входов GPIO);
* '''Coils''' - регистры флагов - двоичные значения, доступные на чтение и на запись (например, переключатели состояний реле);
* '''Input registers''' - регистры ввода - численные значения, доступные только на чтение (например, значение с датчика температуры);
* '''Holding registers''' - регистры хранения - численные значения, доступные на чтение и на запись (например, яркость освещения).


Распределение происходит автоматически на основании описания канала (в топиках /devices/+/controls/+/meta/+).
The following options are available for discrete and numeric registers:


Для дискретных и числовых регистров доступны следующие параметры:
*'''Enabled''' - flag that enables binding of the channel to the register. By default, all channels are disabled.
*'''MQTT channel''' - channel name in the format of +/+ (as a match to /devices/+/controls/+)
*'''Meta-type''' - the channel type obtained from the MQTT queue. The parameter is entered only "for the user", does not affect the operation of the service.
*'''Unit ID''' and '''Start address''' - Modbus TCP address fields. Determined by hashing on behalf of the channel; thus, the same channels on different controllers are likely to have the same address fields. Note: Unit ID 1 and 2 are reserved for the user - no channels will be automatically assigned to these addresses.


* '''Enabled''' - флаг, включающий привязку канала к регистру. По умолчанию, все каналы отключены.
'''Important:''' Because the controller is a gateway, it assigns different Unit IDs to different devices connected to it. Some software is designed to work with one Unit ID (for example 1) on one IP address. In some programs, the start address is considered to start with 1 instead of 0. In this case, you should add 1 to the starting address from the gateway configuration when specifying it in your software.
* '''MQTT channel''' - имя канала в формате +/+ (как соответствие /devices/+/controls/+)
* '''Meta-type''' - тип канала, полученный из очереди MQTT. Параметр внесён только "для пользователя", не влияет на работу службы.
* '''Unit ID''' и '''Start address''' - адресные поля Modbus TCP. Определяются хешированием от имени канала; таким образом, одинаковые каналы на разных контроллерах с большой вероятностью будут иметь одинаковые адресные поля. ''Замечание:'' Unit ID 1 и 2 зарезервированы за пользователем - никакие каналы не будут автоматически назначены на эти адреса.


'''Важно:''' Поскольку контроллер является шлюзом, он назначает разным устройствам, подключенным к нему, свои разные Unit ID. Некоторое программное обеспечение рассчитано на работу с одним Unit ID (например 1) на одном IP-адресе. В некоторых программах стартовый адрес считается начинающимся с 1, а не с 0. В таком случае к стартовому адресу из конфигурации шлюза надо добавлять 1 при задании его в вашем ПО.
For numeric registers, in addition to the information above, the following parameters are also available:


Для числовых регистров, помимо вышеописанных, доступны также параметры:
* '''Register format''' - type of stored data:
** '''Signed integer''' ;
** '''Unsigned integer''';
** '''BCD''' is a binary decimal unsigned integer. (For example, a decimal value of 123 would be encoded as 0x123 == 291);
** '''IEEE 754 float''' -floating point number;
** '''Varchar''' - fixed size text field (1 character per case).


* '''Register format''' - тип хранимых данных:
*''' Size''' - the size of the data in bytes. Keep in mind that for all types except text, two bytes are stored in one register.
** '''Signed integer''' - знаковое целое;
**for integer types - 2, 4 and 8 bytes (respectively, in registers it will be 1, 2 and 4 registers);
** '''Unsigned integer''' - беззнаковое целое;
**for floating-point numbers that's 4 and 8 bytes (2 and 4 registers);
** '''BCD''' - двоично-десятичное беззнаковое целое. (Например, десятичное значение 123 будет кодироваться как 0x123 == 291);
**for text fields - any non-negative value.
** '''IEEE 754 float''' - число с плавающей точкой;
** '''Varchar''' - текстовое поле фиксированного размера (1 символ на регистр).


* '''Size''' - размер данных в байтах. Нужно учитывать, что для всех типов, кроме текстового, в один регистр укладывается два байта.
*''' Maximum value''' of the field. Required for channels of type range. All values greater than the maximum will be replaced by the maximum.
** для целочисленных типов - 2, 4 и 8 байт (соответственно, в регистрах это будет 1, 2 и 4 регистра);
** для чисел с плавающей точкой - 4 и 8 байт (2 и 4 регистра);
** для текстовых полей - любое неотрицательное значение.


* '''Maximum value''' - максимальное значение поля. Требуется для каналов типа range. Все значения больше максимума будут заменены на максимальное.
*''' Value scale''' - multiplier of the value. For example, if the multiplier is 2 and the channel has a value of 10, the register value will be 20. Conversely, if a value of 30 has been written to the register, a message with a value of 15 will go to the broker.


* '''Value scale''' - множитель значения. Например, если множитель равен 2 и в канале появилось значение 10, значение регистра будет 20. И наоборот, если в регистр было записано значение 30, в брокер уйдёт сообщение со значением 15.
*'''Byte swap''' - changes the byte order in Modbus registers. By default, values are written to registers in the big-endian format. If this flag is set, the register will be interpreted as little-endian. Important: the flag only applies to individual registers; for compound values (larger than 2 bytes), only the order of each two-byte word changes. For example, the value 0x12345678 will be written as 0x34127856,


* '''Byte swap''' - поменять порядок байт в регистрах Modbus. По умолчанию, значения записываются в регистры в формате big-endian. Если установить этот флаг, регистр будет интерпретироваться как little-endian. ''Важно:'' флаг действует только на отдельные регистры; в случае составных значений (размером больше 2 байт), меняется порядок только в каждом двухбайтном слове. Например, значение 0x12345678 будет записываться как 0x34127856,
*'''Word swap''' - change word order for compound values. For example, the value 0x12345678 will be written as 0x56781234.


* '''Word swap''' - поменять порядок слов для составных значений. Например, значение 0x12345678 будет записываться как 0x56781234.
So, you need to set both last flags to write the value in little-endian format.


Таким образом, чтобы записать значение в формате little-endian, нужно установить оба последних флага.
General settings:


Общие параметры:
*'''Remap addresses after edit''' - update the addresses of the devices in the case was the imposition of addresses. Useful if you want to resize the data to a larger size. When this flag is set, after saving the configuration file, it will be analyzed for address overlays; if they are found, the service will try to remove them, after which the flag will be removed. (In order to get the updated configuration file, you need to reload the page after saving).''' Attention!''' This flag can be used only on the configured system, as the addresses of any channels, including those already configured, can be changed.
* '''Remap addresses after edit''' - обновить адреса устройств в случае, если произошло наложение адресов. Полезно, если требуется изменить размер данных в сторону увеличения. При установке этого флага после сохранения конфигурационного файла он будет проанализирован на наложения адресов; если таковые будут обнаружены, сервис попытается их устранить, после чего флаг будет снят. (Для того, чтобы получить обновлённый конфигурационный файл, после сохранения требуется перезагрузить страницу). '''Внимание!''' Использовать этот флаг можно только на настраиваемой системе, так как могут измениться адреса любых каналов, в том числе и уже настроенных.

Текущая версия на 19:11, 25 января 2021

Wiren Board allows to display messages from specific topics in the MQTT message queue in Modbus TCP registers. This can be useful for setting up simple interaction between the Wiren Board and SCADA systems with Modbus TCP support.


Installation and configuration on the controller

Installation

First you need to install the wb-mqtt-mbgate package. In the device console, enter

root@wirenboard:~# apt-get update && apt-get install wb-mqtt-mbgate

Settings

Gateway configuration page

After installation, you need to specify the topics that will be displayed on the Modbus TCP registers, specify their addresses and specify the format of the registers. To do this, go to the Configs section in the web interface and open the /etc/wb-mqtt-mbgate.conf configuration file.

Modbus binding

Here you can configure the port and address to which the Modbus TCP server will be available.

Required parameters:

  • Bind address - the address to which the Modbus TCP server will be available. The default value is * , which means that you can connect to any address the controller is available (for example, an IP address or a domain name).
  • Server TCP port - the port number on which the Modbus TCP server will be available. The default value is 502, the standard port for Modbus TCP.

MQTT connection

Here you can configure the parameters to connect to the MQTT message broker. By default, the gateway uses the controller's MQTT broker. It is possible to configure authentication.

Required parameters:

  • Address - the address of the message broker. By default - localhost - connection to the controller broker.
  • Port - the port number on which the broker is available. By default it is 1883.

Advanced settings:

  • Keep-alive interval
  • Enable username+password authentication - set this flag if the broker requires login and password authentication.
  • Login - user name to connect to the broker. Required if the Enable username+password authentication flag is set.
  • Password - password to connect to the broker. Required if the Enable username+password authentication flag is set.

Register bindings

In this section, you can configure topic and register matches.

This section contains a list of all found channels in the MQTT message queue, distributed by type. Channels are identified by the name of a topic: made a list of all the topics that match the pattern /devices/+/controls/+, while in the list they are shown as +/+. For example, if a message with the /devices/alarms/controls/alarm_test topic is found in the message broker, the channel will be recorded as alarms/alarm_test in this list.

If new channels appear in the message broker (for example, when a new device is connected), they will be added to the list when the service is restarted (this happens when the configuration file is saved or when the controller is restarted).

The channels are divided into 4 groups - register types in Modbus:

  • Discrete inputs- binary values (1/0) that are read-only (for example, GPIO input States);
  • Coils - registers flags - binary values available for reading and writing (for example, switches state relay);
  • Input registers - read-only numeric values (e.g. value from temperature sensor);
  • Holding registers - storage registers - numeric values available for reading and writing (for example, brightness).

The distribution takes place automatically on the basis of the description of the channel (in topics /devices/+/controls/+/meta/+).

The following options are available for discrete and numeric registers:

*Enabled - flag that enables binding of the channel to the register. By default, all channels are disabled.
  • MQTT channel - channel name in the format of +/+ (as a match to /devices/+/controls/+)
  • Meta-type - the channel type obtained from the MQTT queue. The parameter is entered only "for the user", does not affect the operation of the service.
  • Unit ID and Start address - Modbus TCP address fields. Determined by hashing on behalf of the channel; thus, the same channels on different controllers are likely to have the same address fields. Note: Unit ID 1 and 2 are reserved for the user - no channels will be automatically assigned to these addresses.

Important: Because the controller is a gateway, it assigns different Unit IDs to different devices connected to it. Some software is designed to work with one Unit ID (for example 1) on one IP address. In some programs, the start address is considered to start with 1 instead of 0. In this case, you should add 1 to the starting address from the gateway configuration when specifying it in your software.

For numeric registers, in addition to the information above, the following parameters are also available:

  • Register format - type of stored data:
    • Signed integer ;
    • Unsigned integer;
    • BCD is a binary decimal unsigned integer. (For example, a decimal value of 123 would be encoded as 0x123 == 291);
    • IEEE 754 float -floating point number;
    • Varchar - fixed size text field (1 character per case).
  • Size - the size of the data in bytes. Keep in mind that for all types except text, two bytes are stored in one register.
    • for integer types - 2, 4 and 8 bytes (respectively, in registers it will be 1, 2 and 4 registers);
    • for floating-point numbers that's 4 and 8 bytes (2 and 4 registers);
    • for text fields - any non-negative value.
  • Maximum value of the field. Required for channels of type range. All values greater than the maximum will be replaced by the maximum.
  • Value scale - multiplier of the value. For example, if the multiplier is 2 and the channel has a value of 10, the register value will be 20. Conversely, if a value of 30 has been written to the register, a message with a value of 15 will go to the broker.
  • Byte swap - changes the byte order in Modbus registers. By default, values are written to registers in the big-endian format. If this flag is set, the register will be interpreted as little-endian. Important: the flag only applies to individual registers; for compound values (larger than 2 bytes), only the order of each two-byte word changes. For example, the value 0x12345678 will be written as 0x34127856,
  • Word swap - change word order for compound values. For example, the value 0x12345678 will be written as 0x56781234.

So, you need to set both last flags to write the value in little-endian format.

General settings:

  • Remap addresses after edit - update the addresses of the devices in the case was the imposition of addresses. Useful if you want to resize the data to a larger size. When this flag is set, after saving the configuration file, it will be analyzed for address overlays; if they are found, the service will try to remove them, after which the flag will be removed. (In order to get the updated configuration file, you need to reload the page after saving). Attention! This flag can be used only on the configured system, as the addresses of any channels, including those already configured, can be changed.