Skip to content

Modbus TCP and RTU over TCP (modbus package) - #36

Open
y001j wants to merge 2 commits into
masterfrom
feat/modbus
Open

y001j wants to merge 2 commits into
masterfrom
feat/modbus

Conversation

@y001j

@y001j y001j commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Branched from feat/mqtt5 (#35) to avoid README/CHANGELOG conflicts. Until #35 is merged this PR also shows its commit; review the last commit only. After #35 merges the diff reduces to Modbus.

A Modbus master and slave for IoT gateways polling many field devices.

Protocol: Modbus TCP and RTU over TCP; functions 0x01–0x06, 0x0F, 0x10, 0x17; exceptions; spec quantity limits.

Client (master, outgoing): context-aware requests from any goroutine, Modbus TCP pipelining (MaxInflight, transaction-ID matching), timeouts, retries, reconnection with backoff (requests wait for the device).

DTUServer (master, incoming): for 4G/Ethernet DTUs and serial device servers in client mode — registration packet (IMEI etc.) with timeout, heartbeats discarded anywhere between frames, Authorize, OnOnline/OnOffline, Link(id), reconnect replaces the old connection.

Server (slave): Handler interface, Memory model with OnWrite, Units routing, RTU broadcast and bad-CRC handling.

RTU robustness: one request at a time; responses that don't fit the outstanding request (unit/function/length/echo) are dropped as late; Drain after timeouts; bad CRC / unframeable bytes resync the stream and surface as ErrCRC / ErrInvalidResponse.

Tests: portable codec/framing/slave tests; end-to-end with a scripted fake device (out-of-order pipelined responses, timeouts + retry, late RTU responses, bad CRC, garbage, device outage + reconnect, context cancel, Close) and fake DTUs (registration, heartbeats glued to and between split responses, replacement, registration timeout, authorization). Both backends, -race, 8 runs.

Interop: our client ↔ pymodbus server and pymodbus 3.16 client ↔ our server, both framings, all functions + exceptions; mbpoll/libmodbus ↔ our server. (pymodbus 3.7.4's sync client fails even against pymodbus's own server — a client bug, hence 3.16.) Smoke test of example/modbusdtu with a simulated DTU.

🤖 Generated with Claude Code

y001j and others added 2 commits November 23, 2026 02:23
MQTT 5 alongside 3.1.1 and 3.1. The protocol version is per connection
and only changes the encoding, so clients of different versions talk
to each other; a QoS 0 packet is encoded at most once per version.

- Properties: full codec with duplicate/zero-value checks; message
  properties (payload format, content type, response topic, correlation
  data, user properties) travel with the message, reach OnPublish and
  are forwarded to MQTT 5 subscribers (dropped for 3.1.1).
- Reason codes on PUBACK/PUBREC/PUBCOMP (0x87 for unauthorized publishes,
  0x92 for unknown PUBREL), SUBACK, UNSUBACK (0x11 no subscription
  existed), CONNACK, and DISCONNECT before server-initiated closes:
  session taken over, keepalive timeout, malformed packet, protocol
  error, invalid topic alias, subscription identifiers.
- Session expiry (CONNECT and DISCONNECT, 0 cannot be raised on
  DISCONNECT), message expiry (queued, inflight and retained messages;
  forwarded with the remaining interval), topic aliases from clients,
  receive maximum (limits the inflight window), maximum packet size in
  both directions, assigned client IDs, subscription options No Local,
  Retain As Published and Retain Handling, will delay (cancelled by a
  reconnect, capped by the session end), DISCONNECT with will message.
- Not supported, refused with their reason codes: shared subscriptions
  (0x9E), subscription identifiers (0xA1), enhanced authentication
  (0x8C).

Session expiry for MQTT 3.1.1 too: Config.SessionExpiry removes sessions
offline for longer, with their subscriptions and queues (persistent
sessions never expired before), and caps what MQTT 5 clients ask for.

New API: Config.SessionExpiry, Config.TopicAliasMaximum,
Broker.PublishMessage, Message.Expiry, Message.Properties, Properties,
UserProperty, Stats.MessagesExpired, Stats.SessionsExpired.

The subscription trie carries per-subscription options and merges
overlapping subscriptions during the match; PUBLISH properties are only
allocated for MQTT 5 and outgoing PUBLISH buffers are sized up front,
so the 3.1.1 hot path makes the same allocations as before (A/B against
master: within noise in all three scenarios).

Tests: codec tests (portable), 9 MQTT 5 broker tests on both backends;
interop with mosquitto_pub/mosquitto_sub -V mqttv5 (properties, 3.1.1
<-> 5, session resume, retained, will delay, shared subscription
refused).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A Modbus master and slave on uringnet, aimed at IoT gateways polling
many field devices.

- Codec (platform-independent): functions 0x01-0x06, 0x0F, 0x10, 0x17
  and exception responses; MBAP framing; RTU framing without a length
  field (by function code and byte count, requests and responses
  differ) with CRC-16/MODBUS; quantity limits per the specification.
- Link: the master on one connection. Requests from any goroutine with a
  context; Modbus TCP pipelining (MaxInflight, matched by transaction
  ID); per-request timeout and retries; RTU sends one request at a time,
  drops responses that do not fit the outstanding request (unit,
  function, length, echoed write) and waits Drain after a timeout or a
  broadcast; bad CRCs and unframeable bytes resynchronize the stream and
  are reported as ErrCRC / ErrInvalidResponse; typed helpers; Stats.
- Client: dials Links in the background and reconnects with backoff;
  requests wait for the connection; outstanding requests are retried
  on the next connection (ErrConnLost when no retry is left).
- DTUServer: a master for devices that connect in (4G/Ethernet DTUs,
  serial device servers in client mode): registration packet parsing
  (RegisterFixed, RegisterFixedHex or a custom function) with a
  timeout, heartbeat packets discarded anywhere between frames,
  Authorize, OnOnline/OnOffline, lookup by ID, and a reconnecting DTU
  replacing its old connection (ErrReplaced).
- Server: a slave answering from a Handler; Memory data model with
  OnWrite; Units routing by unit ID; RTU broadcast and bad-CRC handling.
- example/modbusdtu; package examples; README (EN/ZH), architecture.

Reads use Peek/Discard rather than Framed, since framing depends on
per-connection state (registration, heartbeats, RTU resync).

Tests: codec, framing and slave logic (portable); client/server in both
framings, pipelining with out-of-order responses, timeout and retry,
late RTU responses, bad CRC and garbage, reconnection across a device
outage, context cancellation and Close, DTU registration, heartbeats,
replacement, registration timeout and authorization; both backends
under -race, 8 runs. Interop: our client against the pymodbus server
and the pymodbus 3.16 client against our server, in both framings, and
mbpoll (libmodbus) against our server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.45129% with 161 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.44%. Comparing base (f92576a) to head (77a2ede).

Files with missing lines Patch % Lines
modbus/handler.go 72.78% 43 Missing ⚠️
modbus/link.go 88.05% 35 Missing ⚠️
mqtt/broker.go 90.32% 30 Missing ⚠️
mqtt/packet.go 85.84% 15 Missing ⚠️
mqtt/props.go 86.04% 12 Missing ⚠️
modbus/dtu.go 89.41% 9 Missing ⚠️
modbus/client.go 91.30% 6 Missing ⚠️
modbus/pdu.go 94.87% 6 Missing ⚠️
modbus/server.go 89.74% 4 Missing ⚠️
mqtt/topic.go 95.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #36      +/-   ##
==========================================
+ Coverage   74.98%   78.44%   +3.45%     
==========================================
  Files          31       38       +7     
  Lines        3146     4277    +1131     
==========================================
+ Hits         2359     3355     +996     
- Misses        787      922     +135     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant