Skip to content

Modbus bridge

With CONFIG_PKZ_MODBUS_BRIDGE=y the device is also the adapter for the Modbus units on its own buses, as a PulzrOS gateway’s pulzr-edge is for the units on the gateway’s: adapter protocol v1, adapter id dev-<EUI> (the device’s EUI, lower case), the same topics, payloads and key format as pulzr-edge, with the device’s EUI where the gateway’s goes. Pulzr keeps the units’ readings; the device does not use them itself. Zephyr’s Modbus subsystem does the talking: an RTU client on a zephyr,modbus-serial node (the RS-485 driver-enable pin comes from that node’s de-gpios), and a Modbus TCP client through a raw ADU interface with the MBAP header on a socket.

  1. prj.conf:

    CONFIG_PKZ_MODBUS_BRIDGE=y
    CONFIG_SERIAL=y
    CONFIG_UART_INTERRUPT_DRIVEN=y
  2. Devicetree: an RTU bus is a zephyr,modbus-serial node, named in the configuration by its node name. The Opta’s board already has modbus0 on USART3 with DE and RE; enable the UART:

    &usart3 { status = "okay"; };
  3. Optionally, a default configuration until Pulzr sends one:

    static const struct pkz_config cfg = {
    .fw_version = "1.0.0",
    .modbus = "{\"buses\":[{\"id\":\"rs485-0\",\"serial\":\"modbus0\",\"baud\":9600,"
    "\"units\":[{\"id\":1,\"map\":{\"schema\":0,\"model\":\"meter\",\"fields\":["
    "{\"id\":\"power\",\"function\":4,\"address\":4,\"type\":\"f32\"}]}}]}]}",
    };

    pkz_modbus_config(json, len) replaces it from the application (its own web UI, say), as the command below does. Either way it is checked first, kept in the settings subsystem (pkz/mb/doc), and in force from the next poll. The application calls nothing else: pkz_init() starts the bridge’s thread, which polls once the device is enrolled and its clock is set.

  4. An RS-485 port the application already polls itself (its own sensors, modbus_init_client() on the same interface) is shared, not taken over: name it in modbus_shared and the bridge uses it as it is, with the application’s baud, framing and timeout, and never sets it up or disables it. Zephyr’s client takes the interface’s lock for each request, so the two never interleave on the wire; the bridge’s units sit at other addresses. Every other interface a bus names is the bridge’s own, set up by its thread.

    static const char *const modbus_shared[] = { "modbus0", NULL };
    static const struct pkz_config cfg = { ..., .modbus_shared = modbus_shared };

samples/modbus-bridge is all of this on the Opta (RTU on modbus0) and on native_sim (Modbus TCP to 127.0.0.1:1502).

One JSON document: pulzr-edge’s config.toml buses with each unit’s register map inline in place of the map file’s path. Every member and default is pulzr-edge’s; unknown members are refused.

{"buses": [
{"id": "rs485-0", "kind": "rtu", "serial": "modbus0", "baud": 9600,
"parity": "none", "stop_bits": 1, "timeout_ms": 1000, "retries": 2,
"backoff_ms": 200, "turnaround_ms": 0,
"units": [{"id": 17, "offline_after": 3,
"map": {"schema": 0, "model": "example-energy-meter",
"poll_interval": 10, "heartbeat": 300, "max_gap": 4,
"fields": [
{"id": "voltage", "function": 4, "address": 0, "type": "f32",
"deadband": 0.5, "poll_interval": 5},
{"id": "report_period", "function": 3, "address": 100,
"type": "u16", "writable": true, "min": 1, "max": 3600}]}}]},
{"id": "lan-0", "kind": "tcp", "address": "192.168.1.50:502", "units": [...]}]}
  • A bus: id (a-z 0-9 -, up to 32), kind rtu (default) with serial (the devicetree node’s name), baud, parity (none, even, odd), data_bits (8), stop_bits (1 or 2); or tcp with address (host:port). timeout_ms, retries, backoff_ms (doubles each retry), turnaround_ms (quiet time after each request).
  • A unit: id 1-247, offline_after failed polls in a row, map.
  • A map is pulzr-edge’s register map (schema/register-map.schema.json in pulzr-edge): u16, i16, u32, i32, f32, bool; word_order and byte_order; bit; scale and offset; deadband, poll_interval, heartbeat; writable, write_function, min, max. Neighbors within max_gap registers share a request.

From Pulzr it arrives as the built-in command modbus.config on the device’s own command topic (parkeze/device/<EUI>/cmd), the document as its params: ok, or refused/invalid with what is wrong in detail. It is a remote command, so the device’s remote switch covers it.

Kconfig Default
CONFIG_PKZ_MODBUS_TCP y Modbus TCP buses (one MODBUS_NUMOF_RAW_ADU interface each; 2 by default)
CONFIG_PKZ_MODBUS_BUSES_MAX 2 buses
CONFIG_PKZ_MODBUS_UNITS_MAX 8 units, all buses
CONFIG_PKZ_MODBUS_FIELDS_MAX 64 fields, all units (about 180 bytes each, twice)
CONFIG_PKZ_MODBUS_CONFIG_MAX 3072 the document’s bytes (also within PKZ_CMD_MAX_SIZE)
CONFIG_PKZ_MODBUS_CMD_MAX 512 a command to a unit
CONFIG_PKZ_MODBUS_CMD_QUEUE 4 commands to units waiting for the bus
CONFIG_PKZ_MODBUS_STACK_SIZE, _PRIORITY 4096, 8 the bridge’s thread

A unit’s key is modbus:<EUI>.<bus>.<unit>, e.g. modbus:a8610afffe330001.rs485-0.17; its topics are pulzr/a/dev-<EUI>/d/<key>/<kind>, JSON, QoS 1, not retained. Every message goes through the store, so nothing is lost while the network is away, and seq is the store’s, which survives reboots. One difference from pulzr-edge: up has no rx, whose gw:<EUI> hop would make Pulzr take the device for a gateway.

Kind When Body
state the unit starts answering, or misses offline_after polls {"v":1,"online":true,"last_heard":1793051880.0,"package":"<model>"}; offline without last_heard
state (the application’s own) declared, its answer changes, and every 10 minutes {"v":1,"host_polled":true,"name":"High probe","model":"SEN0438","online":true,"last_heard":1793051880.0}; no online until the application says how a read went. See below
up a field moved past its deadband, or its heartbeat is due {"v":1,"seq":4,"r":[{"ts":…,"v":{"power":1234.5}}],"link":{"modbus":{"function":4,"address":0,"count":4,"latency_ms":40}}}
settings after a write {"v":1,"values":{"report_period":60},"by":"<command id>"}
cmd/res answers to …/<key>/cmd queued, sent, delivered, then ok with data (what was written); or refused (invalid, unknown, local_only) or failed (expired, undeliverable, error) with detail

Commands, on pulzr/a/dev-<EUI>/d/<key>/cmd as pulzr-edge takes them: settings.set with {field: value, …}, and register.write with {"field": id, "value": v} or {"address": a, "function": 3, "value": v}; only fields the map marks writable, every value checked before the first write. There is no discovery message: Pulzr learns of a unit from its first state or up, as from pulzr-edge, and lists it under the device until someone adds it. pkz status lists the units and whether each answers.

Units the application polls itself, and whose readings it reports as its own fields (a controller’s probes), still belong on the device’s Bus Devices in Pulzr. Declare them, and say how each read went:

static const struct pkz_modbus_own probes[] = {
{ .iface = "modbus0", .unit = 6, .name = "High probe", .model = "SEN0438" },
{ .iface = "modbus0", .unit = 1, .name = "Low probe", .model = "SEN0438" },
};
pkz_modbus_own(probes, ARRAY_SIZE(probes)); /* copied; call again when one moves */
...
pkz_modbus_heard("modbus0", 6, err == 0); /* after each read, any thread */

Each goes as state with "host_polled":true on modbus:<EUI>.<bus>.<unit> (<bus> as a scan’s: the configured RTU bus on that interface, else its name): when declared, when it starts or stops answering (offline after 3 unanswered reads in a row), and every 10 minutes. Pulzr lists it on the device’s Bus Devices as the device’s own, with its name, address, bus and whether it answers; never under Found, never to add, and it keeps no readings for it. One the device stops declaring drops off the list within an hour. The bridge sends no up for them, and a scan does not report them. CONFIG_PKZ_MODBUS_OWN_MAX (8) caps the list, about 100 bytes each.

pkz_modbus_scan() asks every address in a range (1–247) of an RTU interface that is already set up, the application’s (named in modbus_shared) or one the configuration polls, for two registers with function 3 or 4. It goes a few addresses at a time (CONFIG_PKZ_MODBUS_SCAN_STEP) in the bridge’s thread between its polls, and needs no lock of its own: Zephyr’s client lock keeps the application, the bridge and the scan apart on the wire, so the application’s own polling goes on. pkz_modbus_scan_status() has its progress and what answered; progress in the request is called for each address.

Answer err
Read 0 regs hold the two registers
Exception > 0, the Modbus code a unit is there and refused that read
Garbled -EIO a reply with a bad CRC, too short or long, with a wrong byte count, or another unit’s frame: two units on one address, noise, or A and B swapped; the scan goes on
Silent (counted in timeouts)

pkz_modbus_probe() is the same read of one address, from the caller’s thread. pkz modbus scan <iface> [first] [last] runs one from the shell and prints each answer as it comes.

A unit that answers (read or exception) and that no bus of the configuration polls, and that the application has not declared as its own, is reported once as state, {"v":1,"online":true,"last_heard":…, "diag":{"scan":{"function":3,"address":0,"regs":[662,214]}}} (or "exception":2), on modbus:<EUI>.<bus>.<unit>: the configured RTU bus on that interface, else the interface’s own name (modbus0). Pulzr lists it under Found like any unit it has not been told about; to poll it, add it there and give modbus.config a bus with that id.