Skip to content

EMS Modbus TCP Server Test (Read/Write)

Introduction

ems_modbus_client_rw.py is a lightweight Modbus TCP client for quick read/write, decoding, probing unknown windows, and validating addresses against your EMS register map.
It works with pymodbus v2 & v3 and supports FLOAT32 / INT32U / BITMAP32 / UINT16.


Quick Start

# 1) Install dependency
pip install pymodbus

# 2) Read 2 words at address 24674
python3 ems_modbus_client_rw.py --read 24674 2

# 3) Read + decode as FLOAT32 with big-endian word order
python3 ems_modbus_client_rw.py --read 24674 2 --dtype FLOAT32 --endian big

# 4) Write a FLOAT32 value (56.24) to address 24674
python3 ems_modbus_client_rw.py --write 24674 56.24 FLOAT32 --endian big

# 5) Probe a window (scan readable regs in a range)
python3 ems_modbus_client_rw.py --probe 24660 40

# 6) Validate an address against your JSON map
python3 ems_modbus_client_rw.py --read 24674 2 \
  --registers emsConfig/ems_register_full.json --device-key ffrMeter

CLI Usage

python3 ems_modbus_client_rw.py [OPTIONS]

Network: --host HOST Default: 127.0.0.1 --port PORT Default: 1510 --unit UNIT_ID Default: 1

Endianness: --endian {big,little} Word order for 32-bit (default: big)

Operations (choose one): --read ADDR COUNT --write ADDR VALUE DTYPE --probe START COUNT

Decoding / Validation: --dtype DTYPE Decode read as e.g. FLOAT32, INT32U, BITMAP32, UINT16 --registers PATH Path to ems_register_full.json --device-key KEY Device key filter for validation (e.g. ffrMeter, pcs)

Other: --debug Verbose debugging (prints more context)

Notes

--dtype affects decoding of read values only. For writes, the dtype is in the --write triple.

For pymodbus v2, the client uses unit=; for pymodbus v3, it uses slave= automatically (no change needed from you).

Flow (What the script does)


flowchart TD
  A([Start]) --> B[Parse CLI arguments]
  B --> C{Connect to Modbus TCP}
  C -- No --> X([Exit: connection error])
  C -- Yes --> D{Mode?}

  D -- Probe --> E[Read pairs in window] --> F[Print hits]
  D -- Read --> G[Validate from JSON (if provided)] --> H[Send read]
  H --> I{OK?}
  I -- No --> X([Exit: read failed])
  I -- Yes --> J[Decode (--dtype) & print]

  D -- Write --> K[Pack by DTYPE & endianness] --> L[Send write]
  L --> M{OK?}
  M -- No --> X([Exit: write failed])
  M -- Yes --> N[Confirm & print]

  F --> Z([Close connection & exit])
  J --> Z
  N --> Z

Data Types & Endianness

UINT16 (default): one 16‑bit register.

FLOAT32 / INT32U / BITMAP32 / INT32: two 16‑bit registers.

Endianness (--endian) controls 32‑bit word order:

big: [hi, lo] (most common in many device maps)

little: [lo, hi]

Examples

# Read two words and decode as FLOAT32 (big word order)
python3 ems_modbus_client_rw.py --read 3050 2 --dtype FLOAT32 --endian big

# Same registers if device uses little-endian words
python3 ems_modbus_client_rw.py --read 3050 2 --dtype FLOAT32 --endian little

Examples Cookbook

1) Raw read (no decode)

python3 ems_modbus_client_rw.py --host 127.0.0.1 --port 1510 --unit 1 --read 24674 2
# -> [OK] Read @24674 count=2 -> raw [16992, 62915]
2) Read & decode as FLOAT32
python3 ems_modbus_client_rw.py --read 24674 2 --dtype FLOAT32 --endian big
# -> [OK] Decoded as FLOAT32 (big words): 56.24
3) Write FLOAT32

