Skip to content

Testing and interop

Test against something that is not live equipment first. OT Fabric gives you three ways to do that for Modbus, from a quick replay of a real device to a cross-implementation interop suite.

Tool What it simulates Best for
modbus-simulator One or more devices described in a JSON fixture, with deterministic exceptions, injected faults and a request trace, over TCP or TLS Integration tests and CI assertions for a gateway or client
modbusctl server static / replay A real device, from an MBCAP recording or a packet trace of its traffic Developing against realistic data without hardware
modbus-interop Nine independent Modbus stacks in Docker, over TCP, UDP and RTU over TCP Proving a library interoperates

modbus-simulator is a deterministic, stateful Modbus TCP device simulator, plain or over TLS. You describe the devices in a JSON fixture, it serves them on one listener (routed by unit ID 1-247), writes are kept in memory, and every request can be recorded to a JSON Lines trace that you assert on in CI. This section follows v1.4.0, built on go-modbus v1.11.0. v1.2.0 was hardened with chaos, stress and fuzz test suites and fixed what they found.

Pre-built binaries for Linux, macOS and Windows are on the releases page. With Go 1.26 or later:

Terminal window
go install github.com/otfabric/modbus-simulator@latest

From a checkout, make build runs the full checks and writes bin/modbus-simulator; go build -o bin/modbus-simulator . builds without them.

  1. Write a fixture. Points are raw 16-bit values or go-modbus codec fields with typed values:

    device.json
    {
    "$schema": "https://otfabric.dev/schemas/modbus-simulator/fixture-v1.json",
    "schemaVersion": "modbus-simulator.fixture.v1",
    "name": "gateway-integration-test",
    "defaults": { "unknownAddress": "exception", "stateMode": "persistent" },
    "devices": [
    {
    "unitId": 1,
    "name": "inverter-a",
    "identity": {
    "vendorName": "OTFabric",
    "productCode": "GWTEST",
    "majorMinorRevision": "1.0.0"
    },
    "state": {
    "coils": [ { "address": 0, "value": true, "writable": true } ],
    "holdingRegisters": [
    { "address": 0, "value": 2301, "writable": false },
    { "address": 1, "value": 501, "writable": true },
    { "address": 10, "codec": "float32/layout:4321", "value": 230.5, "writable": true, "name": "voltage" }
    ],
    "inputRegisters": [ { "address": 0, "value": 1234 } ]
    },
    "behavior": {
    "exceptions": [
    {
    "id": "hr-999-illegal",
    "match": { "fc": 3, "area": "holdingRegisters", "address": 999 },
    "exceptionCode": "illegal_data_address"
    }
    ]
    }
    }
    ]
    }
  2. Validate it against the embedded schema and the semantic rules (exit 0, or 3 on failure):

    Terminal window
    modbus-simulator validate device.json
  3. Serve it and record a trace. The default listen address is :5020:

    Terminal window
    modbus-simulator run --fixture device.json --listen :1502 --trace trace.jsonl
  4. Point your client at tcp://127.0.0.1:1502, unit 1. Stop the simulator with Ctrl-C when the test traffic is done.

Fixture behaviour worth knowing:

  • unknownAddress: exception (the default) answers any address not in the fixture with Illegal Data Address. zeroForReads returns 0 for unknown reads. Writes to unknown addresses always fail, so a mis-mapped gateway write cannot silently grow the map.
  • stateMode: persistent (the default) keeps one state, shared by all clients, for the life of the process. With resetOnConnection every connection works on its own copy of the fixture values, discarded when it disconnects, so clients never see each other’s writes. Per-device behavior overrides the top-level defaults.
  • Exception rules match on fc, area, address or addressRange, and quantity, and are evaluated before normal handling, so a test can force an exception on a valid address.
  • A request for a unit ID that is not in the fixture is answered with Illegal Function.
  • Codec IDs come from go-modbus. modbus-simulator codecs list prints them; the repository ships fixtures that cover every codec.

Fault rules in a device’s behavior.faults change how a matching request is answered, on the wire as their names say:

fault On the wire In the trace
delay The normal response, after delayMs ok: true
timeout No response; the connection stays open, so the client runs into its own timeout ok: false, fault: "timeout"
connectionClose The connection is closed without a response ok: false, fault: "connectionClose"
{ "id": "hr-100-timeout", "match": { "fc": 3, "address": 100 }, "fault": "timeout" }

Before v1.2.0, timeout and connectionClose were answered with a Server Device Failure exception, which never exercised a client’s timeout or reconnect handling.

With "broadcast": true at the top level of a fixture, unit 0 is the broadcast address, as on a serial line behind a gateway: a write (FC05, FC06, FC15, FC16, FC22) is carried out by every device that can take it and no response is sent, and any other request to unit 0 is ignored. Without it, unit 0 is an unknown unit.

--tls-cert, --tls-key and --tls-client-ca together serve Modbus/TCP Security instead of plain TCP. All three are required, so clients must present a certificate that chains to the client CA. The trace records "transport": "tcp+tls".

Terminal window
modbus-simulator run --fixture device.json --listen :8020 \
--tls-cert server.pem --tls-key server.key --tls-client-ca ca.pem

--control 127.0.0.1:5021 serves a small HTTP API, so a test suite can start the simulator once and reset it between cases:

Request Effect
POST /reset Restore every unit to the fixture values, for all clients
POST /reset?unit=N Restore one unit (404 when it is not in the fixture)
POST /reload Read the fixture file again and serve it from then on. An invalid fixture is refused with 422 and the simulator carries on unchanged
GET /healthz 200 while the simulator runs

The control API has no authentication: bind it to a loopback address. Resets and reloads are not written to the trace.

An expectation file lists assertions over the trace. Kinds are contains, notContains, count (with equals, atLeast or atMost), ordered and exact. Matching is by subset: only the fields you name are compared.

expected.json
{
"schemaVersion": "modbus-simulator.expect.v1",
"assertions": [
{ "kind": "contains", "match": { "request": { "fc": 43 } } },
{ "kind": "notContains", "match": { "request": { "address": 999 } } },
{
"kind": "ordered",
"sequence": [
{
"request": { "fc": 6, "address": 1, "value": 777 },
"response": { "ok": true },
"stateChange": { "area": "holdingRegisters", "address": 1, "after": 777 }
},
{
"request": { "fc": 3, "address": 1, "quantity": 1 },
"response": { "ok": true, "values": [777] }
}
]
}
]
}
Terminal window
modbus-simulator assert-trace trace.jsonl --expect expected.json

The trace is written in seq order, which is the order in which requests took effect, also with concurrent clients, so ordered and exact assertions see the real history. Each record is flushed as it is written: you can read the trace while run is still serving, and it survives an abrupt stop. --trace-decoded adds the typed values of codec fields a request fully covers, and --trace-raw adds the request and response PDUs as hex, encoded from the decoded request and the returned response rather than captured from the wire.

Other run flags: --listen (default :5020) and --max-clients (default 0, no limit; a client over the limit is disconnected). Exit codes: 0 success, 2 usage (an unknown --format included), 3 validation, 4 transport or server (also a trace record that could not be written), 8 assertion failure, 10 internal. Most flags have a MODBUS_SIMULATOR_* environment variable.

Supported Not supported
FC01, FC02, FC03, FC04, FC05, FC06, FC15, FC16, FC22, FC23, FC43/14 Other function codes, such as FIFO, file records and diagnostics
Modbus TCP, and TLS with client certificates RTU or serial server
Codec fields on registers Codec fields on coils and discrete inputs

FC22 sets a register to (current AND andMask) OR (orMask AND NOT andMask). FC23 makes the write first and then the read, as one step; when either is not allowed, nothing is written.

Besides a TCP integration test for each of its 21 example fixtures, modbus-simulator has a stress suite (parallel clients that check every answer against a model of their own registers while contending for a shared block, connection churn, the client limit, shutdown with requests in flight), a chaos suite (misbehaving raw TCP clients sending garbage, truncated and oversized frames, slow loris, pipelining and abandoned connections next to well-behaved ones, which must not notice) and fuzz targets for fixtures, expectation files and request sequences. After each run the trace must be valid, numbered without gaps and replay as a sequential history of the fixture. make soak and make fuzz run them for longer; a failing run logs a seed that MODBUS_SIMULATOR_TEST_SEED replays.

When you have access to a device once, record it and keep the recording:

Terminal window
modbusctl client scan --ip 192.168.1.10 --algo smart --start 0 --end 5000 --output scan.mbcap
modbusctl server static --input scan.mbcap --listen 127.0.0.1 --port 1502

server static serves the captured values unchanged. server replay plays a client record capture over time, at its original pace or faster or slower (--speed, --loops, --from). Both serve every read function the capture holds, refuse writes, and serve plain Modbus TCP or Modbus/TCP Security with client certificates. Without --listen they listen on all interfaces, so keep them on a trusted network. Captures can contain device identification and process values: handle them as operational data.

No access to the device, but a packet trace of its traffic? mbtracectl export mbcap or Modbus Trace Explorer turn the trace into a capture of what the device really answered. Captures and traces covers both paths and what a replay can and cannot reproduce.

modbus-interop packages nine independent Modbus implementations as container images with the same command interface. Its current release is v0.4.1 (container contract 1.2). It contains no library under test: a library pulls the images and owns its own scenarios and assertions.

Adapter Implementation Version Language Transports
libmodbus libmodbus v3.2.0 C TCP
pymodbus PyModbus 3.16.1 Python TCP
digitalpetri digitalpetri/modbus 2.1.6 Java TCP
nmodbus NModbus 3.0.83 C# TCP
tokiomodbus tokio-modbus 0.17.0 Rust TCP
j2mod j2mod 3.4.0 Java TCP, UDP, RTU over TCP
jsmodbus jsmodbus 5.0.0 JavaScript TCP, RTU over TCP
modbusesp modbus-esp8266 4.1.1 C++, compiled for Linux TCP, RTU over TCP
modbus4j modbus4j 3.1.0 Java TCP, UDP, RTU over TCP

v0.4.0 added the last four, --transport (tcp, udp, rtu-over-tcp) on server and client, and five features that gate behaviour some stacks get wrong (an unknown function code, a refused write that must change nothing, the highest address, the largest register writes). v0.4.1 stopped declaring file records for the j2mod server. modbus4j is GPL-3.0-or-later, so its image is not published: make image-modbus4j builds it from the pinned source archive, and the self-tests include it wherever it is built.

Each image (ghcr.io/otfabric/modbus-interop-<adapter>) offers server, client <operation>, print-capabilities and print-fixture. Expected values come from the image’s own fixture, and a test skips (does not fail) a scenario that needs a feature the image declares false.

Terminal window
# Needs Docker and jq
make images # build the adapter images
make smoke # container contract of each image
make interop # every reference client against every reference server
make run-libmodbus # a reference server on 127.0.0.1:1502

The stacks differ. Not every one has FC22 or FC43, and they differ in what they check:

libmodbus PyModbus digitalpetri NModbus tokio-modbus j2mod jsmodbus modbus-esp8266 modbus4j
Server FC22 yes yes yes no yes yes no yes no
Server FC43/14 no yes no no yes no yes no no
Client FC43/14 no yes no yes yes yes yes no no
Server quantity check yes no yes yes yes yes no yes no
Server answers an unknown function yes yes yes yes yes no no yes no
Refused write changes nothing yes yes yes yes yes yes yes yes no

The reference servers are unauthenticated and accept writes from anyone. They publish on loopback only and must never be attached to a plant network.

A self-test run with REPORT_DIR set also writes reports/results.json in the organisation’s interop-result-v1 format, with a stable ID per scenario and the digest of every image.

ghcr.io/otfabric/modbus-interop-otfabric is go-modbus behind the same container contract as the reference images (adapter name otfabric), so you can test your client against it, the way OT Fabric tests its own stack against yours:

Terminal window
docker run -d --name go-modbus -p 127.0.0.1:1502:1502 ghcr.io/otfabric/modbus-interop-otfabric:<tag> server
until docker exec go-modbus test -f /run/modbus-interop/ready; do sleep 0.1; done

It serves the same fixture as the reference servers, so anything that uses a modbus-interop-<adapter> image can use this one in its place, and its client commands drive your server the same way.

Its tags are go-modbus versions, such as v1.10.5, and latest; a rebuild of a version replaces its tag, so pin the digest when you need an exact build. It is not part of a modbus-interop release or its manifest.json, and it reports independentEngine: false: a result against it tells you about your stack, not something independent about OT Fabric’s. A result you publish, naming your implementation and version, is independent evidence. Like the references, it is for testing only and has no place on a network you do not control.

go-modbus runs its interop suite on every push (make interop in the go-modbus repository, about five minutes, Docker required). Since v1.13.4 it pins modbus-interop v0.4.1 by digest and runs against all nine stacks; the library itself is unchanged from v1.13.3. modbus4j runs when a local build is named, not in CI.

Reference go-modbus client to reference server Reference client to go-modbus server
libmodbus v3.2.0 pass without FC43 pass without FC43
PyModbus 3.16.1 pass pass
digitalpetri/modbus 2.1.6 pass without FC43 pass FC43 via raw PDU only
NModbus 3.0.83 pass without FC43 and FC22 pass without FC22
tokio-modbus 0.17.0 pass pass
j2mod 3.4.0 pass without FC08, FC17, FC20, FC21, FC43 pass without raw PDUs
jsmodbus 5.0.0 pass without FC08, FC17, FC20 to FC24 pass without FC08, FC17, FC20 to FC24, raw PDUs
modbus-esp8266 4.1.1 pass without FC08, FC17, FC20, FC21, FC24, FC43 pass without FC17
modbus4j 3.1.0, local build pass without FC08, FC20 to FC24, FC43 pass without FC08, FC20, FC21, FC23, FC24, FC43, raw PDUs

The client also runs over the other transports (TestClientTransports): every table read in full, exceptions, and every write read back. It passes against j2mod and modbus4j over UDP and RTU over TCP, and against jsmodbus and modbus-esp8266 over RTU over TCP.

The four newer stacks also skip the behaviour their images declare they lack, such as exception 1 for an unknown function, the reads that end at address 65535 on modbus-esp8266, or FC16 above 120 registers on jsmodbus. go-modbus’s INTEROPERABILITY.md lists them per stack and direction.

The suite covers FC01 to FC06, FC08, FC15, FC16, FC17, FC20 to FC24 and FC43/14. FC08, FC17, FC20, FC21 and FC24 are tested against the references that have them (PyModbus has all five) and through raw PDUs from every reference client that can receive the answer. As a client, go-modbus reads every table at block boundaries and with the largest request of each function, reads writes back on a second connection, checks exceptions 1, 2 and 11, sends two thousand requests on one connection, and runs sixteen connections at once plus a pooled client. As a server, it answers up to 120 operations per reference client, including raw PDUs and exceptions 1, 2, 3 and 11, and each result must match what the client gets from a reference server.

To pin other builds, set MODBUS_INTEROP_<ADAPTER>_IMAGE; to run a subset, set MODBUS_INTEROP_ADAPTERS=libmodbus,pymodbus.

The suite also found a bug in go-modbus, fixed in v1.3.0: the server closed the connection on an FC15, FC16 or FC23 request whose byte count did not match its quantity, where the specification asks for exception 3. The newer stacks brought findings of their own: the j2mod server answers the second of two FC20 sub-requests with the wrong records, so modbus-interop v0.4.1 no longer declares file records for it, and the modbus4j server writes the in-range part of an FC15 or FC16 it then refuses. The findings about the reference stacks themselves are in COMPATIBILITY.md.

  • modbusctl’s tests use an in-memory Modbus device (internal/mbtest) served over TCP, UDP, RTU and ASCII over TCP, and RTU and ASCII on a pseudo-terminal that stands in for a serial port (Linux and macOS).
  • go-serial’s TestReadWrite creates a PTY loopback on Linux, macOS and BSD. For manual testing, create a pair with socat -d -d pty,raw,echo=0 pty,raw,echo=0 and set SERIAL_LOOPBACK_PTY1 and SERIAL_LOOPBACK_PTY2.