24 min read · Automation

A PLC in a plant reads one weight, but the label on the scale display shows another. Or the weight is a strange number in the millions because two registers were read in swapped order. Or the value sits at the same number for half an hour and nobody knows the scale has dropped off the network. These problems do not belong to any particular PLC brand. They happen at the join between the scale and the system that reads it.
This article walks through writing a Modbus TCP client yourself with node:net, so you can see every byte sent and received. We then try it against a simulated scale on our own machine (localhost only). There is code to run, real output, and a test suite. As for how well the DVP-SE or the AS suits weighing work, the end of the article lists what to check against Delta's documents, because the author has not opened a manual that confirms this.
The real problem: weight numbers you should not trust
Three hypothetical situations, not projects of any BT San customer.
- Dry ingredient mixing plant: the system reads the weight while a sack is still being poured into the hopper. The value is still swinging. The system decides to close the valve based on a value that has not settled, and the batch ends up over spec.
- Receiving scale at the plant gate: the scale's network cable comes loose. The system keeps showing the last weight as if nothing happened. Staff record the goods receipt with the old value.
- Bagging line: the installer sends a tare command again when a request times out, even though the first command already succeeded. The zero point shifts to the wrong place.
The root cause is treating a weight reading as just “read one number”. In fact there are at least five questions. How was that number converted from registers (word order, decimal places)? Is it stable yet? Is it fresh or old? Did the write command succeed? And what do we do when communication fails?
What the Modbus TCP documents say, and what is still unconfirmed
| Topic | What the document says | Effect on the code |
|---|---|---|
| MBAP header | The Messaging Implementation Guide says the header is 7 bytes: transaction identifier, protocol identifier (0 = Modbus), length and unit identifier | We build the header ourselves on every send |
| Length | The length field is the number of bytes that follow it, including the unit identifier and the data | length = PDU length + 1 |
| Transaction id | The server must copy the request's transaction id into the response | Used to match a reply to its request and to discard replies nobody is waiting for |
| Port | The ADU is sent over TCP to the registered port, 502 | The example uses a random port on localhost so it does not collide with a real one |
| Data size | Application Protocol Specification V1.1b3 says a read can cover 1 to 125 registers per request, and FC16 can write 1 to 123 | Check qty on both sides |
| Exception | An error response uses the same function code plus 0x80, followed by an exception code (01 to 04 are the basic codes) | Check the high bit of the function code in the response |
| Byte order | Modbus uses big-endian for addresses and data | Inside a single register there is nothing to worry about, but a 32-bit value split across two registers is not defined, so check the device manual |
What this article does not confirm: how the D registers of the Delta DVP-SE and AS map to Modbus addresses. The Delta PLC portfolio page we opened has no such table and says nothing about Modbus TCP. The example therefore uses a register map that we made up entirely. Before using it with a real PLC, open the Delta manual for the exact model and firmware. Check whether that model supports Modbus TCP as a server, whether it needs an extra communication module, and which D register matches which address.
Overview of the example
The code is in the folder examples/delta-dvp-se-as-weighing-modbus-tcp/. It uses only the built-ins of Node 24, with no npm install and no internet. Two programs talk over a real socket on 127.0.0.1.
| File | Role |
|---|---|
| scale.ts | The register map of the imaginary scale, the int32 conversion across two registers, and reading the status bits |
| client.ts | The Modbus TCP client: MBAP, FC03/06/16, exceptions, transaction id, timeout, reconnect |
| mock-scale.ts | A simulated server that answers like a scale, including the tare command and exceptions |
| demo.ts | A script that runs 8 scenarios and prints the results |
| modbus.test.ts | The node:test test suite |
The imaginary register map (holding registers): 0-1 net weight as int32, high word first; 2 number of decimal places (a value of 2 means the unit is 0.01 kg); 3 status bits (bit 0 = stable, bit 1 = overload, bit 2 = tared); 4 command (write 1 = tare); 5 weight sample counter; 6-7 setpoint, same type as the weight
export function encodeInt32(value: number, order: WordOrder = WORD_ORDER): [number, number] {
const u = value >>> 0; // two's complement
const hi = (u >>> 16) & 0xffff;
const lo = u & 0xffff;
return order === "high-first" ? [hi, lo] : [lo, hi];
}
export function decodeInt32(a: number, b: number, order: WordOrder = WORD_ORDER): number {
const [hi, lo] = order === "high-first" ? [a, b] : [b, a];
return ((hi << 16) | lo) | 0; // | 0 turns it back into a signed int32
}
export type Reading = { kg: number; stable: boolean; overload: boolean; tared: boolean; counter: number };
// regs = the 6 registers 0..5 read in one FC03 request
export function parseReading(regs: number[], order: WordOrder = WORD_ORDER): Reading {
const raw = decodeInt32(regs[REG.WEIGHT], regs[REG.WEIGHT + 1], order);
const status = regs[REG.STATUS];
return {
kg: raw / 10 ** regs[REG.DECIMALS],
stable: (status & STATUS.STABLE) !== 0,
overload: (status & STATUS.OVERLOAD) !== 0,
tared: (status & STATUS.TARED) !== 0,
counter: regs[REG.COUNTER],
};
}Word order is the most common mistake. Some devices send the high word first and some send the low word first. Decoding in the wrong order raises no error. It silently gives a wrong number. So the test suite checks both orders and also negative values (a net weight after tare can be negative). If your PLC stores the value, check the manual for how the 32-bit value is arranged, and always test with one known real weight first.
Step 1: build the MBAP frame and match the transaction id
private send(pdu: Buffer): Promise<Buffer> {
const s = this.socket;
if (!s || s.destroyed) return Promise.reject(new Error("not connected"));
this.tid = (this.tid + 1) & 0xffff;
const tid = this.tid;
const head = Buffer.alloc(7);
head.writeUInt16BE(tid, 0);
head.writeUInt16BE(0, 2); // protocol id 0 = Modbus
head.writeUInt16BE(pdu.length + 1, 4); // unit id + PDU
head[6] = this.unit;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(tid);
reject(new ModbusTimeout(`no response to transaction ${tid} in ${this.timeoutMs} ms`));
}, this.timeoutMs);
this.pending.set(tid, { fc: pdu[0], resolve, reject, timer });
s.write(Buffer.concat([head, pdu]));
});
}Each request gets a new transaction id (wrapping at 65535) and is stored in a pending table. When a reply comes back, we find the request by that id, not by the order of arrival. This lets us separate a reply that arrives late, after a timeout, so it does not get mixed up with the next request.
// TCP is a byte stream: one data event can hold half a frame or two frames.
private onData(d: Buffer) {
this.buf = Buffer.concat([this.buf, d]);
while (this.buf.length >= 7) {
const len = this.buf.readUInt16BE(4); // bytes after this field: unit id + PDU
if (this.buf.readUInt16BE(2) !== 0 || len < 2 || len > 254) {
this.socket?.destroy(); // not Modbus: drop the connection
return;
}
if (this.buf.length < 6 + len) return; // wait for the rest
const tid = this.buf.readUInt16BE(0);
const pdu = this.buf.subarray(7, 6 + len);
this.buf = this.buf.subarray(6 + len);
const p = this.pending.get(tid);
if (!p) {
this.lateFrames++; // answer to a request that already timed out
continue;
}
clearTimeout(p.timer);
this.pending.delete(tid);
if (pdu[0] === (p.fc | 0x80)) p.reject(new ModbusException(p.fc, pdu[1]));
else if (pdu[0] !== p.fc) p.reject(new Error("unexpected function code in response"));
else p.resolve(pdu);
}
}- TCP is a byte stream, not messages. One data event may carry half a frame or two frames back to back. So we accumulate bytes and cut them by the length field.
- A protocol id other than 0, or an abnormal length, means it is not Modbus. The example drops the connection.
- A response whose function code equals the request's plus 0x80 is an exception. It returns a ModbusException with the code.
- A frame with no request waiting for it (it arrived late, after a timeout) is counted and discarded.
Step 2: FC03 read, FC06 and FC16 write
async readHolding(addr: number, qty: number): Promise<number[]> {
const pdu = Buffer.alloc(5);
pdu[0] = 0x03;
pdu.writeUInt16BE(addr, 1);
pdu.writeUInt16BE(qty, 3);
const r = await this.request(pdu, true);
if (r[1] !== qty * 2) throw new Error("byte count does not match quantity");
return Array.from({ length: qty }, (_, i) => r.readUInt16BE(2 + i * 2));
}
async writeSingle(addr: number, value: number): Promise<void> {
const pdu = Buffer.alloc(5);
pdu[0] = 0x06;
pdu.writeUInt16BE(addr, 1);
pdu.writeUInt16BE(value, 3);
await this.request(pdu, false);
}
async writeMultiple(addr: number, values: number[]): Promise<void> {
const pdu = Buffer.alloc(6 + values.length * 2);
pdu[0] = 0x10;
pdu.writeUInt16BE(addr, 1);
pdu.writeUInt16BE(values.length, 3);
pdu[5] = values.length * 2;
values.forEach((v, i) => pdu.writeUInt16BE(v, 6 + i * 2));
await this.request(pdu, false);
}FC03 sends the start address and the number of registers. FC06 writes one register. FC16 writes several registers together with a byte count. A 32-bit value such as a setpoint must be written as two registers with FC16 in a single request. If you write one register at a time with FC06, the device may see a half-new, half-old value between the two requests. The simulated side deliberately allows FC06 only on the command register, to show this case.
Step 3: the simulated server and exception codes
// returns the response PDU; [fc|0x80, code] for an exception
const handle = (pdu: Buffer): Buffer => {
const fc = pdu[0];
const ex = (code: number) => Buffer.from([fc | 0x80, code]);
if (fc === 0x03 && pdu.length === 5) {
const addr = pdu.readUInt16BE(1), qty = pdu.readUInt16BE(3);
if (qty < 1 || qty > 125) return ex(3);
if (addr + qty > REG.SIZE) return ex(2);
const r = regs().slice(addr, addr + qty);
const out = Buffer.alloc(2 + qty * 2);
out[0] = fc;
out[1] = qty * 2;
r.forEach((v, i) => out.writeUInt16BE(v, 2 + i * 2));
return out;
}
if (fc === 0x06 && pdu.length === 5) {
const addr = pdu.readUInt16BE(1), value = pdu.readUInt16BE(3);
if (addr !== REG.COMMAND) return ex(2); // only the command register accepts FC06 here
if (value > 1) return ex(3);
if (value === 1) state.tare = state.gross; // tare: net weight becomes 0
return Buffer.from(pdu);
}
if (fc === 0x10 && pdu.length >= 6) {
const addr = pdu.readUInt16BE(1), qty = pdu.readUInt16BE(3);
if (qty < 1 || qty > 123 || pdu[5] !== qty * 2 || pdu.length !== 6 + qty * 2) return ex(3);
if (addr !== REG.SETPOINT || qty !== 2) return ex(2); // only the 2-register setpoint is writable
state.setpoint = decodeInt32(pdu.readUInt16BE(6), pdu.readUInt16BE(8));
return pdu.subarray(0, 5);
}
return ex(1); // illegal function
};| Code | Meaning in the base specification | Example that causes it |
|---|---|---|
| 01 | Function code not supported | Sending a function the device does not have |
| 02 | Invalid address | Reading address 100, or writing the weight register with FC06 |
| 03 | Invalid data value | Writing the value 7 to the command register, or reading more than 125 registers |
An exception is not a network failure. It is the device replying that it will not do this. Retrying the same command does not help. You must fix the address or the value. So the example does not retry when it gets an exception.
Step 4: timeout and reconnect without blindly rewriting
// simplified: one reconnect attempt. Production: backoff, jitter, a health state for the UI.
// Only idempotent requests (reads) are retried; a write may already have been executed.
private async request(pdu: Buffer, retry: boolean): Promise<Buffer> {
try {
if (!this.socket) throw new Error("not connected");
return await this.send(pdu);
} catch (e) {
const lost = e instanceof Error && !(e instanceof ModbusException) && !(e instanceof ModbusTimeout);
if (!lost || !retry) throw e;
await this.connect();
this.reconnects++;
return this.send(pdu);
}
}- A timeout means the result is unknown, not that the command failed. A tare command that timed out may already have succeeded. So automatic resending is risky. The example retries only reads, which can be repeated without side effects.
- After a write that times out, read the status back and check it before deciding. For example, look at the tared bit and the net weight.
- When the connection drops, pending requests are rejected immediately, and the next read reconnects once. A real system should have backoff and a connection status shown on the screen.
A real run: eight scenarios
demo.ts opens the simulated scale on a random port on 127.0.0.1, then talks to it through a socket using the real client. The timeout is set to 150 ms. The last items of these two parts cover handling stable versus stuck values, and handling exceptions and timeouts.
console.log("2) unstable value: do not use it");
mock.sample(1500, false);
const u = await read();
console.log(" ", show(u), u.stable ? "" : "-> ignored, waiting for stable");
console.log("3) stale value: the counter stops moving");
mock.sample(1500);
const before = await read();
mock.state.frozen = true;
const after = await read();
console.log(" ", `counter ${before.counter} -> ${after.counter}`, after.counter === before.counter ? "-> stale, raise an alarm" : "");
mock.state.frozen = false;console.log("6) exception responses");
for (const [name, fn] of [
["read address 100", () => c.readHolding(100, 1)],
["write 7 to command register", () => c.writeSingle(REG.COMMAND, 7)],
["write to read-only weight register", () => c.writeSingle(REG.WEIGHT, 1)],
] as const) {
try {
await fn();
} catch (e) {
if (e instanceof ModbusException) console.log(" ", `${name}: exception code ${e.code}`);
else throw e;
}
}console.log("7) timeout, then a late reply with an old transaction id");
mock.state.delayMs = 300;
try {
await c.readHolding(REG.WEIGHT, 2);
} catch (e) {
console.log(" ", e instanceof ModbusTimeout ? "timeout" : String(e));
}
mock.state.delayMs = 0;
console.log(" ", "next read still gets its own answer:", show(await read()));
await new Promise((r) => setTimeout(r, 400));
console.log(" ", "late frame arrived and was dropped:", c.lateFrames === 1);
console.log("8) connection dropped, client reconnects on the next read");
mock.dropClients();
await new Promise((r) => setTimeout(r, 50));
console.log(" ", show(await read()), `reconnects=${c.reconnects}`);1) read weight (FC03, registers 0..5)
12.34 kg stable=true tared=false counter=1
2) unstable value: do not use it
15.00 kg stable=false tared=false counter=2 -> ignored, waiting for stable
3) stale value: the counter stops moving
counter 3 -> 3 -> stale, raise an alarm
4) tare (FC06, register 4 = 1)
0.00 kg stable=true tared=true counter=3
5) write setpoint 5.00 kg (FC16, registers 6..7) and read it back
registers 0,500 -> 5 kg
6) exception responses
read address 100: exception code 2
write 7 to command register: exception code 3
write to read-only weight register: exception code 2
7) timeout, then a late reply with an old transaction id
timeout
next read still gets its own answer: 0.00 kg stable=true tared=true counter=3
late frame arrived and was dropped: true
8) connection dropped, client reconnects on the next read
0.00 kg stable=true tared=true counter=3 reconnects=1- Read six registers in one request with FC03. Got 12.34 kg and stable. Reading the status and the weight in the same request means both values come from the same moment.
- The value is 15.00 kg but the stable bit is 0. The code does not use this value to decide anything. It waits until the value is stable.
- The sample counter stays at 3 on both reads. This means the scale did not send a new sample, so the value is old. It must raise an alert, not trust the old value.
- Send tare with FC06. The net weight becomes 0.00 and the tared bit is true.
- Write setpoint 5.00 kg with FC16. Reading it back gives registers 0 and 500, which decode back to 5 kg.
- The three kinds of exception return codes 2, 3, 2, as the simulated server defines them.
- A reply slower than the timeout. The client reports a timeout. The next read gets its own reply. Later the late frame arrives and is discarded because no transaction id is waiting for it.
- The server side drops the connection. The next read reconnects by itself. reconnects=1
Test suite
modbus.test.ts has 3 cases. Running node --test modbus.test.ts gives 3 passes. The first case tests int32 conversion in both word orders, negative values and scale. The second tests reading, tare, writing a setpoint and exceptions over a real socket. The third tests timeout, a discarded late frame and reconnect. The tests do not confirm real response times. They only check that events happen in the expected order.
From the example to a real PLC and scale
- First confirm who the Modbus TCP server is: the scale, the PLC or a communication module, and whether that model supports it, according to the manufacturer's documents. Do not assume from the presence of an Ethernet port.
- Ask the scale manufacturer for the register table: data types, word order, units, decimal multiplier, the meaning of the status bits, and the values when overloaded or when the sensor fails.
- If a Delta PLC sits in the middle, look at the table that maps D registers to Modbus addresses in the manual for that model. This example does not provide that table.
- Count addresses the way the document does. Some manufacturers write addresses starting at 1 and some at 0. Test with one known value.
- Keep the stability decision in the scale if you can, and use that device's status bit. Do not write your own filter on top of it without a need.
- Trade or certified weighing must follow the law and use inspected equipment. This example has nothing to do with that part.
Hypothetical examples: applying it to three jobs
Mixing ingredients
A recipe usually has a target weight and an acceptance range. The system should dispense until close to the target, then wait for the stable bit before reading the deciding value, and record the actual weight alongside the target. Setting the setpoint with FC16, both registers in the same request, keeps the device from seeing a half-written value.
Receiving scale
The sample counter and the connection status should always be shown next to the weight number. If the value is older than a set time, the screen must change color or block recording. It must not keep showing the last number.
Bagging
A tare command should require that the scale is empty and stable. After sending it, read the tared bit back to confirm. If it times out, check the status before sending again.
Common mistakes and a checklist
- Decoding the 32-bit value in the wrong word order, or forgetting the decimal places
- Using the weight without looking at the stable bit
- Continuing to show the last value after the scale drops off, with no counter or time to check freshness
- Assuming one data event is one Modbus frame
- Not matching by transaction id, so a late reply lands on the wrong request
- Automatically resending a write command after a timeout
- Writing a 32-bit value one register at a time with FC06
- Mixing addresses that start at 0 with addresses that start at 1
- Assuming that having a TCP port means Modbus TCP is supported
- Confirm from the manual that the device is a Modbus TCP server, and get the register table for the exact model.
- Test the weight conversion with at least one reference weight, including a negative value.
- Use only stable values, and check the freshness of the data.
- Have a timeout, a reconnect and a connection status that the operator can see.
- Write commands do not retry on their own, and the result is checked by reading back.
- Limit network permissions to only the machines that should talk to the scale, because Modbus TCP has no built-in authentication.
- Have a test suite that uses a simulated server for abnormal cases.
Cautions about the example: the register map is imaginary. It is not Delta's or any scale model's. It supports only FC03, 06 and 16. There are no multiple units per connection. Multiple concurrent requests (pipelining) were not actually tested. Reconnect happens only once. It was not tested with a real PLC or scale. Use it as a learning model, not as production-ready code.
References
- Modbus Organization — Modbus Messaging on TCP/IP Implementation Guide V1.0b (MBAP header, port 502) (accessed 2026-11-21)
- Modbus Organization — Modbus Application Protocol Specification V1.1b3 (FC03, FC06, FC16, exceptions, big-endian) (accessed 2026-11-21)
- Modbus Organization — Modbus specifications page (accessed 2026-11-21)
- Delta — PLC portfolio (lists DVP-SE and AS series; no register mapping on the page) (accessed 2026-11-21)
- Node.js — net (TCP sockets) (accessed 2026-11-21)
- Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)