python3 ems_modbus_client_rw.py --write 24674 56.24 FLOAT32 --endian big
# -> [OK] Wrote 56.24 (FLOAT32) -> @24674, words=[16992, 62915]
4) Write UINT16 (single word)

python3 ems_modbus_client_rw.py --write 3200 1234 UINT16
5) Probe around an address
# Helps when you see "illegal address"
python3 ems_modbus_client_rw.py --probe 24660 40
6) Validate an address with your map (safety check)
python3 ems_modbus_client_rw.py --read 6020 1 \
  --registers emsConfig/ems_register_full.json --device-key pcs
# Warns if address not present, suggests nearest known base

Dependencies

This script relies on the following:

Python Standard Library

argparse → parsing CLI arguments

json → loading EMS register maps

struct → packing/unpacking binary register values

sys, pathlib → system exit handling, file paths

Third-party

pymodbus

Client for Modbus TCP read/write

Compatible with both v2 (unit) and v3 (slave) APIs

Typical Workflows

A. You know the register & type

--read ADDR COUNT --dtype FLOAT32 --endian big

If value needs writing, --write ADDR VALUE FLOAT32 --endian big.

B. You’re exploring unknowns

--probe START COUNT

Spot active addresses → test with --read and try --dtype candidates.

C. You have a JSON register map

Add --registers emsConfig/ems_register_full.json --device-key pcs

The tool will warn on unknown addresses and name known ones during --probe.

Troubleshooting

“Cannot connect … Connection refused”

Is server listening on the host/port? Are IP/port/unit correct?

Firewalls or docker port mappings in the path?

Read/Write fails with “Modbus exception (function=?, code=?)”

Address may be invalid or not mapped for that unit id.

Device could reject writes to read-only registers.

Wrong COUNT (e.g., reading 2 when it’s a single 16‑bit reg).

Decoded value looks wrong

Swap endianness: try --endian little.

Check dtype: FLOAT32 vs INT32U makes a big difference.

pymodbus keyword error (unit vs slave)

The script auto-detects v2 vs v3 and uses the correct keyword internally.

If you still see issues, ensure only one pymodbus is installed and it’s up to date.

Best Practices

Keep a small “golden” register list (with dtype & endianness) for your devices.

Use --probe before writing to establish which addresses are alive.

Validate against your JSON to avoid writing to the wrong place.

For FLOAT32: always confirm correct word order with one known reference value.

Exit Messages (What they mean)

[OK] Read … / [OK] Wrote … — operation succeeded.

[ERR] Cannot connect … — TCP session wasn’t established.

[ERR] Read failed … — device rejected or didn’t answer.

[ERR] Write failed … — write not permitted / invalid / device error.

[PROBE] No readable addresses … — range likely illegal for that unit.

Reference: Options Recap

--host/--port/--unit        Target server & slave/unit ID
--endian big|little         Word order for 32-bit values
--read A C                  Read COUNT words @ADDR
--write A V T               Write VALUE of DTYPE @ADDR
--dtype T                   Decode reads (FLOAT32, INT32U, BITMAP32, UINT16)
--probe S C                 Scan window [START .. START+COUNT)
--registers PATH            JSON map for validation & names
--device-key KEY            Device key filter for map
--debug                     Extra verbosity

Python Code

ems_modbus_client_rw_v2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
EMS Modbus TCP Client (read/write, v3 safe) — with decode & probe

Examples:
  # raw read 2 regs @24674
  python3 ems_modbus_client_rw_v2.py --read 6390 2

  # read & decode as FLOAT32 (big word order)
  python3 ems_modbus_client_rw_v2.py --read 24674 2 --dtype FLOAT32 --endian big

  # write FLOAT32 56.24 @24674
  python3 ems_modbus_client_rw_v2.py --write 24674 56.24 FLOAT32 --endian big

  # probe 40 regs around 24660 (helps when you get illegal address)
  python3 ems_modbus_client_rw_v2.py --probe 24660 40

  # validate an address against your JSON map (optional)
  python3 ems_modbus_client_rw_v2.py --read 24674 2 --registers emsConfig/ems_register_full.json --device-key ffrMeter
"""
import argparse, json, struct, sys
from pathlib import Path
from pymodbus import __version__ as pymodbus_version
from pymodbus.client import ModbusTcpClient
from pymodbus.exceptions import ModbusIOException

PMB_V3 = pymodbus_version.startswith("3")


# ------------------- HELP / EXAMPLES FUNCTION -------------------
def show_examples():
    """Print detailed examples for usage and exit."""
    examples = """
EMS Modbus TCP Client (read/write, v3 safe) — with decode & probe

**** always use one address less than what you want to read , since count stats from zero, for example if you need to read 
address 1389----------------you need to give 1388  

Examples:
  # raw read 2 regs @24674
  python3 ems_modbus_client_rw_v2.py --read 6390 2

  # read & decode as FLOAT32 (big word order)
  python3 ems_modbus_client_rw_v2.py --read 24674 2 --dtype FLOAT32 --endian big

  # write FLOAT32 56.24 @24674
  python3 ems_modbus_client_rw_v2.py --write 24674 56.24 FLOAT32 --endian big

  # probe 40 regs around 24660 (helps when you get illegal address)
  python3 ems_modbus_client_rw_v2.py --probe 24660 40

  # validate an address against your JSON map (optional)
  python3 ems_modbus_client_rw_v2.py --read 24674 2 --registers emsConfig/ems_register_full.json --device-key ffrMeter
"""
    print(examples)
    sys.exit(0)
# ---------------------------------------------------------------


def _call_kwargs(unit_id: int):
    return {"slave": unit_id} if PMB_V3 else {"unit": unit_id}


def _u16(n: int) -> int:
    return n & 0xFFFF


def pack_value(dtype: str, value, be_words: bool = True):
    dt = (dtype or "").upper()
    if dt == "FLOAT32":
        b = struct.pack(">f", float(value)) if be_words else struct.pack("<f", float(value))
        hi, lo = struct.unpack(">HH", b)
        return [hi, lo] if be_words else [lo, hi]
    if dt in ("INT32U", "UINT32", "BITMAP32", "INT32"):
        v = int(float(value)) & 0xFFFFFFFF
        hi, lo = (v >> 16) & 0xFFFF, v & 0xFFFF
        return [hi, lo] if be_words else [lo, hi]
    return [_u16(int(float(value)))]


def decode_value(dtype: str, words: list[int], be_words: bool = True):
    dt = (dtype or "").upper()
    if dt == "FLOAT32" and len(words) >= 2:
        hi, lo = (words[0], words[1]) if be_words else (words[1], words[0])
        b = struct.pack(">HH", hi, lo)
        return struct.unpack(">f", b)[0]
    if dt in ("INT32U", "UINT32", "BITMAP32", "INT32") and len(words) >= 2:
        return ((words[0] << 16) | words[1]) if be_words else ((words[1] << 16) | words[0])
    # default 16-bit unsigned
    return words[0] if words else 0


def load_registry(path: Path, device_key: str):
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except Exception as e:
        print(f"[WARN] Failed to read registry {path}: {e}")
        return {}
    out = {}
    for k, v in (data.items() if isinstance(data, dict) else []):
        try:
            if str(v.get("device_key")) != device_key:
                continue
            addr = int(v.get("address"))
            out[addr] = {
                "name": v.get("register_name", f"reg_{addr}"),
                "dtype": str(v.get("data_type", "FLOAT32")).upper(),
                "regs": int(v.get("registers", 2)),
                "rw": str(v.get("rw_type", "read_only")),
            }
        except Exception:
            pass
    return out


def explain_exception(resp):
    if resp is None:
        return "No response (timeout/disconnected)"
    if hasattr(resp, "isError") and resp.isError():
        try:
            fn = getattr(resp, "function_code", "?")
            ec = getattr(resp, "exception_code", "?")
            return f"Modbus exception (function={fn}, code={ec})"
        except Exception:
            return "Modbus exception"
    return ""


def main():
    p = argparse.ArgumentParser(add_help=True)
    p.add_argument("--host", default="127.0.0.1")
    p.add_argument("--port", type=int, default=1520)
    p.add_argument("--unit", type=int, default=1)
    p.add_argument("--endian", choices=["big", "little"], default="big")
    p.add_argument("--read", nargs=2, metavar=("ADDR", "COUNT"))
    p.add_argument("--write", nargs=3, metavar=("ADDR", "VALUE", "DTYPE"))
    p.add_argument("--dtype", help="Decode dtype for --read (e.g. FLOAT32, INT32U, BITMAP32, UINT16)")
    p.add_argument("--probe", nargs=2, metavar=("START", "COUNT"), help="Scan a window and print non-error reads")
    p.add_argument("--registers", help="Path to ems_register_full.json to validate address")
    p.add_argument("--device-key", help="Device key to filter registry (e.g. ffrMeter, pcs, ems)")
    p.add_argument("--debug", action="store_true", help="Enable debug printout")
    p.add_argument("--examples", action="store_true", help="Show usage examples and exit")

    args = p.parse_args()

    # If --examples flag is passed
    if args.examples:
        show_examples()

    be_words = args.endian == "big"

    # Optional registry for validation
    reg_index = {}
    if args.registers and args.device_key:
        reg_index = load_registry(Path(args.registers), args.device_key)

    client = ModbusTcpClient(args.host, port=args.port)
    if not client.connect():
        print(f"[ERR] Cannot connect to {args.host}:{args.port}")
        sys.exit(2)

    if args.probe:
        start, cnt = int(args.probe[0]), int(args.probe[1])
        ok = 0
        for off in range(0, cnt, 2):
            addr = start + off
            try:
                rr = client.read_holding_registers(addr, 2, **_call_kwargs(args.unit))
            except ModbusIOException:
                rr = None
            if rr and (not rr.isError()):
                w = list(rr.registers)
                name = reg_index.get(addr, {}).get("name", "")
                print(f"[PROBE] @{addr:<6} -> {w}  {('(' + name + ')') if name else ''}")
                ok += 1
        if ok == 0:
            print("[PROBE] No readable addresses in window (likely illegal address range / wrong unit).")
        client.close()
        return

    if args.read:
        addr, count = int(args.read[0]), int(args.read[1])

        # Validate address if we have a registry
        if reg_index and addr not in reg_index:
            near = min(reg_index.keys(), key=lambda a: abs(a - addr)) if reg_index else None
            print(f"[WARN] Address {addr} not in registry for device_key={args.device_key}."
                  + (f" Nearest known base: {near} ({reg_index[near]['name']})" if near else ""))
        try:
            rr = client.read_holding_registers(addr, count, **_call_kwargs(args.unit))
        except ModbusIOException:
            rr = None

        if not rr or rr.isError():
            print(f"[ERR] Read failed @{addr}. {explain_exception(rr)}")
        else:
            words = list(rr.registers)
            print(f"[OK] Read @{addr} count={count} -> raw {words}")
            if args.dtype:
                try:
                    val = decode_value(args.dtype, words, be_words)
                    print(f"[OK] Decoded as {args.dtype} ({args.endian} words): {val}")
                except Exception as e:
                    print(f"[WARN] Decode failed: {e}")

    elif args.write:
        addr, value, dtype = int(args.write[0]), args.write[1], args.write[2]
        words = pack_value(dtype, value, be_words)
        try:
            if len(words) == 1:
                rq = client.write_register(addr, words[0], **_call_kwargs(args.unit))
            else:
                rq = client.write_registers(addr, words, **_call_kwargs(args.unit))
        except ModbusIOException:
            rq = None

        if not rq or rq.isError():
            print(f"[ERR] Write failed @{addr}. {explain_exception(rq)}")
        else:
            print(f"[OK] Wrote {value} ({dtype}) -> @{addr}, words={words}")

    client.close()


if __name__ == "__main__":
    main()