Modbus has become a de facto standard communication protocol for communication between industrial electronic devices in a wide range of buses and network. The Weble universal gateway supports both the Master and Slave roles over the following 3 variations of the protocol.
In most cases the Modbus driver is used as a master in order to retrieve the Modbus slaves data (such as energy meters data), and to forward that information to another protocol like BACnet, or to the cloud with MQTT.
The modbus driver can also act as a transparent Modbus TCP to RTU gateway using the forward to serial driver parameter (no routes configuration needed) when configuring the modbus TCP slave such as shown in the schema below.
For detailed information about the Modbus protocol, refer to this source https://www.simplymodbus.ca/
For the Modbus RTU serial line wiring it is important to follow the rs485 general guidelines: modbus wiring guidelines article
This introduction uses Modbus TCP, which needs no wiring: one Modbus TCP slave and one Modbus TCP master run on the same device. The slave TCP server will be listening on the default port 502 and the master TCP client will connect to the slave on the loopback ip address 127.0.0.1. As it is often the case in modbus, the master in this tutorial cyclically polls the slave registers.
The first step is to create the modbus slave, select the Type tcpSlave, and the Mode local slave. (Side note: selecting the forward to serial mode would make the TCP slave act as a transparent Modbus TCP slave to RTU master gateway as shown on the schema above.)
Once the gateway is inserted, start the gateway. If the 502 TCP port is not used by another driver / process, the driver starts without issues. Once the driver is started, insert the holding registers from %M1 to %M10 using the default Slave Unit ID (here 1) by selecting the number of addresses and set it to 10. After clicking the Save button, the 10 addresses are inserted.
Once the addresses are inserted, it is possible to manually set the initial values by double clicking on the Value field as shown below.
Create the modbus by inserting a modbus gateway and selecting tcpMaster for the Type parameter. The host address here is the loopback address 127.0.0.1 (localhost).
After starting the master gateway, it is possible to insert the holding registers here starting at the first register: %M1. By selecting 10 for the number of addresses it will insert addresses %M1, %M2, ..., until %M10. An important parameter is to configure the polling rate in milliseconds. In this example it is configured to 10000 ms, which translates to 10 seconds. It means that the modbus master will send read requests every 10 seconds to refresh the register values.
Once the addresses are inserted, the modbus master should be able to read all inserted registers and update the values when they change after a poll. As shown in the screenshot below the values on the master match the values previously configured on the slave.
The parameters of the modbus driver are divided here in 4 categories:
Section 2.6 explains how to use the gateway as a Modbus TCP to RTU (or TCP to TCP) gateway.
In the table below, there is the type parameter used to select the correct type of the modbus driver, and 2 other parameters (unitId and registerOffset) that impact the addressing scheme (see chapter 3 about addresses).
| Label | JSON Key | Description |
|---|---|---|
| Type | type | Selects the role and the physical link layer. There are 4 supported types: tcpMaster, tcpSlave, rtuMaster and rtuSlave (the value is case-sensitive in the JSON). |
| Default unit ID / Slave unit ID | unitId | Master (label Default unit ID): unit ID (0-255, default 1) used by the addresses that do not specify one: %M100 uses the default unit ID, %M2-100 uses unit ID 2. Slave (label Slave unit ID): unit ID of the addresses that do not specify one. An rtuSlave answers the requests sent to this unit ID and to every unit ID used in an address name (%M3-100 makes the gateway also answer as unit 3), and ignores the other unit IDs. A tcpSlave in local slave mode answers every unit ID; each unit ID has its own registers. One gateway can therefore emulate several slaves. |
| Address offset | registerOffset | Offset (integer number) applied to the modbus registers addresses. An offset of -1 is often used to match the modbus slave manufacturer documentation. With an offset of 0, the first holding register is %M0, while with an offset of -1, the first holding register is %M1 |
Standard serial parameters for RS-485 Modbus RTU communication.
| Label | JSON Key | Description |
|---|---|---|
| ASCII | ascii | Activates or deactivates the modbus ascii framing where frames start with ":" and end with a new line "\r\n" while the rest of the frame (the modbus packet) is written on the line using hexadecimal characters 0–9, A–F. If the parameter is false, then standard modbus RTU is used instead where modbus packets are sent directly on the line (binary encoded). |
| Serial Port | serialPort | Selects the serial interface (hardware). Could be an USB to rs485 adapter or the native serial port of the hardware. Device paths and USB adapters: see Serial ports and USB adapters. |
| BaudRate | baudRate | Serial line transmission speed in bauds (bits/seconds). |
| Parity | parity | Defines the parity bit of the serial characters: N for none, E for even, O for odd. |
| Stopbit | stopBit | Number of end bits sent at the end of each serial character / byte |
| DataBit | dataBit | Number of data bits per serial character: 8 (default, Modbus RTU) or 7 (usually Modbus ASCII). Must be identical on every device of the line: a mismatch gives CRC errors or no answer at all. |
| Label | JSON Key | Description |
|---|---|---|
| Port | port | IP port on which the modbus TCP slave waits for new connections (usually port 502). |
| Host | host | only applies when acting as Master. It is the IP or domain name used to reach the modbus slave device. |
The parameters below only apply to the tcpMaster and rtuMaster types.
| Label | JSON Key | Description |
|---|---|---|
| RequestTimeout | requestTimeout | Time in milliseconds to wait for the answer of the slave before the timeout error. The form proposes 3000 for a tcpMaster and 500 for an rtuMaster; a value below 500 is raised to 500. |
| IdleTimeout | idleTimeout | Defines a pause in milliseconds between each new modbus request |
| IgnoreFirstValuesMs | ignoreFirstValuesMs | At boot, ignores the first values during an initial delay in milliseconds. It is sometimes useful to avoid reading invalid values from a slave which needs time to correctly initialize its modbus registers after a reboot. |
| OnErrorValue | onErrorValue | If a modbus register cannot be read due to an error such as timeout, ILLEGAL_DATA_VALUE, or any other error, a pre-defined configured value (usually 0) can be sent on the register address. If the parameter is left empty, then the value is not updated in case of errors. |
| Error retries | errorRetries | Number of consecutive failed polls of an address tolerated before its status switches to error and the OnErrorValue is applied (0 to 5, default 2; 0 reports the first failure). See section 4.1. |
It is possible with type tcpSlave to act as a transparent modbus gateway and forward the received modbus requests on the serial line for modbus RTU slaves, or to another modbus TCP slave. When this forward mode is activated, the tcpSlave acts as a forward master and forward the requests to the slaves, and then also forward back the slave responses to the initial modbus TCP master at the origin of the requests.
| Label | JSON Key | Description |
|---|---|---|
| Mode | mode | Only applies to the type tcpSlave. Choose the operating mode of the TCP slave : local slave, forward to serial, and forward to tcp |
| FillWithZeros | fillWithZeros | Only applies if the slave is of type rtuSlave or if the tcpSlave mode is local slave. If set to true, it initialize all unused registers with 0 s at start. If set to false, sends the error ILLEGAL_DATA_VALUE until a value is set. |
| Forward to ASCII | forwardAscii | Only applies when the tcpSlave mode is forward to serial. Defines if the serial forward master uses the ASCII encoding or the standard modbus RTU. |
| Forward Serial | forwardSerial | Only applies when the tcpSlave mode is forward to serial. Defines the serial port to be used by the forward master. |
| Forward Baudrate | forwardBaudRate | Only applies when the tcpSlave mode is forward to serial. Defines the serial baud rate to be used by the forward master. |
| Forward parity | forwardParity | Only applies when the tcpSlave mode is forward to serial. Defines the serial parity check method to be used by the forward master. |
| Forward StopBit | forwardStopBit | Only applies when the tcpSlave mode is forward to serial. Defines the number of stop bits to be used by the forward master. |
| Forward DataBit | forwardDataBit | Only applies when the tcpSlave mode is forward to serial. Number of data bits (7 or 8, default 8) used by the forward master. |
| Forward Host | forwardHost | Only applies when the tcpSlave mode is forward to tcp. Defines the host (ip or domain name) used to reach the modbus TCP slave that will ultimately receive the forwarded requests. |
| Forward Port | forwardPort | Only applies when the tcpSlave mode is forward to tcp. Defines the TCP port used to reach the modbus TCP slave that will ultimately receive the forwarded requests. |
| Forward Req Timeout | forwardRequestTimeout | Only applies when the tcpSlave mode is forward to tcp or forward to serial. Time in milliseconds the forward master waits for the answer of the slave before the timeout error (500 proposed by the form; 3000 is used when the field is empty or 0). |
| Forward Idle Timeout | forwardIdleTimeout | Only applies when the tcpSlave mode is forward to tcp or forward to serial. It is the forward master minimum pause in milliseconds between new modbus requests. |
The gateway JSON definition of the master and slave gateways described in the getting started section:
{
"name": "modbus slave",
"driver": "modbus",
"description": "",
"active": 1,
"json": {
"type": "tcpSlave",
"ascii": false,
"host": "192.168.1.99",
"port": 502,
"unitId": 1,
"registerOffset": -1,
"serialPort": "",
"requestTimeout": 3000,
"idleTimeout": 20,
"baudRate": 19200,
"parity": "N",
"stopBit": 1,
"ignoreFirstValuesMs": 0,
"onErrorValue": "",
"errorRetries": 2,
"mode": "local slave",
"fillWithZeros": true,
"forwardSerial": "",
"forwardBaudRate": 19200,
"forwardStopBit": 1,
"forwardHost": "",
"forwardPort": "",
"forwardRequestTimeout": 500,
"forwardIdleTimeout": 0,
"readLoopDelay": 0,
"dataBit": 8,
"forwardDataBit": 8,
"optimizeRead": false
}
}
{
"name": "modbus master",
"driver": "modbus",
"description": "",
"active": 1,
"json": {
"type": "tcpMaster",
"ascii": false,
"host": "127.0.0.1",
"port": 502,
"unitId": 1,
"registerOffset": -1,
"serialPort": "",
"requestTimeout": 3000,
"idleTimeout": 20,
"baudRate": 19200,
"parity": "N",
"stopBit": 1,
"ignoreFirstValuesMs": 0,
"onErrorValue": "",
"errorRetries": 2,
"mode": "local slave",
"fillWithZeros": false,
"forwardSerial": "",
"forwardBaudRate": 19200,
"forwardStopBit": 1,
"forwardHost": "",
"forwardPort": "",
"forwardRequestTimeout": 500,
"forwardIdleTimeout": 0,
"readLoopDelay": 0,
"dataBit": 8,
"forwardDataBit": 8,
"optimizeRead": false
}
}
127.0.0.1 and 502).How it behaves:
GATEWAY_PATH_UNAVAILABLE.%M2-100), they are read once when the gateway starts and then updated every time a master reads or writes these registers through the gateway; they can be routed to other protocols. They are not polled cyclically. Writing such an address from the gateway sends the write to the real slave (holding registers and coils only: %Q and %QX addresses are read-only).Intercept routes. The Modbus requests handled by a gateway can be handed to a route of type intercept, whose function builds the answer (for example a value computed on the fly or fetched from another protocol) instead of the local register table of a slave gateway. The read function codes 01 to 04 and the write function codes 05, 06, 15 and 16 can be intercepted. When no intercept route is active, the request is processed normally. See Intercept routes.
Modbus addresses have the following structure:
%[type][unit id-][register][.start bit]
| Example | Meaning |
|---|---|
%M100 |
holding register 100 of the default unit ID |
%M2-100 |
holding register 100 of unit ID 2 |
%M2-100.3 |
start bit 3 of holding register 100 of unit ID 2 |
%Q10, %Q2-10 |
input register 10 |
%MX5, %MX2-5 |
coil 5 |
%QX5, %QX2-5 |
discrete input 5 |
The modbus addresses are sub-divided in 4 main types:
%M. Example of holding registers : %M0, %M1, %M3, ... , %M65535.%Q. Example of input registers : %Q0, %Q1, %Q3, ... , %Q65535.%MX. Example of coils : %MX0, %MX1, %MX3, ... , %MX65535.%QX. Example of discrete inputs : %QX0, %QX1, %QX3, ... , %QX65535.It is possible to set the slave unit id in the address, as in %M2-1 (holding register 1 of slave unit id 2) or %QX1-4 (discrete input 4 of slave unit id 1). The slave unit id is coded on 8 bits (0 to 255 in the address form; standard Modbus slaves use 1 to 247). Defining the slave id is particularly useful when the modbus driver acts as a master and communicates on the rs485 line with multiple slave units. If the slave id is not specified in the address name (as in %M1 or %QX4), then the slave id defaults to the Default unit ID gateway parameter.
Many slave devices documentation are numbering the memory addresses starting from 1 instead of 0 (%M1 being the first register and %M65536 the last one), so a -1 correction offset often needs to be configured in the Address offset gateway parameter.
Bit access. Only holding registers (%M) and input registers (%Q) accept a start bit (field Start bit of the address form). Select the datatype bit to read one bit, or uint8 / int8 to read 8 bits starting at the start bit.
Bits are numbered from the most significant bit.
.0is the MSB of the register (0x8000) and.15is the LSB (0x0001). When a device manual numbers the bits from the LSB (bit 0 =0x0001), use start bit15 - n. For the same reasonuint8on%M100returns the high byte of the register; use%M100.8for the low byte.
When several addresses are inserted at once (Number of addresses) with a datatype smaller than 16 bits, the start bit is incremented by the size of the datatype: with bit, %M100, %M100.1, ... %M100.15, %M101, ...; with uint8, %M100, %M100.8, %M101, ... Writing a bit address reads the whole register, changes the selected bits and writes the register back.
The main parameters of the modbus addresses are
The following table lists all the addresses parameters
| Label | JSON Key | Description |
|---|---|---|
| Datatype | datatype | Specifies the encoding of the values such as int16BE (big endian signed integer stored on one register), floatBE (big endian 32 bits floating point stored on 2 consecutive modbus registers), etc... |
| Scale | scale | Master only. Multiplies the decoded value before it is emitted: value * scale. On a write the inverse is applied. |
| Offset | offset | Master only. Added after the scale: (value * scale) + offset. On a write the gateway sends (value - offset) / scale. |
| COV increment | cov | Master only. Minimum change between the last emitted value and the newly polled value for the new value to be emitted. Empty (default): every change is emitted. 0: the value is emitted at every poll, even when it has not changed (useful to log at a fixed rate, but it multiplies the routed and logged values). |
| Polling(ms) | readLoopDelay | Master only. Polling period in milliseconds, for example 10000 to refresh the address every 10 seconds (the form proposes 100: raise it on slow serial lines). Other accepted values: a CRON expression for readings at fixed times (for example */15 * * * *); several periods or CRON expressions separated by ;; 0 to disable polling (the address is then only read on demand, for example with the read link of the value column). With a CRON expression the value is emitted at every execution, even when it has not changed. |
| Double read | doubleRead | If the driver acts as Master, it makes two consecutives reads to ensure the correctness of the new value. |
| Group | group | If the driver acts as master, it lets you set a group integer identifier on addresses. If consecutive registers/addresses are configured with the same group (such as group 1 or 2), then the master attempts, instead of doing one query per address, to read all the registers of this group at once using a single modbus request. It can be used to optimize the polling loop or to suit special slave requirements. See How the master groups its read requests below. |
| Store value | remanent | If the driver acts as Slave, then it specifies whether to store the values on the disk or not. If the slave values are not stored on the disk, they are lost after the system reboot. Store values : "never", "always", or a delay in milliseconds such as 60000 to save the address value on the disk every minute. |
By default the master sends one read request per address (an address that spans several registers, such as a floatBE, is read in one request). With many addresses on a slow serial line this takes time: each request costs the response time of the slave plus the IdleTimeout pause.
To read several addresses in a single request, give them the same non-zero Group number. Addresses are merged when they have the same register type (%M, %Q, %MX or %QX), the same unit ID, the same Polling value and the same group, as long as:
When one of these limits is exceeded, the group is automatically split into several requests. Group 0 (default) means "not grouped".
The Optimize read checkbox is only displayed on gateways where it is already enabled; it does not merge addresses that have no group.
The datatype defines how the raw register bits are decoded and encoded. A Modbus register is 16 bits wide, so wider datatypes span several consecutive registers: floatBE on %M100 uses registers 100 and 101, doubleBE uses four registers. Addresses should not overlap.
| Datatype | Size | Registers | Description |
|---|---|---|---|
bit |
1 bit | - | One bit. Type of coils and discrete inputs (set automatically). On a register, combine it with a start bit (%M100.3). |
int8, uint8 |
8 bits | 1 | Signed / unsigned byte taken from a register: the high byte by default, the low byte with start bit 8 (%M100.8). |
int16BE, uint16BE |
16 bits | 1 | Signed / unsigned 16-bit integer, standard Modbus byte order. |
int16LE, uint16LE |
16 bits | 1 | Same, with the two bytes of the register swapped. |
int32BE, uint32BE, int32LE, uint32LE |
32 bits | 2 | Signed / unsigned 32-bit integer. |
int48BE, uint48BE, int48LE, uint48LE |
48 bits | 3 | Signed / unsigned 48-bit integer. BE: most significant register first. LE (special case): the first register holds the 16 most significant bits and the next two registers the 32 least significant bits, each part with its bytes in little-endian order. |
int64BE, uint64BE, int64LE, uint64LE |
64 bits | 4 | Signed / unsigned 64-bit integer (exact up to 2^53). |
floatBE, floatLE |
32 bits | 2 | IEEE 754 single precision floating point. |
doubleBE, doubleLE |
64 bits | 4 | IEEE 754 double precision floating point. |
bcd8 |
8 bits | 1 | 2 binary-coded decimal digits (0-99). |
bcd16BE, bcd16LE |
16 bits | 1 | 4 BCD digits (0-9999). |
bcd32BE, bcd32LE |
32 bits | 2 | 8 BCD digits (0-99999999). |
mod10000_2_BE, mod10000_3_BE, mod10000_4_BE (and _LE) |
32 / 48 / 64 bits | 2 / 3 / 4 | Modulo-10000 format: each register holds four decimal digits (0-9999). With _BE the value is R1 + R2 x 10000 + R3 x 10000^2 + ..., the first register being the least significant; add _sw when the first register is the most significant. _LE reverses all the bytes of the value: the first register is then the most significant and the two bytes of each register are swapped. |
hex_1 ... hex_8 |
16 ... 128 bits | 1 ... 8 | Raw content of N registers as a hexadecimal string (4 hex digits per register). |
ascii_1 ... ascii_8 |
16 ... 128 bits | 1 ... 8 | Text stored in N registers (2 characters per register). |
| Suffix | Effect | Available for |
|---|---|---|
BE / LE |
BE: most significant byte first. LE: all the bytes of the value are reversed (exception: the 48-bit types, see above). |
part of the base type name |
_sw (swap words) |
The order of the 16-bit registers is reversed. | every type of 2 registers or more |
_sb (swap bits) |
The bit order of the whole value is mirrored (first bit <-> last bit). This is not a byte swap and is rarely needed. | every type except bit and ascii_N |
_sw_sb |
Both of the above. | every type of 2 registers or more, except ascii_N |
For a 32-bit value, the four usual byte orders are covered by BE / LE, with or without _sw. Example with the float value 230.0 (0x43660000):
| First register | Second register | Byte order | Datatype |
|---|---|---|---|
0x4366 |
0x0000 |
A B C D | floatBE |
0x0000 |
0x4366 |
C D A B | floatBE_sw |
0x0000 |
0x6643 |
D C B A | floatLE |
0x6643 |
0x0000 |
B A D C | floatLE_sw |
If a value looks scrambled, try these four variants first.
Modbus slaves usually use different registers depending on their manufacturer and model. It is often necessary to read the slave documentation to know which registers to read, and how the data is encoded (datatype). Then it is necessary to manually configure the addresses in the Modbus gateway. All these steps are time consuming and repetitive, especially when working with several slaves of the same model. In order to solve this problem, model files can be defined to automatically import the configuration.
It is straightforward to import a model from model files. Once the popup is open, it is possible to select the model file, and then choose the range of unit ids to import in the gateway. In the screenshot below, the inepro PRO380 model is imported twice from slave unit id 1 to slave unit id 2.
After the confirmation of the import, the addresses with the correct datatype and description are automatically imported.
It is easy to create a model from your current modbus gateway configuration. The first step is to select one of the addresses belonging to the slave unit id from which you would like to export the model.
A model file (extension .modbus) is a JSON text file that can be edited with any text or code editor. Usually companies keep and maintain their own list of models. Some model files are provided below as examples.
Example of a model file:
{
"name": "My meter",
"registers": {
"%M20482": { "description": "Phase 1 line to neutral volts.", "json": { "datatype": "floatBE", "readLoopDelay": 10000 } },
"%M20492": { "description": "Phase 1 current.", "json": { "datatype": "floatBE", "readLoopDelay": 10000, "scale": 1 } }
}
}
registers are %M, %Q, %MX or %QX followed by the register number, without unit ID. On import, one address %<type><unit id>-<register> is created per register and per unit ID of the selected range.description, log and every key of json (datatype, readLoopDelay, scale, offset, cov, group...).description, datatype and readLoopDelay of the addresses of the selected unit ID. Add the other parameters (scale, group...) by hand in the file if needed. Coils and discrete inputs are not exported correctly, and the start bit of bit addresses (%M100.3) is lost on import.{
"name": "%M2-16383",
"description": "Serial",
"json": { "datatype": "hex_2", "readLoopDelay": 10000 }
}
{
"name": "%M1-24599",
"description": "Export Wh since last reset",
"json": { "datatype": "floatBE", "readLoopDelay": "*/15 * * * *", "cov": 0.1 }
}
| Gateway role | Writable address types |
|---|---|
| Master | Holding registers (%M) and coils (%MX). Input registers (%Q) and discrete inputs (%QX) are read-only. |
| Slave | All four types in local slave mode: writing an address sets the value that the gateway serves to the remote master. On a tcpSlave in a forward to ... mode, a write to %M or %MX is sent to the real slave and %Q / %QX are read-only. |
When the gateway is master:
(value - offset) / scale, and rounded for integer datatypes. A value outside the range of the datatype is refused with the error invalid value;device offline.Reads use function codes 01 (coils), 02 (discrete inputs), 03 (holding registers) and 04 (input registers).
Each address of a master gateway has a status: online after a successful read, or ! <error> after repeated failures, for example ! timeout, ! ILLEGAL_DATA_ADDRESS or ! GATEWAY_TARGET_TIMEOUT. The status can be routed (route type status, see routes) to raise an alarm.
timeout (or a GATEWAY_TARGET_TIMEOUT returned by a TCP to RTU gateway), the unit ID is considered offline for 10 seconds: its reads are skipped and its writes fail immediately with device offline, so that a missing slave does not slow down the other slaves of the line. The slave is probed again after 10 seconds.| Symptom | What to check |
|---|---|
! timeout on every address of a unit |
Wiring, unit ID, baud rate / parity / data bits / stop bits (RTU), host and port (TCP). Raise RequestTimeout for slow slaves. |
! ILLEGAL_DATA_ADDRESS |
Wrong register number: check the Address offset (-1 or 0), the register type (%M holding or %Q input) and that grouped addresses do not span registers the slave does not implement. |
| Values shifted by one register | Address offset. |
| Absurd 32-bit or float values | Byte and word order: try the BE, LE, BE_sw and LE_sw variants of the datatype (section 3.2). |
! MISSMATCH DOUBLE READ |
Double read is enabled and two consecutive reads returned different data. |
A master reading the gateway gets ILLEGAL_DATA_VALUE |
Gateway used as slave: the register has no value yet. Set a value or enable FillWithZeros. |
The Monitor entry of the address table menu of a Modbus gateway opens a live view of the Modbus frames exchanged by the gateway. It is available for the four gateway types (TCP or RTU, master or slave) and shows for each frame: time, direction (TX / RX), type, transaction id, unit ID, function code, first address, quantity, data, error and raw bytes. The columns can be filtered, for example on a unit ID or on errors.
Use it to check which requests are really sent, what the slave answers and how long it takes. A capture stops by itself after 5 minutes, and only one monitor can run on a gateway at a time.