Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Modbus

Kconfig: CONFIG_MODULE_MODBUS — GClasses: C_PROT_MODBUS_M

Modbus protocol master — reads/writes device registers (coils, discrete inputs, input/holding registers). For industrial IoT.

C_PROT_MODBUS_M

Modbus master protocol — supports four object types:

ObjectAccessSize
Coilsread-write1 bit
Discrete Inputsread-only1 bit
Input Registersread-only16 bits
Holding Registersread-write16 bits

Address range 0x0000–0xFFFF. Configuration-driven slave device mapping with data-format conversion and multiplier support.

The master runs over C_TCP ("modbus_protocol": "TCP", the default) or over C_UART ("RTU"). Without a bottom gobj it creates its own, chosen by modbus_protocol and not by url: a C_TCP for TCP, a C_UART otherwise. An "RTU" master with a tcp:// url creates a C_UART that tries to open tcp://... as a device, and never connects (“Cannot open tty device” at every try). RTU through a tcp:// gateway to a serial bus (RTU frames carried over TCP) needs a C_TCP bottom given by its host:

hgobj master = gobj_create("modbus", C_PROT_MODBUS_M,
    json_pack("{s:s, s:i, s:o}",
        "modbus_protocol", "RTU",
        "baudrate", 19200,          // the speed of the bus behind the gateway
        "slaves", jn_slaves
    ),
    gobj
);
hgobj tcp = gobj_create_pure_child("modbus", C_TCP,
    json_pack("{s:s}", "url", "tcp://192.168.50.20:4001"),
    master
);
gobj_set_bottom_gobj(master, tcp);
gobj_start(master);

Configuration

The slaves attribute is the whole map: one entry per slave (unit id), each with the blocks to read (mapping, one request per block) and the variables decoded from them (conversion). A 32-bit total power of a meter that keeps its low word first, read over TCP:

{
    "modbus_protocol": "TCP",
    "url": "tcp://192.0.2.10:502",
    "timeout_polling": 10000,
    "timeout_response": 3,
    "slaves": [
        {
            "id": 1,
            "mapping": [
                {"type": "holding_register", "address": 14336, "size": 8}
            ],
            "conversion": [
                {
                    "id": "p_total",
                    "type": "holding_register",
                    "address": 14336,
                    "format": "int32",
                    "endian": "little endian byte swap"
                }
            ]
        }
    ]
}

The same meter on a serial line (RTU) behind the master’s own C_UART. Over RTU two more attributes count: baudrate, the speed of the line, and turnaround_delay, the wait after a broadcast (see Broadcast, below):

{
    "modbus_protocol": "RTU",
    "url": "/dev/ttyUSB0",
    "baudrate": 9600,
    "turnaround_delay": 200,
    "timeout_polling": 10000,
    "timeout_response": 3,
    "slaves": [
        {
            "id": 1,
            "mapping": [
                {"type": "holding_register", "address": 14336, "size": 8}
            ],
            "conversion": [
                {"id": "p_total", "type": "holding_register", "address": 14336,
                 "format": "int32", "endian": "little endian byte swap"}
            ]
        }
    ]
}
AttributeDefault
modbus_protocol"TCP"TCP, RTU or ASCII
url""tcp://<host>:<port>, or the serial device
slaves[]The map, above. Read at mt_start: written while the gobj runs, it takes effect at the next start, with a warning (“Modbus slaves written while the master runs: they take effect at the next start”)
timeout_polling1000Milliseconds between the end of a cycle and the next. The timer counts whole seconds (C_TIMER), so less than 1000 is 1 s
timeout_response10Seconds a slave has to answer one request
turnaround_delay200Over RTU, milliseconds after a broadcast write (slave 0) has left the line before it is answered as done and the next request goes out: the time the slaves need to carry it out (the turnaround delay of the Modbus serial line specification, typically 100-200 ms). It is counted from the end of the frame: the wait is the time of the frame on the line (baudrate) plus this delay. 0 or a negative value is taken as 0: the wait is then the frame alone. The timer ends at the next tick of the yuno (timeout_periodic, 1000 ms by default), so the wait lasts up to one tick more: with the defaults and a short frame, about 1.2 s at most
baudrate9600Over RTU, the speed of the serial line, used to count how long a frame takes on it (11 bits a byte). A C_UART below says its own baudrate, the speed its line runs at, which wins: the bottom of the master, or a C_UART under other layers (the first gobj of the bottom chain that has a baudrate). A speed the tty does not know runs at 9600, and its baudrate says 9600. The C_UART the master creates gets this one. Behind a tcp:// gateway to a serial bus, set it to the speed of that bus: the master cannot see it. That gateway needs a C_TCP bottom given by the host: an "RTU" master creates a C_UART, whatever its url says (see above)
rx_noise_dropped0Stats (read only, counted since the gobj was created): over RTU, the noise dropped -- the bytes after an answer in its read, the bytes that cannot start an answer, and the bytes that come while a broadcast is in flight (below, and those are warned under their own name). One per drop, not per byte

To change the map of a running master, stop it, write slaves and start it again (gobj_write_json_attr() does not take the reference: free yours):

gobj_stop(gobj_modbus);
gobj_write_json_attr(gobj_modbus, "slaves", jn_slaves);
JSON_DECREF(jn_slaves)
gobj_start(gobj_modbus);

(Up to 7.29.3 a write while the master ran freed the map that the cycle in flight pointed into.)

The polling cycle

On EV_CONNECTED the master publishes EV_ON_OPEN and polls 1 s later. A cycle reads each block of each slave in order, one request at a time. A response, an exception or timeout_response moves it to the next block. A disabled block is skipped (see mapping above). After the last block of the last slave it publishes, and the next cycle starts timeout_polling later. When the last request of a cycle ends in a timeout, the next cycle starts timeout_response later instead: a slave that did not answer is given that time again before it is polled. On EV_DISCONNECTED it publishes EV_ON_CLOSE, and a C_TCP reconnects on its own.

What a message carries

At the end of each cycle it publishes one EV_ON_MESSAGE per slave: the slave_id and one key per variable, decoded and multiplied.

{"slave_id": 1, "p_total": 5790}

Only what the cycle read. A variable is published only when every cell it spans was stored since the previous publication, that is, when its block was answered in this cycle. A block that timed out or was answered with an exception leaves its variables out of the message, and a slave none of whose blocks answered is not published at all. Each failure was logged where it started (Modbus Timeout, modbus exception: see below). So a subscriber can receive a message with fewer variables than the map declares, and must not read a missing one as zero. The cells read before a disconnection are discarded with it. (Up to SDK 7.27.7 every variable of every slave was published each cycle: a slave that stopped answering repeated its last values, and one that never answered came out as zeros.)

A consumer that depends on this refuses to build against an older module, with the macro its header defines since this change:

#include <c_prot_modbus_m.h>
#ifndef C_PROT_MODBUS_M_PUBLISHES_WHAT_IT_READ
#error "C_PROT_MODBUS_M publishes what it did not read: needs the SDK after 7.27.7"
#endif

Exceptions and timeouts

An exception response, or a block that does not answer within timeout_response, moves the cycle on at once to the next block. Over TCP the frame ends at the exception code. RTU adds its CRC, and the exception is taken only after its CRC is checked. An RTU answer whose CRC does not match fails its block the same way (“Modbus answer with a bad CRC”), as a warning.

An answer that does not fit what the block asked -- another quantity (“Quantity not corresponding to the request”), a byte count that is not its length (“byte_count != len”), another slave (“slave_id NOT MATCH”) -- fails the block too.

Each failure is logged as a warning (msgset Protocol: the slave answered, or did not, and nothing is broken on our side), with the slave_id, the exception code and name, and the block it answered. It is logged when the block starts failing, or starts failing another way (a new exception code, or a timeout after an exception), not on every cycle: a unit id that does not exist answers the same exception every cycle, and that is one fact. So is a map whose block asks 1 register where the slave answers 2 (up to 7.29.3 that one was logged every cycle). When the block answers again, an info says so, with what it failed with:

{"msg": "modbus exception", "slave_id": 4, "error_code": 2,
 "error_name": "ILLEGAL_DATA_ADDRESS",
 "block": {"type": "holding_register", "address": 256, "size": 12}}
{"msg": "Modbus block answered again", "slave_id": 4,
 "failed_with": "modbus exception 2"}

The exception and the timeout of a request (below) are logged every time, with the request (request), not a block. (Up to SDK 7.27.7 the TCP master waited after an exception for a CRC that TCP does not carry, so each exception cost timeout_response and held the poll of every slave of the connection. Also, every exception and timeout of every cycle was an error.)

Requests: writes, and reads outside the map

A request is an EV_SEND_MESSAGE to the gobj: a write (the default), or a read of registers or bits that are not in the polling map, once.

gobj_send_event(gobj_modbus, EV_SEND_MESSAGE,
    json_pack("{s:i, s:s, s:i, s:[iii]}",
        "id", 1,
        "type", "holding_register",
        "address", 46208,
        "value", 1, 10, 0
    ),
    gobj
);
gobj_send_event(gobj_modbus, EV_SEND_MESSAGE,
    json_pack("{s:s, s:i, s:s, s:i, s:i}",
        "operation", "read",
        "id", 1,
        "type", "holding_register",
        "address", 46208,
        "size", 3
    ),
    gobj
);
Key
operation"write"write or read
id1Slave id, 0-255. Over RTU 0 is the broadcast: a write to it is answered as done without an answer from a slave, and a read from it is refused (Broadcast, below). The ids 248-255 are reserved: a request to one is refused (“slave id 248 is reserved in Modbus RTU (248-255)”)
typeWrite: holding_register, coil. Read: also input_register, input_status
address0-65535. With size, the last one too: address + size - 1 is at most 65535
size1A read: how many (at most 125 registers, 2000 bits). A write takes it from its values
valueA write: a number, or an array of them (at most 123 registers, 1968 coils). A register value is -32768..65535, and a coil is ON if not 0

Every number of a request (id, address, size, each value) is read as the command parser reads an integer: a json integer, a real with no decimals (20.0), a boolean as 1 or 0, or the whole text of a JSON integer ("4096", "-3"). Anything else is refused, never turned into a number:

{"type": "holding_register", "address": "abc", "value": 1}      -> "the address is not a number"
{"type": "holding_register", "address": null, "value": 1}       -> "the address is not a number"
{"operation": "read", "type": "holding_register", "address": "010"}  -> refused, not 8
{"operation": "read", "type": "holding_register", "address": 20.9}   -> refused, not 20
{"id": "x", "type": "holding_register", "address": 20, "value": 1}   -> "the slave id is not a number" (not 0, the RTU broadcast)
{"id": 248, "type": "holding_register", "address": 20, "value": 1}   -> over RTU: "slave id 248 is reserved in Modbus RTU (248-255)"
{"operation": "read", "id": 0, "type": "holding_register", "address": 20}
                                                                -> over RTU: "slave id 0 is the broadcast in Modbus RTU: no slave answers a read"
{"type": "holding_register", "address": 20, "value": "12ab"}    -> "value 0 of the write is not a number"
{"operation": "read", "type": "holding_register", "address": 65535, "size": 2}
                                                                -> "address 65535 and size 2 pass 65535"

(Up to 7.29.2 each of them was sent: "abc" and null as address 0, "010" as 8, 20.9 as 20, "x" as slave 0, "12ab" as 12.)

Anything else in the request travels back in its answer, so a caller can tag it. What goes out: a read with function 01, 02, 03 or 04 by its type. A write of one holding register goes with 06, of several with 16. One coil goes with 05 (ON is 0xFF00), several with 15. It works over TCP and RTU, and ASCII is not built.

Every request is answered, with EV_MODBUS_ANSWER, also when it fails:

{"request": {"operation": "read", "id": 1, "type": "holding_register",
             "address": 46208, "size": 3},
 "result": 0, "comment": "", "error_code": 0, "values": [1, 10, 0]}
{"request": {"operation": "write", "id": 1, "type": "holding_register",
             "address": 46213, "size": 1, "value": [100]},
 "result": -1, "comment": "modbus exception 1 ILLEGAL_FUNCTION",
 "error_code": 1}

request comes with its defaults filled in and the value of a write as an array. result is 0 when done, -1 when not, with the reason in comment, and the Modbus exception, if the slave sent one, in error_code. values are the registers of a read, or its bits as 0/1. A write is checked against the echo the slave answers with (its address, and its value or quantity): an echo that does not match fails it. A log never shows the values of a write (it says "value": "(not logged)"): a write can carry a secret, the password a meter asks before its setup, and the log goes to the logcenter. The answer does carry them -- it goes back only to the gobj that sent the request. A request that cannot be sent -- a bad key, an unknown type, a size out of range -- is answered at once, failed, and logged as an error (“Modbus request refused”). Its reason names a value of the write by its position, never by the value (“value 0 of the write does not fit in a register (-32768..65535)”): it is the why of that log, and the comment of the answer.

{"request": {"type": "holding_register", "address": 20, "value": 70000},
 "result": -1, "error_code": 0,
 "comment": "value 0 of the write does not fit in a register (-32768..65535)"}

The gobj above must declare EV_MODBUS_ANSWER in its FSM.

Broadcast, over RTU. Slave 0 is the broadcast of the Modbus serial line: every slave executes the write, and no slave answers it. So a write to slave 0 goes out and no answer is awaited: once its frame has left the line and turnaround_delay has passed, the time the slaves need to carry it out, it is answered as done, and the next request or block goes out. Done means sent: no slave says that it took it. A read from slave 0 is refused at once: no slave answers it, so it can read nothing.

The wait is counted from the end of the frame. A frame of n bytes takes n * 11 * 1000 / baudrate ms on the line, and the wait is that plus turnaround_delay, ended at the next tick of the yuno. A write of 123 registers (255 bytes) at 9600 baud takes 293 ms on the line: the wait is at least 493 ms.

baudrate 9600, turnaround_delay 200, a write of 123 registers to slave 0
    frame 255 bytes -> 293 ms on the line -> answered as done at the first tick after 493 ms
baudrate 9600, turnaround_delay 200, a write of 1 register to slave 0
    frame 8 bytes   -> 10 ms on the line  -> at the first tick after 210 ms (1.2 s at most)
turnaround_delay 0
    -> at the first tick after the frame has left the line
gobj_send_event(gobj_modbus, EV_SEND_MESSAGE,
    json_pack("{s:i, s:s, s:i, s:i}",
        "id", 0,
        "type", "holding_register",
        "address", 80,
        "value", 4660
    ),
    gobj
);
{"request": {"operation": "write", "id": 0, "type": "holding_register",
             "address": 80, "size": 1, "value": [4660]},
 "result": 0, "comment": "broadcast: no answer expected", "error_code": 0}

The bytes that come while a broadcast is in flight are dropped: they cannot be an answer. A device that breaks the standard and answers a broadcast (00 06 00 50 12 34 <crc>, an echo) is dropped that way, and the next answer is read clean. They are counted in rx_noise_dropped, and warned once per connection under their own name, not as the noise of the line (whose warning they leave alone):

{"msg": "Modbus: bytes during a broadcast, dropped: a device answers broadcasts, against the standard",
 "len": 8, "note": "logged once per connection; counted in rx_noise_dropped"}

An echo that comes after the wait almost always eats the next answer. Then nothing is in flight but the next request: the 0x00 of the echo is dropped, and the bytes after it are taken as the head of a frame of slave 6 (06 00 50 ...), which swallows the answer awaited. That request fails at timeout_response. With such a device, set turnaround_delay above the time it takes to echo.

A broadcast that the connection or a stop cuts is not confirmed. It is never answered, so what is cut is its wait: the slaves possibly executed the frame. Its answer, and the warning, say so, not “before its answer”:

{"request": {"operation": "write", "id": 0, ...}, "result": -1, "error_code": 0,
 "comment": "broadcast sent, not confirmed: the connection dropped before its turnaround delay ended (no slave answers a broadcast)"}
{"msg": "Modbus broadcast NOT confirmed, the connection dropped before its turnaround delay ended: it may have been carried out"}
{"msg": "Modbus broadcast NOT confirmed, the gobj stopped before its turnaround delay ended: it may have been carried out"}

Over TCP slave 0 is a unit id like any other, and its answer is awaited.

(Up to 7.29.3 a read from slave 0 over RTU went out, and a broadcast write failed at timeout_response, done or not, after 10 s of silence on the line.)

