« All posts

Building a Modbus Proxy That Never Silently Serves Stale Data

A deep dive into hardening a self-built Modbus caching proxy for Huawei SDongle inverters against night-time disconnects, hanging reads and silent stale data.

A developer's self-built Modbus caching proxy for a Huawei SUN2000 inverter's SDongle ran flawlessly for weeks until the inverter went to sleep at night, causing an async read to hang indefinitely — with the proxy silently serving stale daytime values for hours. The real danger isn't a crash, the piece argues, but a proxy that keeps running while quietly lying about the data's freshness.

The fix rests on three pillars: every read gets a hard asyncio timeout plus a mandatory 50ms spacing the SDongle requires; a plain TimeoutError is treated as survivable while any other exception breaks out of the batch loop since the connection is likely dead; and once the cache exceeds 120 seconds old, an explicit warning is logged so Home Assistant can surface it. On the client side, a 60-second idle timeout on the 7-byte MBAP header reaps dead connections before they leak resources.

The specific thresholds — 50ms spacing, 10s polling, a 120s staleness limit, and a 60s client timeout — were tuned over months of real-world operation, though the author notes they apply conceptually to any caching proxy, whether self-built or an off-the-shelf add-on like ha-modbusproxy. The post also covers debugging a frozen cache and wiring up Home Assistant automations to alert on staleness.