24 分鐘閱讀 · 自動化

工廠裡的 PLC 讀到一個重量,秤重儀螢幕上顯示的卻是另一個值;或者因為兩個暫存器的順序讀反了,重量變成了幾百萬這樣的怪數字;又或者數值半小時一直停在同一個數上,卻沒有人知道秤重儀已經掉出了網路。這些問題並不出在某個品牌的 PLC 上,而是出在秤重儀與讀取資料的系統之間的銜接處。
本文帶你以 node:net 自己撰寫 Modbus TCP 用戶端,讓你看清每一個傳送與接收的位元組,然後在我們自己的機器上(僅限 localhost)以模擬秤重儀來測試。文中有可執行的程式碼、實際輸出結果與測試集。至於 DVP-SE 或 AS 有多適合秤重工作,文末列出了需要對照 Delta 文件查證的事項,因為作者尚未開啟能確認這一點的手冊。
真實的問題:不該輕信的重量數字
以下是三個假設情境,並非 BT San 任何客戶的專案。
- 乾料混合工廠:系統在袋子還在往料斗裡倒的時候就讀取重量,數值仍在擺動。系統根據尚未穩定的數值決定關閉閥門,結果重量超出規格。
- 工廠門口的收貨秤重點:秤重儀的網路線脫落,系統卻像沒事一樣繼續顯示最後一次的重量。員工以舊數值登記了收貨單。
- 裝袋生產線:請求逾時後,安裝人員重複傳送了 tare 指令,而第一個指令其實早已成功。零點因此偏到了錯誤的位置。
根本原因是把讀取重量當成了「讀一個數字」而已。實際上至少有五件事:這個數字是怎樣從暫存器轉換而來的(word 順序、小數位)、是否已經穩定、是新資料還是舊資料、寫入指令是否成功,以及通訊失敗時怎麼辦。
文件中關於 Modbus TCP 的規定,以及尚未確認的部分
| 主題 | 文件怎麼說 | 對程式碼的影響 |
|---|---|---|
| MBAP header | Messaging Implementation Guide 規定 header 長 7 位元組:transaction identifier、protocol identifier(0 = Modbus)、length 與 unit identifier | 每次傳送時我們自己組裝 header |
| Length | length 欄位是它後面所有欄位的位元組數,包括 unit identifier 與資料 | length = PDU 長度 + 1 |
| Transaction id | 伺服器必須把請求中的 transaction id 複製到回應中 | 用來把回覆與請求配對,並丟棄沒有人在等待的回覆 |
| 連接埠 | ADU 透過 TCP 傳送到已註冊的連接埠,即 502 | 範例在 localhost 上使用隨機連接埠,以免與真實設備衝突 |
| 資料大小 | Application Protocol Specification V1.1b3 規定每次請求可讀取 1 到 125 個暫存器,FC16 可寫入 1 到 123 個 | 兩端都要檢查 qty |
| Exception | 錯誤回應使用原本的 function code 加 0x80,後面接 exception code(01 到 04 為基本代碼) | 檢查回應中 function code 的最高位元 |
| Byte order | Modbus 的位址與資料使用 big-endian | 單一暫存器內部無需擔心,但拆分在兩個暫存器中的 32 位元數值並無規定,必須查看設備手冊 |
本文未能確認的事項:Delta DVP-SE 與 AS 的 D 暫存器如何對應為 Modbus 位址。我們開啟的 Delta PLC portfolio 頁面中沒有這張表,也沒有提到 Modbus TCP。因此範例使用的是完全自行設計的暫存器對應表。在用於真實 PLC 之前,必須開啟所用型號與韌體對應的 Delta 手冊,查看該型號是否支援以 server 身分提供 Modbus TCP、是否需要額外的通訊模組,以及哪個 D 暫存器對應哪個位址。
範例概覽
程式碼位於 examples/delta-dvp-se-as-weighing-modbus-tcp/ 資料夾中,只使用 Node 24 的內建功能,不需 npm install,也不連網。兩個程式透過 127.0.0.1 上真實的 socket 互相通訊。
| 檔案 | 作用 |
|---|---|
| scale.ts | 假想秤重儀的暫存器對應表,兩個暫存器的 int32 轉換,以及狀態位元的讀取 |
| client.ts | Modbus TCP 用戶端:MBAP、FC03/06/16、exception、transaction id、timeout、reconnect |
| mock-scale.ts | 像秤重儀一樣回覆的模擬伺服器,包含 tare 指令與 exception |
| demo.ts | 執行 8 個情境並列印結果的腳本 |
| modbus.test.ts | node:test 測試集 |
假想的暫存器對應表(holding register):0-1 為淨重 int32,high word 在前;2 為小數位數(值為 2 表示單位是 0.01 kg);3 為狀態位元(位元 0 = 穩定,位元 1 = 超載,位元 2 = 已 tare);4 為指令(寫入 1 = tare);5 為重量取樣計數器;6-7 為 setpoint,型別與重量相同
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 順序是最常見的出錯點。有的設備先傳送 high word,有的先傳送 low word。以錯誤的順序解碼不會產生任何 error,而是悄無聲息地得出一個錯誤的數字。因此測試集同時檢查兩種順序,也檢查負值(tare 之後的淨重可能為負)。如果數值是由你那邊的 PLC 保存的,請對照手冊確認 32 位元數值是如何排列的,並且始終先以一個已知的真實重量測試一次。
第 1 步:組裝 MBAP 訊框並以 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]));
});
}每個請求都會得到一個新的 transaction id(到 65535 後循環),並存入 pending 表。回覆返回時,我們依據這個 id 找到對應的請求,而不是依到達的順序。這樣,逾時之後才遲到的回覆就能被區分出來,不會與後面的請求混在一起。
// 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 是位元組串流,不是一則則訊息。一個 data event 可能只帶來半個訊框,也可能一次帶來兩個緊鄰的訊框。所以必須先累積位元組,再依 length 欄位切分。
- protocol id 不為 0,或 length 異常,代表這不是 Modbus。範例會中斷連線。
- function code 等於請求的 function code 加 0x80 的回應是 exception,回傳帶有 code 的 ModbusException。
- 沒有請求在等待的訊框(在 timeout 之後才遲到)會被計數後丟棄。
第 2 步:以 FC03 讀取,以 FC06 與 FC16 寫入
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 傳送起始位址與暫存器數量。FC06 寫入一個暫存器。FC16 寫入多個暫存器,並附帶位元組數。像 setpoint 這樣的 32 位元數值,必須以 FC16 在一個請求中寫入兩個暫存器。如果以 FC06 逐個暫存器寫入,設備可能在兩個請求之間看到一半新、一半舊的數值。範例的模擬端特意只允許在指令暫存器上使用 FC06,以示範這種情況。
第 3 步:模擬伺服器與 exception 代碼
// 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
};| 代碼 | 基本規範中的含義 | 引發它的範例 |
|---|---|---|
| 01 | 不支援該 function code | 傳送設備不具備的 function |
| 02 | 位址無效 | 讀取位址 100,或以 FC06 寫入重量暫存器 |
| 03 | 資料值無效 | 對指令暫存器寫入值 7,或讀取超過 125 個暫存器 |
exception 不是網路故障,而是設備回覆說不會照此執行。以同樣的指令重試沒有用,必須修正位址或數值。因此範例在收到 exception 時不會 retry。
第 4 步:timeout 與 reconnect,不盲目重複寫入
// 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);
}
}- timeout 代表結果未知,而不是失敗。逾時的 tare 指令可能已經成功。因此自動重送有風險。範例只對可以重複執行而沒有副作用的讀取進行 retry。
- 寫入逾時之後,先把狀態讀回來檢查,再做決定,例如查看 tared 位元與淨重。
- 連線中斷時,等待中的請求會立即被拒絕,下一次讀取再重新連線一次。真實系統應具備 backoff,並在螢幕上顯示連線狀態。
實際執行:八個情境
demo.ts 在 127.0.0.1 的隨機連接埠上啟動模擬秤重儀,然後以真實的用戶端透過 socket 與它通訊,timeout 設為 150 ms。這兩個部分的最後一項,分別是對穩定值與卡住值的處理,以及對 exception 與 timeout 的處理。
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- 以 FC03 在一個請求中讀取六個暫存器,得到 12.34 kg 且穩定。在同一個請求中讀取狀態與重量,使這兩個值來自同一時刻。
- 數值為 15.00 kg,但穩定位元為 0。程式碼不會用這個值做決定,而是等到穩定為止。
- 兩次讀取時取樣計數器都停在 3,代表秤重儀沒有傳送新的樣本,所以數值是舊的。必須發出警報,而不是相信原來的值。
- 以 FC06 傳送 tare。淨重變為 0.00,tared 位元為真。
- 以 FC16 寫入 setpoint 5.00 kg。讀回得到暫存器 0 與 500,解碼後還原為 5 kg。
- 三種 exception 回傳的代碼依序為 2、3、2,與模擬伺服器的設定一致。
- 回覆慢於 timeout。用戶端回報 timeout,下一次讀取得到它自己的回覆。之後遲到的訊框到達,因為沒有 transaction id 在等待而被丟棄。
- 在伺服器端中斷連線。下一次讀取自行重新連線。reconnects=1
測試集
modbus.test.ts 有 3 個案例,以 node --test modbus.test.ts 執行可得到 3 個 pass。第一個案例測試兩種 word 順序下的 int32 轉換、負值與 scale。第二個案例透過真實的 socket 測試讀取、tare、寫入 setpoint 與 exception。第三個案例測試 timeout、被丟棄的遲到訊框與 reconnect。這些測試不驗證真實的回應時間,只檢查事件是否依預期的順序發生。
從範例走向真實的 PLC 與秤重儀
- 先確認誰是 Modbus TCP server:秤重儀、PLC 還是通訊模組,以及該型號是否支援,以製造商的文件為準。不要因為有 Ethernet 連接埠就想當然。
- 向秤重儀製造商索取暫存器表:資料型別、word 順序、單位、小數倍數、狀態位元的含義,以及超載或感測器故障時的數值。
- 如果由 Delta PLC 居中轉接,必須在該型號的手冊中查看把 D 暫存器對應為 Modbus 位址的表。本範例沒有提供這張表。
- 位址的計數方式要與文件一致。有的製造商寫的位址從 1 開始,有的從 0 開始。請以一個已知的值測試。
- 盡可能把穩定判斷留在秤重儀中,並使用該設備的狀態位元,沒有必要就不要自己再疊加一層濾波。
- 貿易或需認證的秤重必須符合法律規定,並使用經過檢定的設備。本範例與這一部分無關。
假設範例:用於三種工作
原料混合
配方通常有目標重量與可接受範圍。系統應當投料到接近目標,再等待穩定位元,然後讀取用於決策的數值,並把實際重量與目標一併記錄。以 FC16 在同一個請求中設定兩個暫存器的 setpoint,可避免設備看到寫了一半的數值。
收貨秤重
取樣計數器與連線狀態應始終顯示在重量數字旁邊。如果數值的陳舊時間超過設定值,螢幕必須變色或阻止記錄,而不是繼續顯示最後一個數字。
裝袋
tare 指令應當以秤重儀空載且穩定為條件,發出指令之後必須讀回 tared 位元來確認。如果逾時,先檢查狀態,再決定是否重送。
常見錯誤與檢查清單
- 以錯誤的 word 順序解碼 32 位元數值,或忘了小數位
- 不看穩定位元就使用重量
- 秤重儀掉線之後繼續顯示最後一個值,沒有計數器或時間來檢查資料是否新鮮
- 以為一個 data event 就是一個 Modbus 訊框
- 不使用 transaction id 配對,導致遲到的回覆落到錯誤的請求上
- 逾時後自動重送寫入指令
- 以 FC06 逐個暫存器寫入 32 位元數值
- 把從 0 開始的位址與從 1 開始的位址混用
- 認為有 TCP 連接埠就代表支援 Modbus TCP
- 根據手冊確認設備是 Modbus TCP server,並取得與型號完全對應的暫存器表。
- 至少以一個標準重量測試重量轉換,包括負值。
- 只使用穩定的值,並檢查資料的新鮮度。
- 具備 timeout、reconnect,以及操作人員能看到的連線狀態。
- 寫入指令不自行 retry,並透過讀回來檢查結果。
- 把網路權限限制在應當與秤重儀通訊的機器上,因為 Modbus TCP 本身沒有身分驗證。
- 具備使用模擬伺服器測試異常情況的測試集。
範例的注意事項:暫存器對應表是假想的,不屬於 Delta 或任何型號的秤重儀。僅支援 FC03、06、16,不支援單一連線上的多個 unit,沒有實際測試過同時傳送多個請求的 pipeline,reconnect 僅有一次,也沒有以真實的 PLC 或秤重儀測試。請把它當作學習模型,而不是可直接上線的程式碼。
參考資料
- 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)




