惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Palo Alto Networks Blog
S
Security Affairs
T
Tor Project blog
T
Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
A
Arctic Wolf
K
Kaspersky official blog
O
OpenAI News
Spread Privacy
Spread Privacy
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
Simon Willison's Weblog
Simon Willison's Weblog
雷峰网
雷峰网
P
Privacy & Cybersecurity Law Blog
Know Your Adversary
Know Your Adversary
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
Martin Fowler
Martin Fowler
量子位
博客园_首页
Cyberwarzone
Cyberwarzone
博客园 - 三生石上(FineUI控件)
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
IT之家
IT之家
N
News and Events Feed by Topic
博客园 - 司徒正美
V2EX - 技术
V2EX - 技术
S
Schneier on Security
博客园 - 叶小钗
Attack and Defense Labs
Attack and Defense Labs
AI
AI
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 【当耐特】
Jina AI
Jina AI
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
D
Darknet – Hacking Tools, Hacker News & Cyber Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
Cloudbric
Cloudbric
H
Hacker News: Front Page
The Last Watchdog
The Last Watchdog
V
V2EX
S
SegmentFault 最新的问题
V
Visual Studio Blog
PCI Perspectives
PCI Perspectives
Microsoft Security Blog
Microsoft Security Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build Your Own Modbus-TCP Cache Proxy in Python: One Inverter, Many Home Assistant Clients
Michael Bernhart · 2026-06-24 · via DEV Community

The Huawei SUN2000 SDongle has an annoying trait you only trip over once you want to connect more than one device: it accepts exactly one concurrent Modbus-TCP connection. The moment Home Assistant polls it, the AC·THOR stops getting answers; let evcc squeeze in and one of the two gets dropped. In my setup three clients wanted to read the same registers at once — and the dongle let exactly one through.

The usual advice is: use the ha-modbusproxy add-on. It works. But I wanted to understand what happens underneath, and I didn't want a black-box container for something that, at its core, is surprisingly small. So I wrote the proxy myself: roughly 300 lines of asyncio Python that poll the SDongle once every 10 seconds into an in-memory register cache and serve FC3 reads to any number of parallel clients. This post is the developer deep-dive to my concept post on caching Modbus proxies — that one is about the why, this one is about the how, down to the byte level.

The problem: one upstream, many clients

Modbus-TCP is a simple request-response protocol, but the SDongle is designed as a slave with exactly one master. Multiple masters at once aren't part of the standard, and Huawei enforces that hard. The solution is a proxy that behaves toward the dongle like the one permitted master, and toward every other device like a Modbus slave itself. The second half is the key: it answers client reads not by forwarding to the dongle, but from a cache. That way the dongle only ever sees one calm, periodic poller, no matter how many clients hang off the back.

The configuration: the only thing you change

I parameterize the whole proxy through a handful of constants at the top of the file. In the normal case you only change your SDongle's IP and maybe the listen port. Everything else fits a standard Huawei installation.

# === Configuration ===
SDONGLE_HOST = "192.0.2.10"   # <- deine Huawei SDongle IP (RFC 5737 Beispiel)
SDONGLE_PORT = 502
DEVICE_ID = 1

SERVER_HOST = "0.0.0.0"        # auf allen Interfaces lauschen
SERVER_PORT = 5502
POLL_INTERVAL = 10            # Sekunden

The proxy listens on port 5502 instead of 502 so it can run alongside the actual dongle and needs no root for a privileged port. In Home Assistant, AC·THOR and evcc you then simply enter the proxy host's IP and port 5502 — none of the clients notice they aren't talking to the dongle directly.

Register batching: fewer roundtrips to the dongle

The SDongle is slow, and every single read costs a full TCP roundtrip. Instead of querying each register individually, I read contiguous blocks in one go. Modbus allows up to 125 registers per FC3 read; I group the registers I need into a few batches along the natural gaps in the Huawei map.

REGISTER_BATCHES = [
    (32016, 4),   # PV string 1/2 voltage + current
    (32064, 2),   # Input power (int32)
    (32080, 2),   # Active power (int32)
    (32106, 2),   # Cumulative energy yield (uint32)
    (32114, 2),   # Daily energy yield (uint32)
    (37760, 1),   # Battery SOC
    (37765, 2),   # Battery power (int32)
    (37780, 8),   # Battery total charge/discharge + daily
]

Each entry is a (start_address, count) tuple. These eight batches cover everything my clients need — PV string values, power, yield and the full battery block. Per poll cycle that's eight small reads instead of dozens of individual queries, and the entire cycle finishes in well under a second.

Reading one FC3 batch: packing and unpacking the MBAP frame

This is where it gets interesting. A Modbus-TCP frame is the 7-byte MBAP header (transaction ID, protocol ID, length, unit ID) plus the PDU (function code + payload). With struct.pack I build the request frame, write it to the dongle, and unpack the response again. The format string ">HHHBBHH" encodes exactly that structure: three big-endian uint16 for the MBAP head, then unit, function code and the two uint16 for start address and count.

async def read_batch(reader, writer, start, count):
    req = struct.pack(">HHHBBHH", 0, 0, 6, DEVICE_ID, 3, start, count)
    writer.write(req)
    await writer.drain()
    resp = await asyncio.wait_for(reader.read(9 + count * 2), timeout=3)
    resp_tx, resp_proto, resp_len, resp_unit, resp_fc, byte_count = struct.unpack(
        ">HHHBBB", resp[:9])
    if resp_fc >= 0x80:  # Exception
        return None
    data = resp[9:]
    if len(data) >= count * 2:
        return struct.unpack(">" + "H" * count, data[:count * 2])

Two details matter. The asyncio.wait_for(..., timeout=3) stops a hung dongle from blocking the whole poller — if the answer never comes, the read times out and the cycle drops into backoff. And the resp_fc >= 0x80 check catches Modbus exceptions: if the dongle sets the top bit of the function code, it's not a data response but an error, so I return None instead of unpacking garbage. The int32/uint32 values from the batches get reassembled later by the caller from two consecutive uint16 registers each.

Serving the cache to every client

The second half of the proxy is the server side. When a client connects and sends an FC3 read, I answer it not from the dongle but from the in-memory cache. I read the requested start address and count from the client PDU, pull the values out of the cache dictionary under an asyncio.Lock, and build a valid Modbus response with a correct MBAP header back.

if fc == 3 and len(pdu) >= 5:
    reg_addr, reg_count = struct.unpack(">HH", pdu[1:5])
    values = []
    async with cache_lock:
        for i in range(reg_count):
            values.append(register_cache.get(reg_addr + i, 0))
    byte_count = reg_count * 2
    resp_pdu = struct.pack(">BB", fc, byte_count)
    resp_pdu += struct.pack(">" + "H" * reg_count, *values)
    resp_header = struct.pack(">HHHB", tx_id, 0, len(resp_pdu) + 1, unit_id)
    client_writer.write(resp_header + resp_pdu)

The cache_lock is not optional: the reader loop writes the cache while several client handlers read it at the same time — without the lock you could serve a half-updated register row. It's also important that I mirror the client's tx_id (transaction ID) in the response; a correct Modbus master matches responses precisely on that field, and a wrong value makes some clients discard the answer. Missing registers I answer with 0 rather than an error — that keeps picky clients happy.

The reader loop: poll, backoff, stale warning

Holding it all together is a single long-running task that polls the dongle in a loop. As long as everything is fine it runs at the normal 10-second cadence. If a poll fails, it goes into a shorter retry, and if the cache gets too old, it writes a warning to the log.

async def reader_loop():
    retry_delay = 5
    while True:
        success = await read_sdongle()
        if success:
            last_update = time.time()
            retry_delay = POLL_INTERVAL
        else:
            retry_delay = min(retry_delay, 10)
            age = time.time() - last_update if last_update > 0 else -1
            if age > 120:
                logger.warning(f"Cache stale for {age:.0f}s")
        await asyncio.sleep(retry_delay)

The stale warning after 120 seconds is my early-warning system: when it shows up in the log I know the dongle has stopped answering before the clients even start showing weird values. I deliberately kept the cache holding the last valid values on failure rather than dropping to zero — otherwise every dongle hiccup would push a PV power of 0 W to all clients and trigger false alarms and broken statistics in Home Assistant.

Wiring it into Home Assistant and checking it

On the HA side almost nothing changes versus a direct connection — you just point the Modbus hub at the proxy instead of the dongle. I now run three clients against the same upstream, and on the PV dashboard I see sensor.my_pv_pv_leistung, sensor.my_pv_batteriestand and sensor.pv_gesamt_ertrag updating live — all sourced through the proxy at the same time, without the clients stealing the connection from each other. How I turn these raw values into self-consumption and autarky is in the post on self-consumption and autarky sensors.

Frequently asked questions

Why not just use the ha-modbusproxy add-on?

You can, and for most people it's the right call. But I wanted to understand what happens under the hood and have full control over batching, cache behaviour and logging. If you're happy for an add-on to stay a black box, use the add-on; if you want to understand or extend the mechanism (e.g. your own computed registers, different poll intervals per batch), the home-built proxy is exactly right.

Doesn't the cache serve stale values?

At most as old as your poll interval — 10 seconds here. For PV power, battery SOC and yield that's perfectly fine; these values don't change meaningfully second by second. If you need it faster, lower POLL_INTERVAL, but keep in mind the SDongle gets cranky under overly aggressive polling. Ten seconds is the stable sweet spot for me.

Does the proxy support writes (FC6/FC16)?

Not this version — it's deliberately read-only and only handles FC3. That covers the sensor connection this post is about. Writes (say, a battery charge-mode control) you'd have to add, and then the 1-connection limit bites even harder: writes must not overlap. For pure data sharing across multiple clients, read-only is the safe and sufficient path.

What happens if the SDongle drops out briefly?

The reader loop goes into retry backoff and the cache holds the last valid values instead of falling to zero — so clients see no crash, just frozen values. After 120 seconds without an update the proxy writes a stale warning to the log. When the dongle comes back, the next successful poll refills the cache and the normal 10-second cadence resumes automatically.