When it goes out. A request that arrives while the connection waits between two cycles goes out at once, and the wait resumes after the requests. So does one sent on the EV_ON_MESSAGE that ends a cycle: the wait between cycles comes after it (up to 7.29.2 such a request waited that whole timeout_polling first). One that arrives while a block or another request is in flight goes out after it, before the next block. They go one at a time, in the order they came, so a request that needs another before it in the same connection -- a meter password, and the setup it unlocks -- is sent after it.

A request is valid for the connection it was queued in. When the connection drops, the request in flight and every queued one are answered as failed (“the connection dropped...”) and none of them is sent on the next connection: whatever unlocked them on the old one, a password, is gone with it. A request sent while there is no connection is answered at once (“not connected”). A stop of the gobj drops them, with a warning that lists them (“Modbus requests NOT sent, the gobj stopped”, and “Modbus request NOT confirmed, the gobj stopped before its answer” for the one in flight).

A request that depends on another is sent from the other’s answer. A meter that asks its password before its setup: send the password, and send the setup from the EV_MODBUS_ANSWER of the password when it is good. Nothing has to be stopped when the password is refused: the setup was never queued. (The src of a published event is the master.)

PRIVATE int ac_modbus_answer(hgobj gobj, gobj_event_t event, json_t *kw, hgobj src)
{
    const char *step = kw_get_str(gobj, kw, "request`step", "", 0);
    BOOL done = json_integer_value(json_object_get(kw, "result")) == 0;

    if(strcmp(step, "password")==0) {
        if(done) {
            gobj_send_event(src, EV_SEND_MESSAGE,
                json_pack("{s:s, s:i, s:s, s:i, s:i}",
                    "step", "setup",
                    "id", 1,
                    "type", "holding_register",
                    "address", 46213,
                    "value", 100
                ),
                gobj
            );
        } else {
            gobj_log_warning(gobj, 0,
                "function",     "%s", __FUNCTION__,
                "msgset",       "%s", MSGSET_PROTOCOL,
                "msg",          "%s", "Meter refused the password, its setup is not sent",
                "comment",      "%s", kw_get_str(gobj, kw, "comment", "", 0),
                NULL
            );
        }
    }

    JSON_DECREF(kw)
    return 0;
}

/* in its FSM */
{EV_MODBUS_ANSWER,      ac_modbus_answer,       0},

(step is a key of the caller’s: anything else in a request travels back in its answer.)

To stop the master from one of its answers, post the stop. An answer, and a cycle, are published inside the read of the transport: a subscriber never stops or destroys the publisher’s tree there, synchronously. Post an event to yourself with gobj_post_event(), and stop the master in its action (EV_STOP_METER is an event of the caller’s):

PRIVATE int ac_modbus_answer(hgobj gobj, gobj_event_t event, json_t *kw, hgobj src)
{
    if(json_integer_value(json_object_get(kw, "result")) != 0) {
        gobj_post_event(gobj, EV_STOP_METER, json_object(), gobj);
    }
    JSON_DECREF(kw)
    return 0;
}

PRIVATE int ac_stop_meter(hgobj gobj, gobj_event_t event, json_t *kw, hgobj src)
{
    PRIVATE_DATA *priv = gobj_priv_data(gobj);

    gobj_stop(priv->gobj_modbus);
    JSON_DECREF(kw)
    return 0;
}

A posted stop comes after the master sent what was queued next: the dependent request is sent from the good answer, above, so there is nothing queued for the stop to catch.

The master survives a stop from anywhere, also from inside its own EV_MODBUS_ANSWER or EV_ON_MESSAGE: after it publishes it checks that it still runs, and then sends nothing more, polls no block and arms no wait. The requests still queued are dropped with the warning of a stop. (Up to 7.29.3 it went on with its cycle on the stopped gobj, and logged “cur_slave_ NULL” there and at the next tick.) Its transport ends such a stop as any other: a C_UART closes its tty and publishes EV_DISCONNECTED and EV_STOPPED (see its stop contract). Up to 7.29.3 a C_UART stopped inside its own read kept its tty open and answered -1 to the event loop, which ended the yuno.

