Skip to content
Stand with Ukraine flag

Modbus

This documentation will help you set up the Modbus connector for the ThingsBoard IoT Gateway. We’ll explain the configuration parameters in simple terms to make it easy for you to understand and follow. The Modbus is a widely used protocol for industrial automation and control systems, allowing devices to communicate with each other over a network, and this connector allows seamless integration with the ThingsBoard platform. Use general configuration to enable this extension.

Also, if you are new to ThingsBoard IoT Gateway, we recommend you to read the Getting Started guide to understand the basic concepts of ThingsBoard IoT Gateway and how it works with Modbus protocol.

The connector can be configured via the user interface form, which helps you set up a connection to the Modbus server, collect data and write data to slaves (devices). Let’s look at all the available settings and explain each one clearly. This will help you understand how everything works.

The Modbus connector can be configured in two modes: Basic and Advanced.

  • Basic mode is designed for users who are new to ThingsBoard IoT Gateway and want to quickly set up the connector with minimal configuration. It provides a simplified interface with essential settings.
  • Advanced mode is intended for experienced users who need more control over the configuration. It offers additional options and flexibility for advanced use cases.

You can switch between these modes using the toggle button at the top of the configuration page:

This configuration section contains general connector settings, such as:

  • Name - connector name used for logs and saving to persistent devices;
  • Logs configuration - settings for local and remote logging:
    • Enable remote logging - enables remote logging for the connector;
    • Logging level - logging level for local and remote logs: NONE, ERROR, CRITICAL, WARNING, INFO, DEBUG, TRACE;
  • Report strategy - strategy for sending data to ThingsBoard:
    • Report period - period for sending data to ThingsBoard in milliseconds;
    • Type - type of the report strategy:
      • On report period - sends data to ThingsBoard after the report period;
      • On value change - sends data to ThingsBoard when the value changes;
      • On value change or report period - sends data to ThingsBoard when the value changes or after the report period;
      • On received - sends data to ThingsBoard after receiving data from the device (default strategy).

Master connections (Gateway as a Master) settings

Section titled “Master connections (Gateway as a Master) settings”

A Modbus Master is used to query data from Modbus servers (slaves). In order to configure servers for data retrieving, you need to specify list of slaves.

A Modbus Slave is a device that responds to requests from a Modbus Master. In this section, you can configure the Modbus slaves that the master will query data from. You can add multiple slaves to the list, and each slave can have its own configuration.

The following parameters are used to configure the slave device, its name and profile, as well as for report strategy:

  • Unit ID - ID of the Modbus slave.
  • Device name - name of the device on the platform.
  • Device profile - device profile name on the platform.
  • Report strategy strategy for sending data to ThingsBoard:
    • Report period - period for sending data to ThingsBoard in milliseconds;
    • Type - type of the report strategy:
      • On report period - sends data to ThingsBoard after the report period;
      • On value change - sends data to ThingsBoard when the value changes;
      • On value change or report period - sends data to ThingsBoard when the value changes or after the report period;
      • On received - sends data to ThingsBoard after receiving data from the device (default strategy).

To add a new configuration for connection to server, navigate to the “Master Connections” tab and click the “plus” icon:

Due to the nature of preferred way of communication between Modbus master there are 3 options how to configure this part: if using TCP, UDP or via Serial port.

The following parameters are used to configure TCP connection for the slave:

  • Host - hostname or IP address of the Modbus server.
  • Port - port of the Modbus server for connection.
  • Method - type of a framer, either Socket or RTU.

You can configure additional settings like: TLS connection, polling time, byte order and word order, and other. The table below describes the parameters for this purpose:

ParameterDefault valueDescription
Connection timeout (s)35Timeout in seconds for connecting to Modbus server
Byte orderLITTLEOrder of bytes to read
Word orderLITTLEThe order of words when reading several registers
RetriestrueRetrying sending data to the master. The values can be either: true or false
Retries on emptytrueRetrying sending data to the master if it is empty
Retries on invalidtrueRetrying sending data to the master if it is failed
Poll period (ms)5000Period in milliseconds to check the attributes and the telemetry on the slave
Connect attempt time (ms)5000A waiting period in milliseconds before connecting to the master
Connect attempt count5The number of connection attempts made through the ThingsBoard gateway
Wait after failed attempts (ms)300000A waiting period in milliseconds before trying to send data to the master
  1. Click on the “Advanced connection settings” subsection to open it;

  2. Make the necessary settings.

Also, you can configure TLS connection (can be used only for TCP/UDP connection type). The table below describes the parameters required to configure TLS connection:

ParameterDescription
Path to client certificate filePath to certificate file in filesystem with gateway
Path to private key filePath to private key file
PasswordServer password
Server hostnameServer hostname (Should match with hostname in certificate)

In the data mapping, you can specify how the Modbus master will interact with the slaves. This includes reading data from the slaves. You can also use this section to configure which data will be sent as device attributes or telemetry. Data mapping contains all the necessary settings for flexible data management.

The configuration in this unit provides settings for processing data on Modbus server. These settings will be interpreted in ThingsBoard platform instance as attributes/time series of the device. The following parameters are used to configure device attributes and time series:

  • Key - key of the attribute or time series on the platform.
  • Type - data type of the Modbus register.
  • Function code - Modbus function code for reading the register.
  • Objects count - number of registers to read.
  • Address - address of the register on the Modbus server.

For adding a new attribute or time series, use the following steps:

  1. Click on “pencil” icon in the “Attributes” or “Time series” section (depends on the selected section);

  2. In the opened window click “Add attribute” or “Add time series” (depends on selected section);

  3. Fill in key, type, function code, objects count and address fields. Click “Apply”.

You can enable a specific report strategy for each time series or attribute. This strategy defines how often data is sent to the ThingsBoard server. The following strategies are available:

  • On report period - sends data to ThingsBoard after the report period;
  • On value change - sends data to ThingsBoard when the value changes;
  • On value change or report period - sends data to ThingsBoard when the value changes or after the report period;
  • On received - sends data to ThingsBoard after receiving data from the device (default strategy).

You can map register values to human-readable strings using the enum mapping feature. This is particularly useful for registers where value denotes a state of the device instead of a “sensor value”. Enum mapping works with all register types. Uplink RPC to Device calls can use enum mapping to get interpreted values. Also, enum mapping works with batch reading as expected.

In order to set up enum mapping for a specific attribute or time series, you need to define the variants parameter in the configuration. This parameter is an object where each key represents a possible register value, and the corresponding value is the human-readable string that describes that register value.

Example of enum mapping configuration:

{
"tag": "status",
"type": "16int",
"address": 1,
"objectsCount": 1,
"functionCode": 3,
"variants": {
"0": "Stopped",
"1": "Booting",
"2": "Running"
}
}

Example of enum mapping configuration for coil register:

{
"tag": "relay",
"type": "bits",
"address": 1,
"objectsCount": 1,
"functionCode": 1,
"bitTargetType": "int",
"variants": {
"0": "Disable",
"1": "Enable"
}
}

Example of enum mapping configuration for RPC to Device call:

{
"method": "getStatus",
"type": "16int",
"address": 1,
"objectsCount": 1,
"functionCode": 3,
"variants": {
"0": "Stopped",
"1": "Booting",
"2": "Running"
}
}

modifier for attribute/time series value can be applied using the following settings:

ParameterDescription
Typemultiplier - the result of reading will be multiplied by the value of this parameter.
divider - the result of reading will be divided by the value of this parameter
ValueThe value that will be used to modify the read value

To optimize the reading process, you can group multiple registers into a single batch read request. This approach reduces the number of requests sent to the Modbus server, which can enhance performance and decrease network traffic. Take attention that the registers in a batch read request must be of the same type and function code.

Two parameters are important for group reading configuration: address and tag. Let’s look at them in more detail:

  • address - is the address of the starting register and the address of the ending register, separated by a - character. For example, 0-10 means that the group read starts with the register at address 0 and ends at the register at address 10, inclusive.
  • tag - is a unique identifier for each register within a group read. It is used to identify a specific register within a given address range. The tag name can be formed using an expression using the following variables:
    • ${address} - register address within group read.
    • ${unitId} - slave ID.
    • ${functionCode} - function code.
    • ${type} - data type of register.
    • ${objectsCount} - number of objects.

Also, divider and multiplier parameters work as expected.

Example of group reading configuration:

{
"tag": "${unitId} - ${type} - ${address}",
"type": "16int",
"functionCode": 3,
"objectsCount": 1,
"address": "0-10"
}

As an example, we will use ThingsBoard Modbus Demo Server, which can be run using Docker and the following command:

Terminal window
docker run -it -p 5021:5021 thingsboard/tb-gw-modbus-server:latest

The server available at 0.0.0.0:5021. The server has the following structure:

Variable NameRegister TypeData TypeAddress
TemperatureHolding16int0
HumidityHolding16int1
PowerHolding16int2
PressureHolding16int3
RelayCoilbits1

We are interested in register 1, which contains the relay state value (off/on). To read the value of this register, we need to add this register as attribute/telemetry in the device configuration. To do this, follow these steps:

  1. Go to “Entities” → “Gateways” in the left sidebar and select your gateway.

  2. Click on the “Connectors configuration” button on the right side menu.

  3. Select the created Modbus connector and click on the “Master Connections” tab. Make sure you have configured and connected device (if you don’t know how to do it, see Getting Started guide or Connection settings and Data mapping sections of this guide). Click on the “Pencil” icon on a device you want to configure attribute updates for.

  4. Scroll down to the “Attributes or Time series” section and click on the “Pencil” icon to edit the attributes and telemetry.

  5. Click on the “Add attribute” or “Add telemetry” button. In our case, we will add relay time series, so fill in the “Key” field with relay, select the “Type” as bits, select “Function code” field as “01 - Read Coils”, select “Bit target type” as “Boolean”, and in the “Address” field enter 1. This is the address of the Modbus register we want to read.

  6. Remember to save your changes by clicking the “Apply” button.

Now we can check if the attribute/telemetry works. Go to “Entities” → “Devices” → select a created device → “Last telemetry” tab and check the value of the relay telemetry. It should be false since the default value of the relay is off.

Full configuration for Modbus connector for the example above will look like this:

{
"master": {
"slaves": [
{
"host": "0.0.0.0",
"port": 5021,
"method": "socket",
"unitId": 1,
"deviceName": "Demo Device",
"deviceType": "default",
"timeout": 35,
"byteOrder": "LITTLE",
"wordOrder": "LITTLE",
"retries": true,
"retryOnEmpty": true,
"retryOnInvalid": true,
"pollPeriod": 1000,
"connectAttemptTimeMs": 500,
"connectAttemptCount": 5,
"waitAfterFailedAttemptsMs": 30000,
"type": "tcp",
"attributes": [],
"timeseries": [
{
"tag": "relay",
"type": "bits",
"address": 1,
"objectsCount": 1,
"functionCode": 1,
"bitTargetType": "bool"
}
],
"attributeUpdates": [],
"rpc": []
}
]
}
}

The Requests mapping section allows you to configure how the ThingsBoard platform instance will interact with the devices. That is, how the platform will request data from the devices, how it will update device attributes, and how it will send RPC commands to the devices.

Modbus connector supports the following requests mapping:

  • Attribute updates - allows update device nodes values from ThingsBoard platform instance.
  • RPC methods - allows sending RPC commands to devices. Using RPC methods, you can get or set values of the Modbus registers. Modbus connector supports different types of RPC methods, such as:
    • Reserved GET/SET methods - these methods are automatically created for each attribute and time series parameter. You can use them to get or set values of the Modbus registers.
    • Configurable RPC methods to device - these methods allow you to configure custom RPC commands in connector configuration that can be sent to the devices.

This subsection contains configuration for attribute updates request from ThingsBoard platform instance.

ThingsBoard allows provisioning device attributes and fetches some of them from the device application. You can treat this as a remote configuration for devices. Your devices are able to request shared attributes from ThingsBoard. See user guide for more details.

The following parameters are used to configure attribute updates:

  • Key - shared attribute name.
  • Type - type of value, which is used to identify the data type of the value that is being received.
  • Function code - function to use for data processing, specifically Modbus functions.
  • Objects count - count of objects to write or read, which specifies how many registers will be processed in the request.
  • Address - object address, which is used to identify the specific object in the Modbus protocol.

In order to add new attribute update, follow these steps:

  1. Navigate to the “Attribute updates” section and click the “pencil” icon;

  2. In the opened window click “Add attribute update”;

  3. Set an attribute key name, type, function code, objects count, and address. Then, click “Apply”.

ThingsBoard allows sending RPC commands to the device that is connected to ThingsBoard directly or via Gateway. Configuration, provided in this section is used for sending RPC requests from ThingsBoard to device. The following parameters are used to configure RPC methods:

  • Method name - RPC method name, which is used to identify the request.
  • Type - data type of value, which is used to identify the data type of the value that is being received.
  • Function code - function to use for data processing, specifically Modbus functions.
  • Objects count - count of objects to write or read, which specifies how many registers will be processed in the request.
  • Address - object address, which is used to identify the specific object in the Modbus protocol.

In order to add a new RPC method, follow these steps:

  1. Navigate to the “RPC requests” section and click the “pencil” icon;

  2. In the opened window click the “Add request”;

  3. Fill in key, type, function code, objects count and address fields. Click “Apply”.

Attribute updates allow you to update register values in the Modbus server. You can add new attribute updates in the “Attribute updates” section of the device configuration page.

As an example, we will use ThingsBoard Modbus Demo Server, which can be run using Docker and the following command:

Terminal window
docker run -it -p 5021:5021 thingsboard/tb-gw-modbus-server:latest

The server available at 0.0.0.0:5021. The server has the following structure:

Variable NameRegister TypeData TypeAddress
TemperatureHolding16int0
HumidityHolding16int1
PowerHolding16int2
PressureHolding16int3
RelayCoilbits1

We are interested in register “1”, we added this register as a telemetry parameter with the key relay. We used telemetry so that later it would be convenient for us to see if the value we changed using the attribute update has changed. You, also, can add this telemetry datapoint to the device configuration or use the reserved get method to check the value of the node.

Let’s add an attribute update to our configuration. For this purpose, follow these steps:

  1. Go to “Entities” → “Gateways” in the left sidebar and select your gateway.

  2. Click on the “Connectors configuration” button on the right side menu.

  3. Select the created Modbus connector and click on the “Master Connections” tab. Make sure you have configured and connected device (if you don’t know how to do it, see Getting Started guide or Connection settings and Data mapping sections of this guide). Click on the “Pencil” icon on a device you want to configure attribute updates for.

  4. Scroll down to the “Attribute updates” section and click on the “Pencil” icon to edit the attribute updates.

  5. Click on the “Add attribute update” button. In our case, we will add relay attribute update, so the “Key” field, enter relay, select the “Type” as bits, “Function code” as “05 - Write Single Coil”, fill in the “Objects count” field with 1, select “Bit target type” as “Boolean” and in the “Address” field enter “1”.

  6. Remember to save your changes by clicking the “Apply” button.

Now we can check if the attribute update works. Go to “Entities” → “Devices” → select a created device → “Attributes” tab → select “Shared attributes” → click on the ”+” icon and add relay attribute with type “Boolean” set it to “True”.

Now, let’s check the value of the relay register. In the selected device, go to the “Last telemetry” tab and check the value of the relay telemetry. It should be true since we set the shared attribute to true.

Try to change the value of the relay shared attribute to false. After a few seconds, you should see that the relay telemetry value has changed to false, which means that the attribute update worked correctly.

Full configuration for Modbus connector for the examples above will look like this:

{
"master": {
"slaves": [
{
"host": "0.0.0.0",
"port": 5021,
"method": "socket",
"unitId": 1,
"deviceName": "Demo Device",
"deviceType": "default",
"timeout": 35,
"byteOrder": "LITTLE",
"wordOrder": "LITTLE",
"retries": true,
"retryOnEmpty": true,
"retryOnInvalid": true,
"pollPeriod": 1000,
"connectAttemptTimeMs": 500,
"connectAttemptCount": 5,
"waitAfterFailedAttemptsMs": 30000,
"type": "tcp",
"attributes": [],
"timeseries": [
{
"tag": "relay",
"type": "bits",
"address": 1,
"objectsCount": 1,
"functionCode": 1,
"bitTargetType": "bool"
}
],
"attributeUpdates": [
{
"tag": "relay",
"type": "bits",
"address": 1,
"objectsCount": 1,
"functionCode": 5,
"bitTargetType": "bool"
}
],
"rpc": []
}
]
}
}

The advanced configuration section provides a detailed overview of all available parameters for the Master section configuration.

Gateway can run as a Modbus master. This configuration section for the Modbus master, which is used to query data from Modbus servers (slaves).

The Slaves list is used to specify the list of Modbus slaves that the master will query data from.

ParameterDefault valueDescription
server.slaves[].unitIdUnit ID of Modbus slave.
server.slaves[].deviceNameDevice name on the platform.
server.slaves[].deviceTypedefault(Optional) Device profile name on the platform.
server.slaves[].pollPeriod (in ms)Period in milliseconds to check the attributes and the telemetry on the slave.
server.slaves[].delayBetweenRequestsMs0(Optional) Delay between reading and writing requests. Useful for devices that implement Modbus RTU over TCP internally consist of a TCP-to-Serial converter.
server.slaves[].timeout (in sec)35(Optional) Timeout in seconds for connecting to Modbus server.
server.slaves[].retriestrue(Optional) Retrying sending data to the master. The values can be either: true or false.
server.slaves[].retryOnEmptytrue(Optional) Retrying sending data to the master if it is empty.
server.slaves[].retryOnInvalidtrue(Optional) Retrying sending data to the master if it is failed.
server.slaves[].connectAttemptTimeMs (in ms)5000(Optional) A waiting period in milliseconds before connecting to the master.
server.slaves[].connectAttemptCount5(Optional) The number of connection attempts made through the ThingsBoard gateway.
server.slaves[].waitAfterFailedAttemptsMs (in ms)300000(Optional) A waiting period in milliseconds before trying to send data to the master.
server.slaves[].byteOrderLITTLEOrder of bytes to read.
server.slaves[].wordOrderLITTLEThe order of words when reading several registers.
server.slaves[].reportStrategy(Optional) Report strategy object using for configuring report strategy for device.

