# Modbus TCP slave :id=top

------

> _Doc Ver:_ 1.2  
_App Ver:_ 2.6.6.53  
_Date:_ 09/13/2026

------

SA1 uses the **same Modbus TCP slave wire protocol as SA2** (`sa_daq`): the master **polls FC03** holding registers; the device does **not** push. The slave runs **inside sa-di**, not a separate `modbustcp` process. There is no `/modbus-map` page and no `sa_daq.conf` `[modbus]` section.

**Factory default is off, port 1502.** After enable, masters connect to the device LAN IP on 1502 (Docker publishes container 1502 to the host). Port **502** is allowed; `sa-di.service` already has `CAP_NET_BIND_SERVICE`.

See also: [Get data via the command](get_data.md) · [Architecture](architecture.md) · [Virtual sensors](vss.md) · [Start, check, upgrade](operate.md) · [Docker](docker.md) · [API](api.md)

**Contents:** [Diff](#diff) · [UI](#ui) · [Protocol](#proto) · [MBAP](#mbap) · [Network](#sec) · [Map](#map) · [Config](#cfg) · [Exceptions](#exc) · [Test](#test) · [Troubleshooting](#trouble) · [Where to read this](#where)

------

## 0. Versus SA2 / older SA1 :id=diff

| | SA1 2.6.6.33+ | SA2 / old standalone |
|---|---------------|---------------------|
| Who listens | **sa-di** | `sa_daq` or standalone `sa_modbus_tcp_slave` / `modbustcp` |
| Config | `/var/sa/conf/modbus.json` (Addon Parameters) | `sa_daq.conf` `[modbus]` or `/modbus-map` |
| Enable | Addon Save → `:SYS:RELOAD` | edit conf / restart a process |
| Default port | **1502** | often 1502; cable-force profile often 502 |
| Protocol | FC03 only; float32 / scaled_int; dense or sparse | same wire format |
| Not implemented | ASCII, RTU, DCBA float layout, write FCs | some old packs had RTU / ASCII daemons |

The Addon **Modbus ascii** tab (`modbusascii.json`) is a serial ASCII report. It is **not** this TCP slave. Do not mix it with TCP 1502.

After upgrade, persist may still show retired IDs (`MODBUSRTU_ENABLE`, `MODBUS_FLOAT_FORMAT`, `MODBUS_RPTERR*`, `MODBUSRTU_UART`). sa-di **ignores** them. Package AfterCfg is always `:SYS:RELOAD` — do not `killall -9 modbustcp`. If the field file still has **Port 502**, merge keeps that value; set 1502 and Save if you want the new default.

------

## 1. Enable from the Web UI :id=ui

Needs **admin** (`can_operate`). A `user` role gets **403** on `setjson.php` and AfterCfg.

1. Open `http://<device-IP>/login` (or `:8080` / `:81` if 80 is down).
2. **Addon** → item **2** **Modbus Configure** (`addon.php?view=2`; factory enabled-tab order, 1-based).
3. Check **Enable** (`MODBUS_ENABLE`).
4. Set **Port = 1502** (or the port you agreed with the master), Listen IP `0.0.0.0`.
5. Click **Save**. The page:
   - `POST /m/setjson.php` with `name=addon/modbus.json` (sa-web writes the **top-level** `/var/sa/conf/modbus.json`; a symlink there is replaced by a regular file);
   - then `GET /m/tcp.php?…cmd=:CMD?:SYS:RELOAD ` (trailing space from the page; browsers send `%20`). sa-web maps that to sa-di `:SYS:RELOAD`.
6. AfterCfg should return **`0`**. No sa-di restart.
7. **Configure** runs AfterCfg only and does not rewrite JSON. Change values, then **Save**.

Turning Enable off and Saving stops the listener. Changing IP/port while enabled rebinds. Parameter Memos match this page; the **Help** button opens this document (`help/#/{lang}modbus_tcp_slave`).

The Service page shows **Modbus TCP** (`SI_MODBUS_TCP`); each successful FC03 reply increments the counter.

SA1 and SA2 are mutually exclusive. Do not run `sa_daq` beside sa-di. Do not run two `sa-di`.

------

## 2. Protocol :id=proto

- **Role:** slave. Masters must not expect FC16 / FC06 / FC01 / FC04.
- **Transport:** Modbus TCP (MBAP + PDU). Protocol ID must be **0**, otherwise exception 0x01 and the **connection is dropped**.
- **Listen:** `0.0.0.0:1502` by default, **IPv4 only** (`AF_INET`). Listen backlog **16**.
- **Function:** **`0x03` Read Holding Registers** only
- **Per point:** **2** holding registers (32-bit)
- **FC03 start and quantity must both be even**; quantity 1–125 and must not pass the map high bound
- **Byte order:** default big-endian (high word first). See [§2.1](#endian)
- **Encode:** `float32` (IEEE 754, default) or `scaled_int`
- **Unit ID:** optional; when on, UnitID must equal Slave ID or **0x0B**
- **Connections:** `MODBUS_MAX_CONN` (default 100); incomplete MBAP/PDU for `MODBUS_TIMEOUT` seconds drops the socket
- **Values:** each FC03 snapshots the **latest complete** `rwlesscache` slot (index `ei-1`) and copies matched real `PhysicValue`. If that slot `Counter==0` (no complete frame yet), every register is **0**. Virtuals: [§4.2](#virtual)
- **ID cap:** snapshot IDs 1–**512**. Sparse maps may name a larger SensorID, but **IDs &gt; 512 always read 0**

### 2.1 Byte order and encoding :id=endian

A 32-bit payload is split into high and low 16-bit halves, then placed in two registers (each register is still big-endian on the wire):

| `MODBUS_BYTE_ORDER` | Start register | Next register | Notes |
|---------------------|--------------|---------------|-------|
| 0 big-endian (default) | high 16 | low 16 | network order, most PLCs |
| 1 little-endian | low 16 | high 16 | some x86 masters |

**float32 example:** engineering `22.0` → IEEE 754 `0x41B00000`.

- big-endian: start=`0x41B0`, next=`0x0000`
- little-endian: start=`0x0000`, next=`0x41B0`

Values outside about `±3.4e38`, or NaN/Inf, encode as **0**.

**scaled_int:** `round(engineering × 10000)` as signed int32 (clamped). `22.0` → `220000` = `0x00035B60`.

- big-endian: start=`0x0003`, next=`0x5B60`
- little-endian: start=`0x5B60`, next=`0x0003`

The master **divides by 10000**. Non-finite values become **0**.

### 2.2 MBAP frame :id=mbap

A one-point read (2 registers) is **12** bytes:

| Offset | Len | Field | Example (start 4096, qty 2, Unit 1) |
|------|------|------|-------------------------------------|
| 0 | 2 | Transaction ID | `00 01` |
| 2 | 2 | Protocol ID | **must be `00 00`** |
| 4 | 2 | Length (bytes after this field, including Unit ID) | `00 06` |
| 6 | 1 | Unit ID | `01` |
| 7 | 1 | Function | `03` |
| 8 | 2 | Start address | `10 00` (4096) |
| 10 | 2 | Quantity | `00 02` |

A good reply is **13** bytes: MBAP + Unit + `03` + byte count `04` + 4 register bytes. An exception is **9** bytes: function `| 0x80` then one exception code. Protocol ID ≠ 0 uses function `0x00` in the exception PDU (`0x80` on the wire) and then drops the connection.

### 2.3 Network and security :id=sec

- **No** Modbus password, TLS, or allow-list. Enabling the slave exposes PVs on that TCP port. Use a trusted LAN; do not port-forward it to the internet.
- Firewall: allow **1502/tcp** (or your chosen port) from the master subnet.
- IPv4 only. `::` / IPv6 in Listen IP fails bind (`[modbus] bad server_ip`).
- Ports **&lt; 1024** (including 502) need `CAP_NET_BIND_SERVICE` (factory unit has it).
- When the connection cap is hit, new TCP is **closed with no Modbus exception** (`[modbus] reject: max connections`).
- Docker: the master hits the **host** mapped port (`SA1_MODBUS_PORT`, default 1502). sa-di still listens on 1502 inside the container.

------

## 3. Register map :id=map

### 3.1 Dense (`MODBUS_MAP` empty)

- Address: `register_start + (SensorID − 1) × 2`
- Default `register_start = 4096` (`0x1000`), `channel_count = 32` → **`0x1000`–`0x103F`** (64 registers)
- `channel_count` 1–256; UI `register_start` steps by 2 (keep it even)
- Only **matched** (`IsMatched`) real PVs; unmatched / empty slots read **0**
- Virtuals stay out of dense mode unless Include virtual is on

| Channel | SensorID | Start (hex) | Registers | FC | Default type |
| --- | ---- | ---------- | ----- | ---- | ------- |
| 1   | 1    | 0x1000     | 2     | 0x03 | Float32 |
| 2   | 2    | 0x1002     | 2     | 0x03 | Float32 |
| …   | …    | …          | 2     | 0x03 | Float32 |
| 32  | 32   | 0x103E     | 2     | 0x03 | Float32 |

SensorID 100 sits at `4096 + 99×2 = 4294`. Raise `channel_count` to at least 100 or the start is out of range (**0x02**).

### 3.2 Sparse (`MODBUS_MAP` non-empty)

Any valid even mapping switches to sparse. Separators: `,` `;` `|`. Optional `map.` prefix. `=` or `:` between address and ID.

```text
0=101,2=102,4=103
map.0=101
map.2=102
```

Blade-root My/η from `bladeload.php` **Fill Modbus sparse map**:

```text
0=201,2=202,4=203,6=204,8=205,10=206,12=207,14=208
```

That write does **not** set `MODBUS_ENABLE`. Enable the slave on Addon → Modbus Configure. See [Root load](bladeload.md).

- Address must be **even**; odd addresses are **ignored** (`[modbus] map.<addr> ignored`)
- At most 128 entries; a later line for the same address overwrites
- Span is from the lowest mapped address through **max mapped address + 1**
- Unmapped even addresses in the request return **0** (not an exception)
- Mapped virtual IDs are exported even when Include virtual is off
- SensorID must be ≥ 1; **IDs &gt; 512** are not in the snapshot → **0**

### 3.3 Reading

FC03: start + even count. Max 125 registers per request (and the map high bound). Factory dense 32 channels: read **64** registers once.

### 3.4 PLC 4xxxx display :id=plc

This handbook and `mbpoll -0` use **protocol addresses** (zero-based). Some PLCs display holding registers as 4xxxx:

`display ≈ 40001 + protocol_address` → 4096 → **44097** (if that PLC shows address 0 as 40001).

Follow the master manual. Do not type 4096 into a 4xxxx field unless that software says so.

------

## 4. Config keys :id=cfg

Truth: **`/var/sa/conf/modbus.json`**. UI: Addon → Modbus Configure. The page Help link opens this document.

| ID | Default | Meaning |
|------|--------|------|
| `MODBUS_ENABLE` | false | start/stop the slave on `:SYS:RELOAD` |
| `MODBUS_IP` | `0.0.0.0` | listen address (IPv4) |
| `MODBUS_PORT` | 1502 | listen port (1–65535) |
| `MODBUS_ID` | 1 | Slave / Unit ID (1–247); used when validation is on |
| `MODBUS_VALIDATE_UNIT_ID` | false | check Unit ID |
| `MODBUS_MAX_CONN` | 100 | max clients (1–1024) |
| `MODBUS_TIMEOUT` | 30 | drop if a frame is incomplete (s, 1–3600) |
| `MODBUS_CHANNEL_COUNT` | 32 | dense slots (1–256) |
| `MODBUS_REGISTER_START` | 4096 | dense start (must be even) |
| `MODBUS_BYTE_ORDER` | 0 | 0 big-endian, 1 little-endian |
| `MODBUS_ENCODE_MODE` | 0 | 0 float32, 1 scaled_int |
| `MODBUS_INCLUDE_VIRTUAL` | false | export virtuals in dense mode |
| `MODBUS_MAP` | empty | sparse map; empty = dense |

sa-di reads `Data.Value` for those IDs. Minimal enable fragment (the full file also has groups, memos, AfterCfg):

```json
{"ID":"MODBUS_ENABLE","Data":{"Type":2,"Value":true}},
{"ID":"MODBUS_PORT","Data":{"Type":1,"Value":1502}},
{"ID":"MODBUS_MAP","Data":{"Type":0,"Value":""}}
```

### 4.1 Unit ID check :id=unit

Off by default: any Unit ID can read. When on:

1. UnitID ≠ `MODBUS_ID` → exception **0x0B** (exception PDU echoes the request Unit ID)
2. Point the master Slave ID at the same value as the page (factory 1)

### 4.2 Virtual points :id=virtual

- Dense + Include virtual off: `vrwlescache` is not scanned
- Dense + Include virtual on: virtual `VAL` is exported; dense mode skips virtuals with `Error≠0`
- Sparse: mapped virtual IDs are always snapshotted

IDs and formulas: [Virtual sensors](vss.md) · [Formulas](function.md).

------

## 5. Exceptions :id=exc

Standard exception PDU: function `| 0x80`, then the exception code.

| Code | Name | When |
| ---- | ------ | ------------------------ |
| 0x01 | Illegal function | not FC03, or MBAP Protocol ID ≠ 0 |
| 0x02 | Illegal address | start below the map low bound or above the high bound |
| 0x03 | Illegal value | count 0, odd start/count, past the high bound, more than 125 registers, or FC03 payload shorter than 4 bytes |
| 0x0B | Gateway target | Unit ID check on and UnitID ≠ Slave ID |

New TCP clients are dropped (no Modbus exception) when `max_connections` is full. Length &lt; 2 or an oversized PDU closes the socket quietly.

------

## 6. Test master :id=test

Confirm the listener:

```bash
ss -lnt | grep 1502
# LISTEN ... 0.0.0.0:1502
```

### 6.1 Raw TCP (no pymodbus version pin)

```python
import socket, struct
addr, port, start, count = "127.0.0.1", 1502, 4096, 2
pkt = struct.pack(">HHHBBHH", 1, 0, 6, 1, 3, start, count)
s = socket.create_connection((addr, port), 2)
s.sendall(pkt)
resp = s.recv(256)
s.close()
assert resp[7] == 3 and resp[8] == 4
hi, lo = struct.unpack(">HH", resp[9:13])
bits = (hi << 16) | lo
print(struct.unpack(">f", struct.pack(">I", bits))[0])
```

A field box has returned `0x41B00000` → **22.0** (big-endian float32). Unmatched sensors are **0.0**.

### 6.2 pymodbus 3

```python
from pymodbus.client import ModbusTcpClient
c = ModbusTcpClient("127.0.0.1", port=1502)
assert c.connect()
rr = c.read_holding_registers(4096, count=64, device_id=1)
print(rr.registers[:4])
c.close()
```

### 6.3 mbpoll

```bash
mbpoll -0 -a 1 -r 4096 -c 64 -t 4:float -p 1502 127.0.0.1
```

`-0` is protocol-address zero-based. Do not treat 4096 as PLC 4xxxx unless that master documents it that way.

Docker: the master hits the **host** mapped port (default 1502, `SA1_MODBUS_PORT`). sa-di still listens on 1502 inside the container.

------

## 7. Troubleshooting :id=trouble

| Symptom | Check |
|------|-----|
| `ss` has no 1502 | not enabled / not saved; AfterCfg not `0`; sa-di down; persist port is still 502 |
| bind failed | port in use (SA2 / another sa-di); Listen IP not IPv4; &lt;1024 without capability |
| Connect then drop | max connections; Protocol ID ≠ 0; bad Length |
| Exception 0x01 | FC01/04/16 etc. |
| Exception 0x02 | start outside dense/sparse span (`channel_count` too small or start ≠ 4096) |
| Exception 0x03 | odd start/count, or too many registers |
| Exception 0x0B | Unit ID check is on |
| All zeros | unmatched sensors, no complete frame yet (`Counter==0`), wrong channel, encode/endian mismatch, sparse ID &gt; 512 |
| 403 | `user` role tried to Save |
| UI Save still off | inspect `/var/sa/conf/modbus.json` `MODBUS_ENABLE`; sa-web writes the top-level file |
| Clash with SA2 | stop `sa_daq` / `sa_web`; never run both stacks |

Do not `killall -9`. Hot-apply with `:SYS:RELOAD` (debug page or Addon Save). Log prefix `[modbus]`.

------

## 8. Where this help lives :id=where

Same source tree (`web/help/`):

| Surface | URL |
|------|------|
| On-device Handbook (Help → Handbook / 手册) | `http://<device>/help/#/modbus_tcp_slave` |
| Help menu → Modbus TCP | same |
| Addon **Help** | this page |
| Handbook short tip (`help/tips/`) | Help → Handbook category |
| LAN portal | http://192.168.3.9/sa1/help/ (`reader.html#/zh-cn/modbus_tcp_slave`) |
| Internet portal | http://sc.casstk.com/sa1/help/ (pages only, no tars) |
| Q&A | http://112.74.47.129:9999 (say you are asking about **SA1**) |
| Portal FAQ | `…/sa1/help/faq.json` keys `modbus*` |

Edit `web/help/` only, then `bash scripts/sync-runtime.sh --web` (device) and `bash scripts/sync-sa1-mirrors.sh` (portals). **Do not** sync `conf/` onto persist.

------

## Change log :id=changelog

|Version|Date|Description|
|:--:|----|----------|
|1.2|09/13/2026|MBAP, security, IPv4, ID 512 cap, PLC 4xxxx, JSON fragment, help surfaces, bind/all-zero troubleshooting.|
|1.1|09/13/2026|UI steps, endian examples, master samples, upgrade leftovers, troubleshooting.|
|1.0|09/13/2026|SA1 slave in sa-di; protocol matches SA2 FC03.|

------

[Top](#top)