Which answer is taken. Only an answer to what is in flight, a block or a request. Over TCP it must carry the transaction id of the frame sent and protocol 0: the late answer of a request that timed out has the same slave, function and size as the request sent after it, and without that check it is taken for it: a value of another register given as good. Such a frame, and any frame that comes while nothing is in flight, is read whole and dropped with a warning. What is in flight goes on waiting for its own answer:

{"msg": "Modbus frame dropped: not the answer awaited", "in_flight": 1,
 "t_id": 9, "t_id_sent": 10, "protocol": 0, "slave_id": 1,
 "modbus_function": 3, "length": 5}

RTU carries no transaction id: there a frame is dropped the same way when nothing is in flight, or when its slave or its function is not the one sent -- an exception’s function without its 0x80 bit. The late exception of a read that timed out (0x83) is not the answer of the write (06) sent after it: it is dropped, and the echo that follows answers the write. A late answer with the same slave, function and size as the next request still cannot be told from its answer. An RTU answer is checked against its CRC before anything in it is taken, an exception included.

{"msg": "Modbus frame dropped: not the answer awaited", "in_flight": 1,
 "slave_id": 1, "slave_id_sent": 1, "modbus_function": 131,
 "modbus_function_sent": 6}

Over TCP an answer with the transaction id sent but another function, an exception included (a 0x84 to a 03), is a broken answer: it fails the request, or the block, as “Modbus answer of another function”. A block is always a read, so the echo of a write (06) to one fails it too. A broken answer -- a bad CRC (“Modbus answer with a bad CRC”), another function, or a frame that does not match the request (“Modbus answer of a request does not match it”, for example an MBAP of length 3 to a read) -- fails the request as a warning: the bytes are the peer’s.

Bytes that come after an answer in the same read, over TCP, came before the next request went out: the frame they start is not its answer. It is read whole (its head can come in the next read) and dropped, with "in_flight": 0, and the answer after it is read. An MBAP length outside 3-254 (the unit and a PDU of at most 253 bytes) says nowhere a frame ends: the connection is dropped (“Modbus TCP: bad MBAP length, the connection is dropped”), which answers what was in flight and every queued request as failed (below).

A byte over TCP that is no frame drops the connection. TCP loses and adds nothing, so such a byte is from a broken slave or gateway. The head read across it is shifted, and its MBAP length is out of range (with one stray byte it reads 0): the connection is dropped and made again. That is the resync, on purpose: searching the stream for something that looks like an MBAP head can take the bytes of a value for one.