Example of the slave configuration:

"master": {
"slaves": [
{
"timeout": 35,
"byteOrder": "LITTLE",
"wordOrder": "LITTLE",
"retries": true,
"retryOnEmpty": true,
"retryOnInvalid": true,
"pollPeriod": 5000,
"sendDataOnlyOnChange": true,
"connectAttemptTimeMs": 5000,
"connectAttemptCount": 5,
"waitAfterFailedAttemptsMs": 300000,
"deviceName": "Demo Device",
"deviceType": "default",
"unitId": 1,
...
}
]
}

The Modbus connector supports three types of connections to the Modbus slave:

  • TCP - connection to the Modbus slave over TCP/IP protocol.
  • UDP - connection to the Modbus slave over UDP protocol.
  • Serial - connection to the Modbus slave over serial port (RS-232, RS-485, etc.).
ParameterDefault valueDescription
master.slaves[].typeType of connection to Modbus device.
master.slaves[].hostlocalhostHostname or ip address of Modbus server.
master.slaves[].port5021Port of Modbus server for connection.
master.slaves[].methodsocketType of a framer Socket or RTU, if needed.

Example of the TCP/UDP slave configuration:

"master": {
"slaves": [
{
"host": "127.0.0.1",
"port": 5021,
"method": "socket",
...
}
]
}
ParameterDefault valueDescription
master.slaves[].typeserialType of connection to Modbus device.
master.slaves[].portPort of Modbus slave for connection.
master.slaves[].methodsocketType of a framer Socket or RTU, if needed.
master.slaves[].baudrate19200Baud rate for serial connection.
master.slaves[].stopbits1(Optional) The number of bits sent after each character in a message to indicate the end of the byte.
master.slaves[].parityNone(Optional) The type of checksum to use to verify data integrity. This can be on of the following: (E)ven, (O)dd, (N)one.
master.slaves[].bytesize8(Optional) The number of bits in a byte of serial data. This can be one of 5, 6, 7, or 8.
master.slaves[].stricttrue(Optional) Use Inter char timeout for baud rates less than or equal to 19200
master.slaves[].repackfalse(Optional) Repack data to remove padding bytes.
master.slaves[].handleLocalEchofalse(Optional) Handle local echo for serial connections. This is useful for devices that echo back the data sent to them.

Example of the serial slave configuration:

"master": {
"slaves": [
{
"method": "ascii",
"baudrate": 4800,
"stopbits": 1,
"bytesize": 5,
"parity": "N",
"strict": true,
...
}
]
}
ParameterDescription
server.slaves[].attributes[]List of attributes that will be sent to the ThingsBoard platform instance.
server.slaves[].attributes[].tagKey name of the attribute in ThingsBoard. It can be specified as a static value.
server.slaves[].attributes[].typeData type of value.
server.slaves[].attributes[].functionCodeFunction code to use for reading the attribute value from the Modbus slave.
server.slaves[].attributes[].objectsCountNumber of objects to read from the Modbus slave.
server.slaves[].attributes[].addressAddress of the object in the Modbus slave. Can be configured for batch reading.
server.slaves[].attributes[].divider(Optional) Divider for the value. If not specified, the value will be sent as is.
server.slaves[].attributes[].multiplier(Optional) Multiplier for the value. If not specified, the value will be sent as is.
server.slaves[].attributes[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.
mapping[].attributes[].reportStrategy(Optional) Report strategy for the attributes data. If not specified, the device report strategy will be used.
server.slaves[].timeseries[]List of time series that will be sent to the ThingsBoard platform instance.
server.slaves[].timeseries[].tagKey name of the time series in ThingsBoard. It can be specified as a static value.
server.slaves[].timeseries[].typeData type of value.
server.slaves[].timeseries[].functionCodeFunction code to use for reading the time series value from the Modbus slave.
server.slaves[].timeseries[].objectsCountNumber of objects to read from the Modbus slave.
server.slaves[].timeseries[].addressAddress of the object in the Modbus slave. Can be configured for batch reading.
server.slaves[].timeseries[].divider(Optional) Divider for the value. If not specified, the value will be sent as is.
server.slaves[].timeseries[].multiplier(Optional) Multiplier for the value. If not specified, the value will be sent as is.
server.slaves[].timeseries[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.
mapping[].attributes[].reportStrategy(Optional) Report strategy for the time series data. If not specified, the device report strategy will be used.

Example of the attributes and telemetry configuration:

"attributes": [
{
"tag": "string_read",
"type": "string",
"functionCode": 4,
"objectsCount": 4,
"address": 1
}
],
"timeseries": [
{
"tag": "16uint_read",
"type": "16uint",
"functionCode": 4,
"objectsCount": 2,
"address": 18
},
]
ParameterDescription
server.slaves[].attributeUpdates[]List of attributes that will be updated on the device.
server.slaves[].attributeUpdates[].tagKey name of the shared attribute in ThingsBoard. It can be specified as a static value.
server.slaves[].attributeUpdates[].typeData type of value.
server.slaves[].attributeUpdates[].functionCodeFunction code to use for reading the attribute value from the Modbus slave.
server.slaves[].attributeUpdates[].objectsCountNumber of objects to read from the Modbus slave.
server.slaves[].attributeUpdates[].addressAddress of the object in the Modbus slave.
server.slaves[].attributeUpdates[].timeout (in ms)(Optional) Timeout for the request in milliseconds. If not specified, the default timeout is used (5 sec).
server.slaves[].attributeUpdates[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.

Example of the attributes updates configuration:

{
"tag": "relay",
"type": "bits",
"functionCode": 5,
"objectsCount": 1,
"bitTargetType": "int",
"address": 29
}
ParameterDescription
server.slaves[].rpc[]List of RPC methods that will be available on the device.
server.slaves[].rpc[].tagName of the RPC method. It can be specified as a static value.
server.slaves[].rpc[].typeData type of value.
server.slaves[].rpc[].functionCodeFunction code to use for reading the RPC method value from the Modbus slave.
server.slaves[].rpc[].objectsCountNumber of objects to read from the Modbus slave.
server.slaves[].rpc[].addressAddress of the object in the Modbus slave.
server.slaves[].rpc[].timeout (in ms)(Optional) Timeout for the request in milliseconds. If not specified, the default timeout is used (5 sec).
server.slaves[].rpc[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.

Example of the RPC methods configuration:

"rpc": [
{
"tag": "setValue",
"type": "16int",
"functionCode": 6,
"objectsCount": 1,
"address": 31
}
]

Gateway can run as a Modbus slave. Gateway as a slave can store data, send updates to the platform when changes occur or at fixed intervals, also, user can change storing data via RPCs or shared attribute updates.

Enabling Gateway as a Slave and sending data to the platform

Section titled “Enabling Gateway as a Slave and sending data to the platform”

To enable the Gateway as a Modbus slave, you need to toggle “Enable” button in the “Server configuration” section. Please note that this option will only create a modbus slave, but it will not send any data to the platform automatically:

To send data to the platform, you need to enable “Send data to the platform” toggle in the “Server configuration”, which will enable sending data to the platform when changes occur or at fixed intervals:

Due to the nature of preferred way of communication between Modbus master there are 3 options how to configure this part: TCP, UDP or via Serial port.

The following parameters are used to configure TCP connection for Gateway as a Slave:

  • Host - hostname or IP address of the Modbus server.
  • Port - port of the Modbus server for connection.
  • Method - type of a framer, either Socket or RTU.
  • Unit ID - ID of the current slave on Modbus.
  • Device name - name of the current slave. Don’t use “Gateway” as the value of “Device name” parameter!
  • Device profile - device profile of the current slave.
  • Poll period (ms) - period in milliseconds for checking the attributes and telemetry.

You can configure additional settings like: TLS connection, byte order, word order, and other. The following parameters are used to configure advanced connection settings:

  • Byte order - byte order for the Modbus connection, either LITTLE or BIG.
  • Word order - word order for the Modbus connection, either LITTLE or BIG.
  • Vendor name - name of the vendor for the Modbus connection.
  • Product code - product code for the Modbus connection.
  • Vendor URL - URL of the vendor for the Modbus connection.
  • Product name - name of the product for the Modbus connection.
  • Model name - model name for the Modbus connection.
  • TLS - enable or disable TLS connection for the Modbus connection (Only for TCP and UDP connections):
    • Path to client certificate - path to the client certificate file.
    • Path to client private key - path to the client private key file.
    • Password - password for the client private key file.

To configure advanced connection settings, follow these steps:

  1. Click on the “Advanced connection settings” subsection to open it;

  2. Make the necessary settings.

In this section, you can specify initial values for registers and coils. Each value refers to a specific type of register. There are:

  1. Holding registers
  2. Coils initializer
  3. Input registers
  4. Discrete inputs

For each register type, you can configure the value types that will be used to read/write data. According to the data type you select, the gateway will use the appropriate Modbus function code to read or write data.

To configure the value types for reading, use the attributes and telemetry sections. To write data, use the RPC methods and shared attributes sections. Also note that each value type is configured similarly to the corresponding data types in the attributes and telemetry, RPC methods, and shared attributes sections. The only exception is that you need to set an initial value in the “Value” field.

Depending on which value the register belongs to, you should add it to the appropriate array.

Select basic or advanced Modbus configuration:

To add new value to the gateway slave, use the following steps:

  1. Click on “pencil” icon in the row of the selected section;

  2. In the opened window click “Add attribute” or other (depends on selected section);

  3. Fill in key, type, function code, objects count, address and value fields. Click “Apply”.

The advanced configuration section provides a detailed overview of all available parameters for the Gateway as a Slave configuration section.

Gateway can run as a Modbus slave. This configuration section for the Modbus slave, which is used to store data and send updates to the platform when changes occur or at fixed intervals.

ParameterDefault valueDescription
slave.byteOrderLITTLEThe order of bytes to read.
slave.wordOrderLITTLEThe order of words when reading several registers.
slave.pollPeriod (in ms)5000Period in milliseconds to read and send the attributes and the telemetry to the platform.
slave.sendDataToThingsBoardtrueIf set to TRUE, the Gateway will perform autoconfiguration and send values to ThingsBoard every poll period
slave.unitIdID of current gateway slave on Modbus.
slave.deviceNameDevice name on the platform.
slave.deviceTypedefault(Optional) Device profile name on the platform.

Example of the slave configuration:

"slave": {
"type": "tcp",
"host": "127.0.0.1",
"port": 5026,
"method": "socket",
"deviceName": "Modbus Slave Example",
"deviceType": "default",
"pollPeriod": 5000,
"sendDataToThingsBoard": false,
"byteOrder": "LITTLE",
"wordOrder": "LITTLE",
"unitId": 0,
...
}

The Modbus connector supports three types of connections to the Modbus slave:

  • TCP - connection to the Modbus slave over TCP/IP protocol.
  • UDP - connection to the Modbus slave over UDP protocol.
  • Serial - connection to the Modbus slave over serial port (RS-232, RS-485, etc.).
ParameterDescription
slave.typeType of connection to Modbus device, can be: tpc or udp.
slave.hostHostname or ip address of Modbus server.
slave.portPort of Modbus server for connection.
slave.methodType of a framer Socket or RTU, if needed.

Example of the TPC/UDP configuration:

"slave": {
"type": "tcp",
"host": "127.0.0.1",
"port": 5026,
"method": "socket",
...
}
ParameterDefault valueDescription
slave.typeserialType of connection to Modbus device, can be: tpc or udp.
slave.portPort of Modbus slave for connection.
slave.methodrtuType of a framer Socket or RTU, if needed.
slave.baudrate19200(Optional) Baud rate for serial connection.
slave.stopbits1(Optional) The number of bits sent after each character in a message to indicate the end of the byte.
slave.parityN(Optional) The type of checksum to use to verify data integrity. This can be on of the following: (E) ven, (O)dd, (N)one.
slave.bytesize8(Optional) The number of bits in a byte of serial data. This can be one of 5, 6, 7, or 8.
slave.stricttrue(Optional) Use Inter char timeout for baud rates less than or equal to 19200.
slave.handleLocalEchofalse(Optional) Handle local echo for serial connections. This is useful for devices that echo back the data sent to them.

Example of the serial configuration:

"slave": {
"type": "serial",
"port": 5026,
"method": "rtu",
"baudrate": 4800,
"stopbits": 1,
"bytesize": 5,
"parity": "N",
"strict": true,
"handleLocalEcho": false,
...
}

The Gateway as a Salve supports security configuration. This configuration is used to secure the connection to the Modbus slave and to authenticate the connection. Available only for the TCP and UDP connections.

ParameterDescription
slave.securitySecurity object.
slave.security.keyfileHostname or ip address of Modbus server.
slave.security.certfilePort of Modbus server for connection.
slave.security.passwordType of a framer Socket or RTU, if needed.

Example of the security configuration:

"slave": {
"type": "tcp",
"host": "127.0.0.1",
"port": 5026,
"method": "socket",
"security": {
"keyfile": "/path/to/keyfile.pem",
"certfile": "/path/to/certfile.pem",
"password": "your_password"
}
...
}

The Values list is used to specify the initial values for registers and coils. Each value refers to a specific type of register. There are:

  1. Holding registers
  2. Coils initializer
  3. Input registers
  4. Discrete inputs

For each register type, you can configure the value types that will be used to read/write data. According to the data type you select, the gateway will use the appropriate Modbus function code to read or write data.

ParameterDescription
slave.values[].<register_type>.attributes[]The list of attributes.
slave.values[].<register_type>.attributes[].tagKey name of the attribute on the platform.
slave.values[].<register_type>.attributes[].addressObject address.
slave.values[].<register_type>.attributes[].typeType of value.
slave.values[].<register_type>.attributes[].objectsCountCount of objects to write.
slave.values[].<register_type>.attributes[].valueInitial register value.
slave.values[].<register_type>.attributes[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.
slave.values[].<register_type>.timeseries[]The list of timeseries.
slave.values[].<register_type>.timeseries[].tagKey name of the timeseries on the platform.
slave.values[].<register_type>.timeseries[].addressObject address.
slave.values[].<register_type>.timeseries[].typeType of value.
slave.values[].<register_type>.timeseries[].objectsCountCount of objects to write.
slave.values[].<register_type>.timeseries[].valueInitial register value.
slave.values[].<register_type>.timeseries[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.

Example of the attributes and timeseries configuration:

"slave": {
...
"values": {
"holding_registers": {
"attributes": [
{
"address": 1,
"type": "string",
"tag": "sm",
"objectsCount": 1,
"value": "ON"
}
],
"timeseries": [
{
"address": 2,
"type": "16int",
"tag": "smm",
"objectsCount": 1,
"value": 12334
}
],
}
}
}
ParameterDescription
slave.values[].<register_type>.attributeUpdates[]The list of attribute updates.
slave.values[].<register_type>.attributeUpdates[].tagKey name of the attribute on the platform.
slave.values[].<register_type>.attributeUpdates[].addressObject address.
slave.values[].<register_type>.attributeUpdates[].typeType of value.
slave.values[].<register_type>.attributeUpdates[].functionCodeFunction code to write value.
slave.values[].<register_type>.attributeUpdates[].objectsCountCount of objects to write.
slave.values[].<register_type>.attributeUpdates[].valueInitial register value.
slave.values[].<register_type>.attributeUpdates[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.

Example of the attribute updates configuration:

"slave": {
...
"values": {
"holding_registers": {
"attributeUpdates": [
{
"tag": "shared_attribute_write",
"type": "32int",
"functionCode": 6,
"objectsCount": 2,
"address": 29,
"value": 1243
}
],
}
}
}
ParameterDescription
slave.values[].<register_type>.rpc[]The list of attribute updates.
slave.values[].<register_type>.rpc[].tagKey name of the attribute on the platform.
slave.values[].<register_type>.rpc[].addressObject address.
slave.values[].<register_type>.rpc[].typeType of value.
slave.values[].<register_type>.rpc[].functionCodeFunction code to write value.
slave.values[].<register_type>.rpc[].objectsCountCount of objects to write.
slave.values[].<register_type>.rpc[].valueInitial register value.
slave.values[].<register_type>.rpc[].bitTargetTypeThe response type can be either an integer (0/1) or a boolean (True/False). Used only with type bits.

Example of the RPC methods configuration:

"slave": {
...
"values": {
"holding_registers": {
"rpc": [
{
"tag": "setValue",
"type": "16int",
"functionCode": 5,
"objectsCount": 1,
"address": 31,
"value": 22
}
]
}
}
}

Here’s more details regarding Modbus functions and the supported data types.

The Modbus connector supports the following Modbus functions:

Modbus function codeDescription
Read data
1Read Coils
2Read Discrete Inputs
3Read Multiple Holding Registers
4Read Input Registers
Write data:
5Write Coil
6Write Register
15Write Coils
16Write Registers

A list and description of the supported data types for reading/writing data.

TypeFunction codeObjects countNote
string3-41-…Read bytes from registers and decode it (‘UTF-8’ coding).
bytes3-41-…Read bytes from registers.
bits1-41-…Read coils. If the objects count is 1, result will be interpreted as a boolean. Otherwise the result will be an array with bits.
16int3-41Integer 16 bit.
16uint3-41Unsigned integer 16 bit.
16float3-41Float 16 bit.
32int3-42Integer 32 bit.
32uint3-42Unsigned integer 32 bit.
32float3-42Float 32 bit.
64int3-44Integer 64 bit.
64uint3-44Unsigned integer 64 bit.
64float3-44Float 64 bit.