answer of the block + 0x00, in one read; the next answer 00 07 00 00 00 05 01 03 02 ...
    -> the next head is 00 00 07 00 00 00 05 01 03: {"msg": "Modbus TCP: bad MBAP
       length, the connection is dropped", "length": 0}

Over RTU the bytes after an answer in the same read are dropped. An RTU frame carries no length, and its head is all that says where it ends: a noise byte when the slave releases the RS485 line, taken as the head of the next frame, made the answer after it “not the answer awaited”, or kept the master waiting for more bytes until timeout_response. The next answer starts a read of its own: it comes after the next request goes out.

Over RTU a byte that cannot start an answer is dropped too, where a frame can start (at the start of a read, or after a frame dropped in it): a 0x00 (slave 0 is the broadcast, which no slave answers) or a 0xF8-0xFF (slave ids 248-255 are reserved). While a broadcast is in flight every byte is dropped there: no answer can come (Broadcast, above). That is the noise byte that comes in a read of its own, before an answer or between two: taken as a head, it lost the answer after it (up to 7.29.3). A noise byte 0x01-0xF7 there is still taken as a head: it can be the first byte of a late frame of another slave, whose head says how long it is, and which is read whole and dropped. If every byte that is not the id of the slave asked is dropped, that frame is cut in pieces, and a piece taken as a head swallows the answer awaited. That noise byte is the limit: the answer after it is lost (the request fails at timeout_response, and the next one starts clean).

Each drop is counted in the stats attribute rx_noise_dropped, before the answer it follows is published. The warning (“Modbus: bytes after the answer, dropped” or “Modbus: bytes that cannot start an answer, dropped”, len, and the bytes during a broadcast have their own, above) is logged when the noise starts, once per connection, not for every answer: a line that spikes in every cycle is one fact. It is logged again only after a polling cycle that polled a block and dropped nothing, which an info says (“Modbus: a cycle came without noise”, with the count so far). A cycle that polled nothing -- a master whose map has no block it can poll, and only serves requests -- says nothing of the line: such a master warns once per connection. The traffic trace dumps every drop. The transition is the cycle, not the answer: a line that spikes on some answers of every cycle stays one warning, where, with a transition per answer, the log has a line at each change.

01 03 02 00 46 <crc> 00          one read: the answer, then a noise byte
    -> the answer is taken; {"msg": "Modbus: bytes after the answer, dropped", "len": 1,
       "note": "logged again only after a polled cycle without noise; counted in rx_noise_dropped"}
FF                               a read of its own, the request in flight
01 03 02 00 49 <crc>             the next read: the answer
    -> FF dropped, counted; no log while the noise goes on; the answer is taken
... noise in the next cycles too: no log, rx_noise_dropped grows
... a cycle that polls a block, without noise:
    -> {"msg": "Modbus: a cycle came without noise", "rx_noise_dropped": 4}

When the master is a service (__modbus__ in a gate), the agent reads the count:

ycommand -c 'stats-yuno id=<id> service=__modbus__'   # "rx_noise_dropped": 4

(Up to 7.29.3: an exception was taken whatever its function, so over RTU a late one failed the write sent after it, a write that was done, and its echo was then dropped. The echo of a write answering a block counted as its answer. The bytes after an answer were dropped, half a frame included, which left the stream in the middle of one and lost the next answer. Also, a frame of another transaction id with an MBAP length of 65535 was “read whole”, swallowing every answer of the next timeout_response. Up to 7.29.2 the transaction id was written and never read, an RTU exception was taken before its CRC, and a bad CRC or an MBAP of length 3 logged an internal error, “answered WITHOUT reading its answer”.)

A consumer that relies on the answers refuses to build against an older module:

#include <c_prot_modbus_m.h>
#ifndef C_PROT_MODBUS_M_ANSWERS_REQUESTS
#error "C_PROT_MODBUS_M does not answer requests: needs the SDK after 7.29.2"
#endif

(Up to SDK 7.29.2 no request was answered and only writes existed: one holding register over TCP went out right. Function 05 sent the value as given instead of 0xFF00, several values went out without their quantity and byte count, RTU refused every write, and writes queued when the connection dropped were sent on the next one. Up to 7.27.7 a write was never taken out of the queue, and the polling did not resume after it.)

Commands

Commands: dump_data (current register snapshot), set-poll-timeout.

dump_data takes slave_id (an integer, -1 all slaves), address and size (-1 all data). address and size are DTP_JSON since SDK 7.27.0: a number or its text, as the register maps write them ("address": "4096"). They were DTP_STRING, which the command parser now holds to a string, so a number from a SPA is refused with that type. An address above 0xFFFF answers -1 “Address out of range”.

/*  the address as a register map writes it, the size as a number  */
json_t *resp = gobj_command(gobj_modbus, "dump_data",
    json_pack("{s:i, s:s, s:i}", "slave_id", 1, "address", "4096", "size", 16),
    gobj
);

Trace levels: messages (each published message, and the variables a cycle left out), traffic (raw bytes), polling, decode, send.

What the traffic trace shows of a write. The frame of a write (functions 05, 06, 15, 16, over TCP and RTU) is marked secret (gbuffer_set_secret()) before it goes to the transport, so the traffic trace of C_PROT_MODBUS_M and that of its C_TCP dump it as "<N bytes hidden>". The gclass also hides its own dumps of what it receives by the function of the frame: a write (05, 06, 15, 16) or the exception of one -- and anything while a write is in flight, as a broken frame can give a wrong function. So the late echo of a write, which comes while a read is in flight, is hidden too (up to 7.29.3 it was dumped with its value: the gclass looked only at what was in flight). Reads, and their answers, are dumped in full:

{"msg": "C_PROT_MODBUS_M^modbus ==> C_TCP^modbus", "len": 12, "secret": true, "data": "<12 bytes hidden>"}
{"msg": "C_TCP^modbus", "len": 3, "secret": true, "data": "<3 bytes hidden>"}

Two limits, both outside this gclass: