feat(devices): DT-008 reader discovery + auto-configuration over the vendor UDP protocol
Build & push images / images (push) Successful in 3m7s
Build & push images / images (push) Successful in 3m7s
The Dingtian DT-008's Windows-only config tool speaks a small binary UDP protocol (reader :24680 unicast get/set, :24582 broadcast search/set-network), reversed in wiki/raw/dingtian_qr_linux (PROTOCOL.md + dingtian_qr.py, copied to scripts/). Reading park-2's readers with it from the booth found both in WG26 output mode — the "beeps but captures nothing" enrolment failure: they never pushed HTTP at all. The app now speaks the protocol itself (packages/devices dingtian-qr-config.ts, Node dgram, host-network container) and the dingtian-qr-reader driver uses it: - discover(): first driver to implement the wizard's Scan capability; rows show serial, IP, output mode, current server target, card format, firmware. - preconditions: output type must be HTTP (fixable — save switches it); typed serial must equal the reported one and the reader must answer on UDP (both block the save). - configureInputPush(): set-network the reader's server to this booth's IP + listen port, confirmed by polling (the reader applies it without an ack and is silent for seconds). - usesPushAuth=false: the scan GET carries no credentials, so no push secret is stored. - a reader saved without an IP warns instead of failing (legacy vendor-tool setup). Verified on the bench unit: WG26→HTTP, target 8080→8081→8080, struct byte-identical after. 15 protocol tests against a fake reader + 17 adapter tests. Wiki: device-discovery, first-run-setup, dingtian-dt008-reader, site-device-installation §2 (SSH procedure; the "needs a Windows laptop" claim withdrawn), new source page dingtian-qr-linux-tool.
This commit is contained in:
@@ -0,0 +1,346 @@
|
||||
import { createSocket, type Socket } from "node:dgram";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
QR_CMD,
|
||||
QR_OUTPUT_HTTP,
|
||||
buildDeviceInfo,
|
||||
checksum,
|
||||
discoverReaders,
|
||||
exchange,
|
||||
frameHeader,
|
||||
parseDeviceInfo,
|
||||
parseFirmware,
|
||||
parseFrame,
|
||||
parseParams,
|
||||
readFirmware,
|
||||
readParams,
|
||||
setNetwork,
|
||||
writeSetting,
|
||||
ipToBytes,
|
||||
} from "./dingtian-qr-config.js";
|
||||
|
||||
// The DT-008 configuration protocol, against a FAKE reader on loopback that behaves like
|
||||
// the real one (wiki/raw/dingtian_qr_linux/PROTOCOL.md): header + payload must arrive as
|
||||
// two datagrams, every write is acked with cmd+1 and a status byte, search answers with
|
||||
// a 96-byte DeviceInfo, set-network is applied WITHOUT a reply. Byte layouts below are
|
||||
// the worked examples and the reference capture from the bench reader HC002721.
|
||||
|
||||
// --- reference bytes -------------------------------------------------------
|
||||
|
||||
/** Build a 720-byte Params struct like the bench capture (HTTP, 10.0.10.204:8080, 8H…). */
|
||||
function referenceParams(over: Partial<{ outputType: number; server: string; serverPort: number }> = {}): Buffer {
|
||||
const b = Buffer.alloc(720);
|
||||
b.writeUInt32LE(0, 0x000); // static IP
|
||||
ipToBytes("10.0.10.12").copy(b, 0x004);
|
||||
ipToBytes("255.255.255.0").copy(b, 0x008);
|
||||
ipToBytes("10.0.10.1").copy(b, 0x00c);
|
||||
ipToBytes("8.8.8.8").copy(b, 0x010);
|
||||
ipToBytes("8.8.4.4").copy(b, 0x014);
|
||||
b.write(over.server ?? "10.0.10.204", 0x018, "utf8");
|
||||
b.writeUInt32LE(over.serverPort ?? 8080, 0x048);
|
||||
b.writeUInt32LE(0, 0x04c); // PHP
|
||||
b.writeUInt8(over.outputType ?? 3, 0x198); // HTTP
|
||||
b.writeUInt8(2, 0x19c); // 8H
|
||||
b.writeUInt8(1, 0x1a0); // add Enter
|
||||
b.writeUInt8(0, 0x1a1);
|
||||
b.writeUInt32LE(1, 0x1a4); // ASCII
|
||||
b.writeUInt32LE(1, 0x1c8);
|
||||
b.writeUInt32LE(1, 0x1ec); // restart 12 h
|
||||
b.writeUInt32LE(0, 0x1f0); // normal
|
||||
b.writeUInt32LE(0, 0x1f8); // buzzer off
|
||||
b.writeUInt32LE(20, 0x1fc); // 2000 µs
|
||||
b.writeUInt32LE(4, 0x200); // 400 µs
|
||||
b.writeUInt32LE(9600, 0x204);
|
||||
b.writeUInt32LE(8, 0x208);
|
||||
b.writeUInt32LE(1, 0x20c);
|
||||
b.writeUInt32LE(2, 0x210); // parity none
|
||||
b.writeUInt32LE(4, 0x214); // QR ASCII
|
||||
b.writeUInt32LE(1, 0x218); // fill light open
|
||||
b.writeUInt32LE(1, 0x288);
|
||||
b.writeUInt32LE(1, 0x28c);
|
||||
b.write("K:", 0x290, "utf8");
|
||||
return b;
|
||||
}
|
||||
|
||||
function referenceFirmware(serial = "HC002721"): Buffer {
|
||||
const b = Buffer.alloc(64);
|
||||
b.write("doorqrcode", 0);
|
||||
b.write("ver_client1_1.1", 16);
|
||||
b.write("v3s", 32);
|
||||
b.write("h42", 40);
|
||||
b.write(serial, 48);
|
||||
return b;
|
||||
}
|
||||
|
||||
// --- fake reader -----------------------------------------------------------
|
||||
|
||||
interface FakeReader {
|
||||
readonly unicast: number;
|
||||
readonly broadcast: number;
|
||||
readonly writes: { cmd: number; value: number }[];
|
||||
params: Buffer;
|
||||
singleDatagramFrames: number;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** A loopback reader. One socket plays both ports (unicast + "broadcast"). */
|
||||
async function fakeReader(params = referenceParams(), serial = "HC002721"): Promise<FakeReader> {
|
||||
const bind = (): Promise<Socket> =>
|
||||
new Promise((res) => {
|
||||
const s = createSocket("udp4");
|
||||
s.bind(0, "127.0.0.1", () => res(s));
|
||||
});
|
||||
const uni = await bind();
|
||||
const bc = await bind();
|
||||
const state: FakeReader = {
|
||||
unicast: uni.address().port,
|
||||
broadcast: bc.address().port,
|
||||
writes: [],
|
||||
params,
|
||||
singleDatagramFrames: 0,
|
||||
close: () => {
|
||||
uni.close();
|
||||
bc.close();
|
||||
},
|
||||
};
|
||||
|
||||
const reply = (sock: Socket, rinfo: { address: string; port: number }, cmd: number, payload: Buffer) => {
|
||||
// Real replies: header + payload in ONE datagram, id arbitrary.
|
||||
sock.send(Buffer.concat([frameHeader(cmd, payload, 0x1234), payload]), rinfo.port, rinfo.address);
|
||||
};
|
||||
const deviceInfo = () => {
|
||||
const p = parseParams(state.params);
|
||||
return buildDeviceInfo({ ...p, serial });
|
||||
};
|
||||
|
||||
const handle = (sock: Socket, rinfo: { address: string; port: number }, cmd: number, payload: Buffer) => {
|
||||
switch (cmd) {
|
||||
case QR_CMD.firmware:
|
||||
return reply(sock, rinfo, 1, referenceFirmware(serial));
|
||||
case QR_CMD.getParams:
|
||||
return reply(sock, rinfo, 31, state.params);
|
||||
case QR_CMD.search:
|
||||
return reply(sock, rinfo, 3, deviceInfo());
|
||||
case QR_CMD.setNetwork: {
|
||||
// Applied only when the serial matches; the real reader sends NO ack.
|
||||
const info = parseDeviceInfo(payload);
|
||||
if (info.serial !== serial) return;
|
||||
const next = Buffer.from(state.params);
|
||||
next.fill(0, 0x018, 0x048);
|
||||
next.write(info.server, 0x018, "utf8");
|
||||
next.writeUInt32LE(info.serverPort, 0x048);
|
||||
next.writeUInt32LE(info.httpLanguage, 0x04c);
|
||||
state.params = next;
|
||||
return;
|
||||
}
|
||||
case QR_CMD.outputType: {
|
||||
const v = payload.readUInt32LE(0);
|
||||
state.writes.push({ cmd, value: v });
|
||||
if (v < 1 || v > 10) return reply(sock, rinfo, cmd + 1, Buffer.from([1])); // rejected
|
||||
state.params = Buffer.from(state.params);
|
||||
state.params.writeUInt8(v, 0x198);
|
||||
return reply(sock, rinfo, cmd + 1, Buffer.from([0]));
|
||||
}
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Two-datagram write discipline, like the hardware: a header announcing len > 0 waits
|
||||
// for the payload datagram; a header WITH payload glued on is a single-datagram frame
|
||||
// → counted and ignored.
|
||||
for (const sock of [uni, bc]) {
|
||||
let pending: { cmd: number; len: number } | null = null;
|
||||
sock.on("message", (msg, rinfo) => {
|
||||
if (pending) {
|
||||
const p = pending;
|
||||
pending = null;
|
||||
if (msg.length === p.len) handle(sock, rinfo, p.cmd, msg);
|
||||
return;
|
||||
}
|
||||
if (msg.length < 17 || msg.subarray(0, 4).toString("ascii") !== "XXXX") return;
|
||||
const cmd = msg.readUInt32LE(8);
|
||||
const len = msg.readUInt32LE(12);
|
||||
if (msg.length > 17) {
|
||||
state.singleDatagramFrames++;
|
||||
return;
|
||||
}
|
||||
if (len === 0) handle(sock, rinfo, cmd, Buffer.alloc(0));
|
||||
else pending = { cmd, len };
|
||||
});
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
let reader: FakeReader | null = null;
|
||||
const opts = () => ({
|
||||
timeoutMs: 300,
|
||||
retries: 0,
|
||||
ports: { unicast: reader!.unicast, broadcast: reader!.broadcast },
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
reader?.close();
|
||||
reader = null;
|
||||
});
|
||||
|
||||
// --- framing (worked examples from PROTOCOL.md §2) -------------------------
|
||||
|
||||
describe("DT-008 config frame", () => {
|
||||
it("search request: magic, id 0, cmd 2, len 0, checksum 0xFF", () => {
|
||||
expect(frameHeader(QR_CMD.search).toString("hex")).toBe("58585858" + "00000000" + "02000000" + "00000000" + "ff");
|
||||
});
|
||||
|
||||
it("set buzzer on (cmd 18, u32 1): checksum 0xFF − 1 = 0xFE", () => {
|
||||
const payload = Buffer.from([1, 0, 0, 0]);
|
||||
expect(checksum(payload)).toBe(0xfe);
|
||||
expect(frameHeader(18, payload).toString("hex")).toBe("58585858" + "00000000" + "12000000" + "04000000" + "fe");
|
||||
});
|
||||
|
||||
it("parses a reader ack (cmd 19, one status byte) and rejects a bad checksum", () => {
|
||||
const ack = Buffer.from("58585858" + "00000000" + "13000000" + "01000000" + "ff" + "00", "hex");
|
||||
expect(parseFrame(ack)).toEqual({ id: 0, cmd: 19, payload: Buffer.from([0]) });
|
||||
const bad = Buffer.from(ack);
|
||||
bad[16] = 0x00;
|
||||
expect(parseFrame(bad)).toBeNull();
|
||||
expect(parseFrame(Buffer.from("YYYY", "ascii"))).toBeNull();
|
||||
});
|
||||
|
||||
it("IPv4 is stored little-endian (bytes reversed): 10.0.10.12 → 0c 0a 00 0a", () => {
|
||||
expect(ipToBytes("10.0.10.12").toString("hex")).toBe("0c0a000a");
|
||||
expect(() => ipToBytes("10.0.10")).toThrow(/IPv4/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DT-008 blocks", () => {
|
||||
it("decodes the reference 720-byte params", () => {
|
||||
const p = parseParams(referenceParams());
|
||||
expect(p).toMatchObject({
|
||||
dhcp: 0,
|
||||
ip: "10.0.10.12",
|
||||
netmask: "255.255.255.0",
|
||||
gateway: "10.0.10.1",
|
||||
dns1: "8.8.8.8",
|
||||
dns2: "8.8.4.4",
|
||||
server: "10.0.10.204",
|
||||
serverPort: 8080,
|
||||
httpLanguage: 0,
|
||||
outputType: QR_OUTPUT_HTTP,
|
||||
cardInputFormat: 2,
|
||||
lastAddEnter: 1,
|
||||
restartInterval: 1,
|
||||
buzzer: 0,
|
||||
highPulseUs: 2000,
|
||||
lowPulseUs: 400,
|
||||
baudrate: 9600,
|
||||
parity: 2,
|
||||
qrOutputFormat: 4,
|
||||
fillLight: 1,
|
||||
cardPrefix: "K:",
|
||||
qrPrefix: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("DeviceInfo round-trips (serial, addresses, server, port, language)", () => {
|
||||
const info = {
|
||||
serial: "HC009E84",
|
||||
ip: "10.0.10.7",
|
||||
netmask: "255.255.255.0",
|
||||
gateway: "0.0.0.0",
|
||||
dns1: "0.0.0.0",
|
||||
dns2: "0.0.0.0",
|
||||
server: "10.0.10.101",
|
||||
serverPort: 3000,
|
||||
httpLanguage: 1,
|
||||
};
|
||||
const b = buildDeviceInfo(info);
|
||||
expect(b.length).toBe(96);
|
||||
expect(b.subarray(0, 8).toString("ascii")).toBe("HC009E84");
|
||||
expect(b.readUInt32LE(88)).toBe(3000);
|
||||
expect(parseDeviceInfo(b)).toEqual(info);
|
||||
});
|
||||
|
||||
it("decodes FirmwareInfo", () => {
|
||||
expect(parseFirmware(referenceFirmware())).toEqual({
|
||||
model: "doorqrcode",
|
||||
firmware: "ver_client1_1.1",
|
||||
chip: "v3s",
|
||||
hardware: "h42",
|
||||
serial: "HC002721",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// --- transport against the fake reader ------------------------------------
|
||||
|
||||
describe("DT-008 config transport", () => {
|
||||
it("readFirmware / readParams: unicast cmd 0 and 30, reply cmd+1", async () => {
|
||||
reader = await fakeReader();
|
||||
expect((await readFirmware("127.0.0.1", opts()))?.serial).toBe("HC002721");
|
||||
const p = await readParams("127.0.0.1", opts());
|
||||
expect(p?.server).toBe("10.0.10.204");
|
||||
expect(p?.outputType).toBe(3);
|
||||
expect(reader.singleDatagramFrames).toBe(0);
|
||||
});
|
||||
|
||||
it("writeSetting sends header THEN payload (two datagrams) and returns the status byte", async () => {
|
||||
reader = await fakeReader(referenceParams({ outputType: 6 })); // WG26, like park-2
|
||||
expect(await writeSetting("127.0.0.1", QR_CMD.outputType, QR_OUTPUT_HTTP, opts())).toBe(0);
|
||||
expect(reader.writes).toEqual([{ cmd: 6, value: 3 }]);
|
||||
expect(parseParams(reader.params).outputType).toBe(3);
|
||||
expect(reader.singleDatagramFrames).toBe(0);
|
||||
});
|
||||
|
||||
it("an out-of-range value is acknowledged with status 1 and changes nothing", async () => {
|
||||
reader = await fakeReader();
|
||||
expect(await writeSetting("127.0.0.1", QR_CMD.outputType, 42, opts())).toBe(1);
|
||||
expect(parseParams(reader.params).outputType).toBe(3);
|
||||
});
|
||||
|
||||
it("no reader → null after the retries (never throws)", async () => {
|
||||
reader = await fakeReader();
|
||||
const dead = { ...opts(), ports: { unicast: 1, broadcast: 1 } }; // nobody listens on :1
|
||||
expect(await exchange("127.0.0.1", QR_CMD.getParams, undefined, { ...dead, retries: 1 })).toBeNull();
|
||||
expect(await readParams("127.0.0.1", dead)).toBeNull();
|
||||
});
|
||||
|
||||
it("discoverReaders: cmd 2 to each broadcast, collects cmd 3 DeviceInfo, dedupes by serial", async () => {
|
||||
reader = await fakeReader();
|
||||
const found = await discoverReaders({ ...opts(), broadcasts: ["127.0.0.1", "127.0.0.1"] });
|
||||
expect(found).toHaveLength(1);
|
||||
expect(found[0]).toMatchObject({
|
||||
serial: "HC002721",
|
||||
ip: "10.0.10.12",
|
||||
server: "10.0.10.204",
|
||||
serverPort: 8080,
|
||||
replyFrom: "127.0.0.1",
|
||||
});
|
||||
});
|
||||
|
||||
it("discoverReaders with no broadcast targets returns [] without touching the network", async () => {
|
||||
expect(await discoverReaders({ broadcasts: [], timeoutMs: 50 })).toEqual([]);
|
||||
});
|
||||
|
||||
it("setNetwork: broadcast cmd 32; the matching reader applies it silently (re-read to confirm)", async () => {
|
||||
reader = await fakeReader();
|
||||
const before = parseParams(reader.params);
|
||||
await setNetwork(
|
||||
{ ...before, serial: "HC002721", server: "10.0.10.101", serverPort: 3000 },
|
||||
"127.0.0.1",
|
||||
opts(),
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const after = await readParams("127.0.0.1", opts());
|
||||
expect(after?.server).toBe("10.0.10.101");
|
||||
expect(after?.serverPort).toBe(3000);
|
||||
expect(after?.ip).toBe(before.ip); // network block preserved
|
||||
});
|
||||
|
||||
it("setNetwork for another serial is ignored by this reader", async () => {
|
||||
reader = await fakeReader();
|
||||
const before = parseParams(reader.params);
|
||||
await setNetwork({ ...before, serial: "HC00FFFF", server: "1.2.3.4", serverPort: 1 }, "127.0.0.1", opts());
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect((await readParams("127.0.0.1", opts()))?.server).toBe("10.0.10.204");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,483 @@
|
||||
import { createSocket, type Socket } from "node:dgram";
|
||||
import { networkInterfaces } from "node:os";
|
||||
|
||||
// Dingtian DT-008 QR/RFID reader — CONFIGURATION protocol (UDP). This is what the
|
||||
// vendor's Windows-only `QRCode_v1_6_5.exe` speaks for "Search device" / "Get parameter"
|
||||
// / the Set buttons; reversed in wiki/raw/dingtian_qr_linux/PROTOCOL.md and verified on
|
||||
// real readers (bench HC002721; park-2's two units read with it on 2026-10-08). Lets the
|
||||
// setup wizard FIND readers on the device VLAN and put a freshly assigned reader into HTTP
|
||||
// mode pointing at this booth — instead of a Windows laptop on site. The scan push itself
|
||||
// (HTTP GET /qa/mcardsea.<ext>) is a different protocol, handled by routes/qr-reader.ts.
|
||||
//
|
||||
// Frame (both directions, little-endian):
|
||||
// 'XXXX' | id u32 | cmd u32 | len u32 | checksum u8 (0xFF − Σpayload) | payload
|
||||
// Even cmd = request/write, reply = cmd + 1. QUIRK: the reader only accepts a write when
|
||||
// the 17-byte header and the payload arrive as TWO datagrams (header first); a single
|
||||
// datagram is silently ignored. Replies come as one datagram, from an arbitrary source
|
||||
// port. Reader listens on 24680 (unicast: 0 firmware, 30 params, every field write) and
|
||||
// 24582 (broadcast: 2 search, 32 set-network). set-network is applied but NOT acknowledged
|
||||
// by the real reader — verify it by re-reading the params (cmd 30).
|
||||
//
|
||||
// SECURITY: unauthenticated UDP, like the relay board — the reader sits on the isolated
|
||||
// device VLAN reachable only by the host (wiki/concepts/network-isolation.md).
|
||||
|
||||
export const QR_PORT_UNICAST = 24680;
|
||||
export const QR_PORT_BROADCAST = 24582;
|
||||
const MAGIC = Buffer.from("XXXX", "ascii");
|
||||
const HEADER_LEN = 17;
|
||||
const PARAMS_LEN = 720;
|
||||
const DEVICE_INFO_LEN = 96;
|
||||
const FIRMWARE_LEN = 64;
|
||||
|
||||
/** Command numbers (requests; the reply is cmd + 1). */
|
||||
export const QR_CMD = {
|
||||
firmware: 0,
|
||||
search: 2,
|
||||
outputType: 6,
|
||||
cardInputFormat: 8,
|
||||
getParams: 30,
|
||||
setNetwork: 32,
|
||||
} as const;
|
||||
|
||||
/** `output type` values on the wire (cmd 6 / Params 0x198). Only HTTP contacts the booth;
|
||||
* in every other mode the reader beeps locally and the scan goes elsewhere. */
|
||||
export const QR_OUTPUT_HTTP = 3;
|
||||
export const QR_OUTPUT_TYPES: Record<number, string> = {
|
||||
1: "USB virtual keyboard",
|
||||
2: "USB virtual serial port",
|
||||
3: "HTTP",
|
||||
4: "MQTT",
|
||||
5: "RS232",
|
||||
6: "WG26",
|
||||
7: "WG34",
|
||||
8: "RS485",
|
||||
9: "AC Output",
|
||||
10: "TCP",
|
||||
};
|
||||
export const QR_CARD_INPUT_FORMATS: Record<number, string> = {
|
||||
1: "6H",
|
||||
2: "8H",
|
||||
3: "8H10D",
|
||||
4: "6H10D",
|
||||
5: "2H3D+4H5D",
|
||||
};
|
||||
export const QR_HTTP_LANGUAGES: Record<number, string> = {
|
||||
0: "PHP",
|
||||
1: "JSP",
|
||||
2: "C#",
|
||||
3: "ASP",
|
||||
4: "CGI",
|
||||
};
|
||||
|
||||
export function outputTypeName(v: number): string {
|
||||
return QR_OUTPUT_TYPES[v] ?? `unknown (${v})`;
|
||||
}
|
||||
|
||||
export interface QrOptions {
|
||||
/** Per-attempt reply wait. */
|
||||
readonly timeoutMs?: number;
|
||||
/** Extra attempts after the first (the exe never retries; UDP can drop). */
|
||||
readonly retries?: number;
|
||||
/** Port overrides (tests run a fake reader on loopback ephemeral ports). */
|
||||
readonly ports?: { readonly unicast?: number; readonly broadcast?: number };
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 1500;
|
||||
const DEFAULT_RETRIES = 1;
|
||||
|
||||
// --- framing ---------------------------------------------------------------
|
||||
|
||||
export function checksum(payload: Buffer): number {
|
||||
let sum = 0;
|
||||
for (const b of payload) sum += b;
|
||||
return (0xff - sum) & 0xff;
|
||||
}
|
||||
|
||||
/** The 17-byte header for `cmd` + `payload` (the payload is sent as its own datagram). */
|
||||
export function frameHeader(cmd: number, payload: Buffer = Buffer.alloc(0), id = 0): Buffer {
|
||||
const h = Buffer.alloc(HEADER_LEN);
|
||||
MAGIC.copy(h, 0);
|
||||
h.writeUInt32LE(id >>> 0, 4);
|
||||
h.writeUInt32LE(cmd >>> 0, 8);
|
||||
h.writeUInt32LE(payload.length, 12);
|
||||
h.writeUInt8(checksum(payload), 16);
|
||||
return h;
|
||||
}
|
||||
|
||||
export interface QrFrame {
|
||||
readonly id: number;
|
||||
readonly cmd: number;
|
||||
readonly payload: Buffer;
|
||||
}
|
||||
|
||||
/** Parse a reply datagram (header + payload in one). null = not a valid frame. */
|
||||
export function parseFrame(datagram: Buffer): QrFrame | null {
|
||||
if (datagram.length < HEADER_LEN || !datagram.subarray(0, 4).equals(MAGIC)) return null;
|
||||
const id = datagram.readUInt32LE(4);
|
||||
const cmd = datagram.readUInt32LE(8);
|
||||
const len = datagram.readUInt32LE(12);
|
||||
const payload = datagram.subarray(HEADER_LEN, HEADER_LEN + len);
|
||||
if (payload.length !== len || checksum(payload) !== datagram.readUInt8(16)) return null;
|
||||
return { id, cmd, payload };
|
||||
}
|
||||
|
||||
// --- field codecs ----------------------------------------------------------
|
||||
|
||||
/** IPv4 as the reader stores it: little-endian u32 = the dotted bytes REVERSED. */
|
||||
export function ipToBytes(ip: string): Buffer {
|
||||
const parts = ip.split(".").map(Number);
|
||||
if (parts.length !== 4 || parts.some((o) => !Number.isInteger(o) || o < 0 || o > 255)) {
|
||||
throw new Error(`not an IPv4 address: ${ip}`);
|
||||
}
|
||||
return Buffer.from(parts.reverse());
|
||||
}
|
||||
|
||||
export function bytesToIp(b: Buffer, off: number): string {
|
||||
return `${b[off + 3]}.${b[off + 2]}.${b[off + 1]}.${b[off]}`;
|
||||
}
|
||||
|
||||
function cstr(b: Buffer, off: number, len: number): string {
|
||||
const s = b.subarray(off, off + len);
|
||||
const nul = s.indexOf(0);
|
||||
return s.subarray(0, nul < 0 ? s.length : nul).toString("utf8");
|
||||
}
|
||||
|
||||
function putStr(b: Buffer, off: number, len: number, s: string): void {
|
||||
b.fill(0, off, off + len);
|
||||
// Leave the last byte NUL (the exe caps the 48-byte server field at 47 chars).
|
||||
b.write(s, off, len - 1, "utf8");
|
||||
}
|
||||
|
||||
// --- blocks ----------------------------------------------------------------
|
||||
|
||||
/** 96-byte DeviceInfo: the search reply (cmd 3) and the set-network payload (cmd 32). */
|
||||
export interface QrDeviceInfo {
|
||||
readonly serial: string;
|
||||
readonly ip: string;
|
||||
readonly netmask: string;
|
||||
readonly gateway: string;
|
||||
readonly dns1: string;
|
||||
readonly dns2: string;
|
||||
/** Hostname or IP the reader pushes scans to (factory: "ipc.fondvision.com"). */
|
||||
readonly server: string;
|
||||
readonly serverPort: number;
|
||||
/** 0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI — only picks the push URL's extension. */
|
||||
readonly httpLanguage: number;
|
||||
}
|
||||
|
||||
export function parseDeviceInfo(b: Buffer): QrDeviceInfo {
|
||||
if (b.length < DEVICE_INFO_LEN) throw new Error(`DeviceInfo too short: ${b.length}`);
|
||||
return {
|
||||
serial: cstr(b, 0, 20),
|
||||
ip: bytesToIp(b, 20),
|
||||
netmask: bytesToIp(b, 24),
|
||||
gateway: bytesToIp(b, 28),
|
||||
dns1: bytesToIp(b, 32),
|
||||
dns2: bytesToIp(b, 36),
|
||||
server: cstr(b, 40, 48),
|
||||
serverPort: b.readUInt32LE(88),
|
||||
httpLanguage: b.readUInt32LE(92),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDeviceInfo(info: QrDeviceInfo): Buffer {
|
||||
const b = Buffer.alloc(DEVICE_INFO_LEN);
|
||||
putStr(b, 0, 20, info.serial);
|
||||
ipToBytes(info.ip).copy(b, 20);
|
||||
ipToBytes(info.netmask).copy(b, 24);
|
||||
ipToBytes(info.gateway).copy(b, 28);
|
||||
ipToBytes(info.dns1).copy(b, 32);
|
||||
ipToBytes(info.dns2).copy(b, 36);
|
||||
putStr(b, 40, 48, info.server);
|
||||
b.writeUInt32LE(info.serverPort >>> 0, 88);
|
||||
b.writeUInt32LE(info.httpLanguage >>> 0, 92);
|
||||
return b;
|
||||
}
|
||||
|
||||
/** 64-byte FirmwareInfo (reply 1). */
|
||||
export interface QrFirmware {
|
||||
readonly model: string; // "doorqrcode"
|
||||
readonly firmware: string; // "ver_client1_1.1"
|
||||
readonly chip: string; // "v3s"
|
||||
readonly hardware: string; // "h42"
|
||||
readonly serial: string; // "HC002721"
|
||||
}
|
||||
|
||||
export function parseFirmware(b: Buffer): QrFirmware {
|
||||
if (b.length < FIRMWARE_LEN) throw new Error(`FirmwareInfo too short: ${b.length}`);
|
||||
return {
|
||||
model: cstr(b, 0, 16),
|
||||
firmware: cstr(b, 16, 16),
|
||||
chip: cstr(b, 32, 8),
|
||||
hardware: cstr(b, 40, 8),
|
||||
serial: cstr(b, 48, 16),
|
||||
};
|
||||
}
|
||||
|
||||
/** The 720-byte parameter struct (reply 31). Only the fields the exe shows are decoded. */
|
||||
export interface QrParams {
|
||||
readonly dhcp: number;
|
||||
readonly ip: string;
|
||||
readonly netmask: string;
|
||||
readonly gateway: string;
|
||||
readonly dns1: string;
|
||||
readonly dns2: string;
|
||||
readonly server: string;
|
||||
readonly serverPort: number;
|
||||
readonly httpLanguage: number;
|
||||
/** See QR_OUTPUT_TYPES; 3 = HTTP. */
|
||||
readonly outputType: number;
|
||||
/** See QR_CARD_INPUT_FORMATS; 1 = 6H. */
|
||||
readonly cardInputFormat: number;
|
||||
readonly lastAddEnter: number;
|
||||
readonly lastAddNewline: number;
|
||||
readonly qrPrefix: string;
|
||||
readonly qrSuffix: string;
|
||||
readonly restartInterval: number;
|
||||
readonly workMode: number;
|
||||
readonly buzzer: number;
|
||||
readonly highPulseUs: number;
|
||||
readonly lowPulseUs: number;
|
||||
readonly baudrate: number;
|
||||
readonly dataBits: number;
|
||||
readonly stopBits: number;
|
||||
readonly parity: number;
|
||||
readonly qrOutputFormat: number;
|
||||
readonly fillLight: number;
|
||||
readonly cardOutputFormat: number;
|
||||
readonly cardPrefix: string;
|
||||
readonly cardSuffix: string;
|
||||
}
|
||||
|
||||
export function parseParams(b: Buffer): QrParams {
|
||||
if (b.length < PARAMS_LEN) throw new Error(`Params too short: ${b.length}`);
|
||||
return {
|
||||
dhcp: b.readUInt32LE(0x000),
|
||||
ip: bytesToIp(b, 0x004),
|
||||
netmask: bytesToIp(b, 0x008),
|
||||
gateway: bytesToIp(b, 0x00c),
|
||||
dns1: bytesToIp(b, 0x010),
|
||||
dns2: bytesToIp(b, 0x014),
|
||||
server: cstr(b, 0x018, 48),
|
||||
serverPort: b.readUInt32LE(0x048),
|
||||
httpLanguage: b.readUInt32LE(0x04c),
|
||||
outputType: b.readUInt8(0x198),
|
||||
cardInputFormat: b.readUInt8(0x19c),
|
||||
lastAddEnter: b.readUInt8(0x1a0),
|
||||
lastAddNewline: b.readUInt8(0x1a1),
|
||||
qrPrefix: cstr(b, 0x1a8, 32),
|
||||
qrSuffix: cstr(b, 0x1cc, 32),
|
||||
restartInterval: b.readUInt32LE(0x1ec),
|
||||
workMode: b.readUInt32LE(0x1f0),
|
||||
buzzer: b.readUInt32LE(0x1f8),
|
||||
highPulseUs: b.readUInt32LE(0x1fc) * 100,
|
||||
lowPulseUs: b.readUInt32LE(0x200) * 100,
|
||||
baudrate: b.readUInt32LE(0x204),
|
||||
dataBits: b.readUInt32LE(0x208),
|
||||
stopBits: b.readUInt32LE(0x20c),
|
||||
parity: b.readUInt32LE(0x210),
|
||||
qrOutputFormat: b.readUInt32LE(0x214),
|
||||
fillLight: b.readUInt32LE(0x218),
|
||||
cardOutputFormat: b.readUInt32LE(0x288),
|
||||
cardPrefix: cstr(b, 0x290, 32),
|
||||
cardSuffix: cstr(b, 0x2b0, 32),
|
||||
};
|
||||
}
|
||||
|
||||
// --- transport -------------------------------------------------------------
|
||||
|
||||
function openSocket(): Promise<Socket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const s = createSocket({ type: "udp4", reuseAddr: true });
|
||||
s.once("error", reject);
|
||||
s.bind(0, "0.0.0.0", () => {
|
||||
s.removeListener("error", reject);
|
||||
resolve(s);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function sendTo(sock: Socket, host: string, port: number, buf: Buffer): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
sock.send(buf, port, host, (err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
/** Send `cmd` the way the exe does: the header datagram, then the payload datagram. */
|
||||
async function sendCommand(sock: Socket, host: string, port: number, cmd: number, payload: Buffer): Promise<void> {
|
||||
await sendTo(sock, host, port, frameHeader(cmd, payload));
|
||||
if (payload.length) await sendTo(sock, host, port, payload);
|
||||
}
|
||||
|
||||
/** Collect reply frames matching `want` for up to `ms`, calling `onFrame` for each;
|
||||
* resolves early when `onFrame` returns true (= done). */
|
||||
function collect(
|
||||
sock: Socket,
|
||||
ms: number,
|
||||
onFrame: (f: QrFrame, from: string) => boolean,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const done = () => {
|
||||
clearTimeout(timer);
|
||||
sock.removeListener("message", onMsg);
|
||||
resolve();
|
||||
};
|
||||
const onMsg = (msg: Buffer, rinfo: { address: string }) => {
|
||||
const f = parseFrame(msg);
|
||||
if (f && onFrame(f, rinfo.address)) done();
|
||||
};
|
||||
const timer = setTimeout(done, ms);
|
||||
sock.on("message", onMsg);
|
||||
});
|
||||
}
|
||||
|
||||
/** Unicast `cmd` to the reader and await the `cmd + 1` reply payload; null = no reply. */
|
||||
export async function exchange(
|
||||
host: string,
|
||||
cmd: number,
|
||||
payload: Buffer = Buffer.alloc(0),
|
||||
opts: QrOptions = {},
|
||||
): Promise<Buffer | null> {
|
||||
const port = opts.ports?.unicast ?? QR_PORT_UNICAST;
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const retries = opts.retries ?? DEFAULT_RETRIES;
|
||||
const sock = await openSocket();
|
||||
try {
|
||||
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||
await sendCommand(sock, host, port, cmd, payload);
|
||||
let got: Buffer | null = null;
|
||||
await collect(sock, timeoutMs, (f) => {
|
||||
if (f.cmd !== cmd + 1) return false;
|
||||
got = f.payload;
|
||||
return true;
|
||||
});
|
||||
if (got) return got;
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
sock.close();
|
||||
}
|
||||
}
|
||||
|
||||
export async function readFirmware(host: string, opts?: QrOptions): Promise<QrFirmware | null> {
|
||||
const b = await exchange(host, QR_CMD.firmware, undefined, opts);
|
||||
return b && b.length >= FIRMWARE_LEN ? parseFirmware(b) : null;
|
||||
}
|
||||
|
||||
export async function readParams(host: string, opts?: QrOptions): Promise<QrParams | null> {
|
||||
const b = await exchange(host, QR_CMD.getParams, undefined, opts);
|
||||
return b && b.length >= PARAMS_LEN ? parseParams(b) : null;
|
||||
}
|
||||
|
||||
/** Write one u32 setting (cmd 6 output type, 8 card input format, 18 work mode, 22
|
||||
* buzzer, …). Resolves the reader's status byte: 0 = applied (immediately, no reboot),
|
||||
* 1 = rejected (out of range); null = no acknowledgement. */
|
||||
export async function writeSetting(
|
||||
host: string,
|
||||
cmd: number,
|
||||
value: number,
|
||||
opts?: QrOptions,
|
||||
): Promise<number | null> {
|
||||
const payload = Buffer.alloc(4);
|
||||
payload.writeUInt32LE(value >>> 0, 0);
|
||||
const b = await exchange(host, cmd, payload, opts);
|
||||
return b && b.length >= 1 ? b.readUInt8(0) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the reader's network block (IP/netmask/gateway/DNS, push server + port, URL
|
||||
* language) — cmd 32, an L2 BROADCAST that only the reader whose serial matches applies.
|
||||
* The real reader applies it without replying, so this resolves after sending; the caller
|
||||
* must re-read the params to confirm. `broadcast` is the subnet-directed address
|
||||
* (e.g. 10.0.10.255 — see subnetBroadcastFor); the global 255.255.255.255 is refused by
|
||||
* the kernel on some hosts (EACCES) and is not what the exe sends.
|
||||
*/
|
||||
export async function setNetwork(info: QrDeviceInfo, broadcast: string, opts: QrOptions = {}): Promise<void> {
|
||||
const port = opts.ports?.broadcast ?? QR_PORT_BROADCAST;
|
||||
const sock = await openSocket();
|
||||
try {
|
||||
sock.setBroadcast(true);
|
||||
await sendCommand(sock, broadcast, port, QR_CMD.setNetwork, buildDeviceInfo(info));
|
||||
} finally {
|
||||
sock.close();
|
||||
}
|
||||
}
|
||||
|
||||
export interface DiscoveredReader extends QrDeviceInfo {
|
||||
/** Address the reply came from (normally = ip). */
|
||||
readonly replyFrom: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the LAN: cmd 2 to every subnet-directed broadcast (one per local IPv4 interface
|
||||
* unless `broadcasts` is given), collect cmd 3 replies for `timeoutMs`, dedupe by serial.
|
||||
* Readers must share an L2 segment with the host — fine on the booth (host network) and
|
||||
* the device VLAN; impossible from a bridged dev container or across Netbird.
|
||||
*/
|
||||
export async function discoverReaders(
|
||||
opts: QrOptions & { readonly broadcasts?: readonly string[] } = {},
|
||||
): Promise<DiscoveredReader[]> {
|
||||
const port = opts.ports?.broadcast ?? QR_PORT_BROADCAST;
|
||||
const timeoutMs = opts.timeoutMs ?? 2000;
|
||||
const targets = opts.broadcasts ?? subnetBroadcasts();
|
||||
if (targets.length === 0) return [];
|
||||
const sock = await openSocket();
|
||||
const found = new Map<string, DiscoveredReader>();
|
||||
try {
|
||||
sock.setBroadcast(true);
|
||||
for (const b of targets) {
|
||||
// One unreachable interface must not abort the whole scan.
|
||||
await sendCommand(sock, b, port, QR_CMD.search, Buffer.alloc(0)).catch(() => {});
|
||||
}
|
||||
await collect(sock, timeoutMs, (f, from) => {
|
||||
if (f.cmd === QR_CMD.search + 1 && f.payload.length >= DEVICE_INFO_LEN) {
|
||||
const info = parseDeviceInfo(f.payload);
|
||||
found.set(info.serial, { ...info, replyFrom: from });
|
||||
}
|
||||
return false; // keep collecting until the deadline
|
||||
});
|
||||
} finally {
|
||||
sock.close();
|
||||
}
|
||||
return [...found.values()];
|
||||
}
|
||||
|
||||
// --- local network helpers -------------------------------------------------
|
||||
|
||||
function parseV4(s: string): number[] | null {
|
||||
const p = s.split(".").map(Number);
|
||||
return p.length === 4 && p.every((o) => Number.isInteger(o) && o >= 0 && o <= 255) ? p : null;
|
||||
}
|
||||
|
||||
/** Subnet-directed broadcast addresses of every non-loopback local IPv4 interface. */
|
||||
export function subnetBroadcasts(): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const ifaces of Object.values(networkInterfaces())) {
|
||||
for (const i of ifaces ?? []) {
|
||||
if (i.family !== "IPv4" || i.internal) continue;
|
||||
const a = parseV4(i.address);
|
||||
const m = parseV4(i.netmask);
|
||||
if (!a || !m) continue;
|
||||
out.add(a.map((o, k) => (o | (~m[k]! & 0xff)) & 0xff).join("."));
|
||||
}
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** The subnet-directed broadcast of the local interface whose subnet contains `host`;
|
||||
* null when no directly attached interface does (set-network can't reach it then). */
|
||||
export function subnetBroadcastFor(host: string): string | null {
|
||||
const h = parseV4(host);
|
||||
if (!h) return null;
|
||||
for (const ifaces of Object.values(networkInterfaces())) {
|
||||
for (const i of ifaces ?? []) {
|
||||
if (i.family !== "IPv4" || i.internal) continue;
|
||||
const a = parseV4(i.address);
|
||||
const m = parseV4(i.netmask);
|
||||
if (!a || !m) continue;
|
||||
const same = h.every((o, k) => (o & m[k]!) === (a[k]! & m[k]!));
|
||||
if (same) return a.map((o, k) => (o | (~m[k]! & 0xff)) & 0xff).join(".");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -41,3 +41,219 @@ describe("QR reader healthCheck (ICMP liveness)", () => {
|
||||
expect(hostField!.required).toBe(false); // operation is push-by-serial; IP is monitor-only
|
||||
});
|
||||
});
|
||||
|
||||
// --- DT-008 configuration over the vendor UDP protocol -----------------------------
|
||||
// The protocol layer is mocked (it has its own fake-reader tests in
|
||||
// dingtian-qr-config.test.ts); here we check what the ADAPTER decides: which
|
||||
// preconditions it reports, what it writes to fix them, and how it points the reader at
|
||||
// the booth. Scenario values are park-2's real readers (WG26, server 10.0.10.101:3000).
|
||||
|
||||
const qr = vi.hoisted(() => ({
|
||||
readFirmware: vi.fn(),
|
||||
readParams: vi.fn(),
|
||||
writeSetting: vi.fn(),
|
||||
setNetwork: vi.fn(),
|
||||
subnetBroadcastFor: vi.fn(),
|
||||
discoverReaders: vi.fn(),
|
||||
}));
|
||||
vi.mock("./dingtian-qr-config.js", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("./dingtian-qr-config.js")>();
|
||||
return { ...real, ...qr };
|
||||
});
|
||||
|
||||
const fw = { model: "doorqrcode", firmware: "ver_client1_1.1", chip: "v3s", hardware: "h42", serial: "HC009E84" };
|
||||
const park2Params = {
|
||||
dhcp: 0,
|
||||
ip: "10.0.10.7",
|
||||
netmask: "255.255.255.0",
|
||||
gateway: "0.0.0.0",
|
||||
dns1: "0.0.0.0",
|
||||
dns2: "0.0.0.0",
|
||||
server: "10.0.10.101",
|
||||
serverPort: 3000,
|
||||
httpLanguage: 1,
|
||||
outputType: 6, // WG26 — the park-2 fault
|
||||
cardInputFormat: 1,
|
||||
lastAddEnter: 1,
|
||||
lastAddNewline: 0,
|
||||
qrPrefix: "",
|
||||
qrSuffix: "",
|
||||
restartInterval: 1,
|
||||
workMode: 0,
|
||||
buzzer: 0,
|
||||
highPulseUs: 2000,
|
||||
lowPulseUs: 400,
|
||||
baudrate: 9600,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
parity: 2,
|
||||
qrOutputFormat: 4,
|
||||
fillLight: 1,
|
||||
cardOutputFormat: 1,
|
||||
cardPrefix: "",
|
||||
cardSuffix: "",
|
||||
};
|
||||
|
||||
type Configurable = {
|
||||
checkPreconditions(): Promise<{ ok: boolean; issues: { key: string; fixable: boolean; message: string }[] }>;
|
||||
fixPreconditions(): Promise<{ ok: boolean; issues: { key: string }[] }>;
|
||||
configureInputPush(o: { host: string; port: number; pathBase: string; auth: { user: string; password: string } }): Promise<void>;
|
||||
usesPushAuth?: boolean;
|
||||
};
|
||||
const reader = (cfg: Record<string, string>) => dingtianQrReaderDriver.create(cfg) as unknown as Configurable;
|
||||
const push = { pathBase: "/x", auth: { user: "u", password: "p" } };
|
||||
|
||||
afterEach(() => {
|
||||
for (const m of Object.values(qr)) m.mockReset();
|
||||
});
|
||||
|
||||
describe("DT-008 preconditions (reader must be in HTTP mode, serial must match)", () => {
|
||||
it("WG26 → one FIXABLE issue naming the mode and the current target", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue(park2Params);
|
||||
const r = await reader({ serial: "HC009E84", host: "10.0.10.7" }).checkPreconditions();
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.issues).toHaveLength(1);
|
||||
expect(r.issues[0]).toMatchObject({ key: "output-type", fixable: true });
|
||||
expect(r.issues[0]!.message).toMatch(/WG26.*HTTP.*10\.0\.10\.101:3000/);
|
||||
});
|
||||
|
||||
it("typed serial ≠ reported serial → UNFIXABLE (scans would land on the wrong device)", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
|
||||
const r = await reader({ serial: "HC00D3B0", host: "10.0.10.7" }).checkPreconditions();
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.issues).toEqual([expect.objectContaining({ key: "serial-mismatch", fixable: false })]);
|
||||
expect(r.issues[0]!.message).toContain("HC009E84");
|
||||
});
|
||||
|
||||
it("serial comparison ignores case/whitespace; HTTP mode → ok", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
|
||||
expect(await reader({ serial: " hc009e84 ", host: "10.0.10.7" }).checkPreconditions()).toEqual({ ok: true, issues: [] });
|
||||
});
|
||||
|
||||
it("no IP → ok with no issues (nothing to talk to; legacy vendor-tool setup)", async () => {
|
||||
expect(await reader({ serial: "HC009E84" }).checkPreconditions()).toEqual({ ok: true, issues: [] });
|
||||
expect(qr.readParams).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("IP set but no UDP answer → UNFIXABLE 'unreachable' (save fails with a clear message)", async () => {
|
||||
qr.readFirmware.mockResolvedValue(null);
|
||||
qr.readParams.mockResolvedValue(null);
|
||||
const r = await reader({ serial: "HC009E84", host: "10.0.10.9" }).checkPreconditions();
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.issues[0]).toMatchObject({ key: "unreachable", fixable: false });
|
||||
expect(r.issues[0]!.message).toMatch(/10\.0\.10\.9.*UDP 24680/);
|
||||
});
|
||||
|
||||
it("fixPreconditions writes cmd 6 = 3 (HTTP) once and re-checks", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValueOnce(park2Params).mockResolvedValue({ ...park2Params, outputType: 3 });
|
||||
qr.writeSetting.mockResolvedValue(0);
|
||||
const r = await reader({ serial: "HC009E84", host: "10.0.10.7" }).fixPreconditions();
|
||||
expect(qr.writeSetting).toHaveBeenCalledTimes(1);
|
||||
expect(qr.writeSetting).toHaveBeenCalledWith("10.0.10.7", 6, 3);
|
||||
expect(r.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("fixPreconditions: a rejected / unacknowledged write throws (no silent 'fixed')", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue(park2Params);
|
||||
qr.writeSetting.mockResolvedValue(1);
|
||||
await expect(reader({ serial: "HC009E84", host: "10.0.10.7" }).fixPreconditions()).rejects.toThrow(/status 1/);
|
||||
qr.writeSetting.mockResolvedValue(null);
|
||||
await expect(reader({ serial: "HC009E84", host: "10.0.10.7" }).fixPreconditions()).rejects.toThrow(/no acknowledgement/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DT-008 configureInputPush (point the reader at this booth)", () => {
|
||||
it("already pointing at us → no write at all", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
|
||||
await reader({ serial: "HC009E84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 3000, ...push });
|
||||
expect(qr.setNetwork).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("different target → set-network with the READER's serial + its own network block, then verified by polling (reader is silent right after)", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams
|
||||
.mockResolvedValueOnce({ ...park2Params, outputType: 3, server: "10.0.10.203", serverPort: 8080 })
|
||||
.mockResolvedValueOnce(null) // re-initialising its network: no answer to the first poll
|
||||
.mockResolvedValue({ ...park2Params, outputType: 3, server: "10.0.10.101", serverPort: 3000 });
|
||||
qr.subnetBroadcastFor.mockReturnValue("10.0.10.255");
|
||||
qr.setNetwork.mockResolvedValue(undefined);
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const p = reader({ serial: "hc009e84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 3000, ...push });
|
||||
await vi.advanceTimersByTimeAsync(3000); // poll 1: silent, poll 2: new target
|
||||
await p;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
expect(qr.setNetwork).toHaveBeenCalledWith(
|
||||
{
|
||||
serial: "HC009E84", // as REPORTED, not as typed
|
||||
ip: "10.0.10.7",
|
||||
netmask: "255.255.255.0",
|
||||
gateway: "0.0.0.0",
|
||||
dns1: "0.0.0.0",
|
||||
dns2: "0.0.0.0",
|
||||
server: "10.0.10.101",
|
||||
serverPort: 3000,
|
||||
httpLanguage: 1,
|
||||
},
|
||||
"10.0.10.255",
|
||||
);
|
||||
});
|
||||
|
||||
it("reader did not apply the new target → throws (set-network has no ack; the re-read is the proof)", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3, server: "10.0.10.203", serverPort: 8080 });
|
||||
qr.subnetBroadcastFor.mockReturnValue("10.0.10.255");
|
||||
qr.setNetwork.mockResolvedValue(undefined);
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const p = reader({ serial: "HC009E84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 3000, ...push });
|
||||
const expectation = expect(p).rejects.toThrow(/did not apply server 10\.0\.10\.101:3000 \(still 10\.0\.10\.203:8080\)/);
|
||||
await vi.advanceTimersByTimeAsync(15_000); // polls once a second until the 12 s deadline
|
||||
await expectation;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("reader not on a directly attached subnet → throws before broadcasting", async () => {
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue({ ...park2Params, outputType: 3 });
|
||||
qr.subnetBroadcastFor.mockReturnValue(null);
|
||||
await expect(
|
||||
reader({ serial: "HC009E84", host: "10.0.10.7" }).configureInputPush({ host: "10.0.10.101", port: 80, ...push }),
|
||||
).rejects.toThrow(/directly attached subnet/);
|
||||
expect(qr.setNetwork).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("declares usesPushAuth=false and pushesToBackend (the scan GET is identified by serial)", () => {
|
||||
expect(reader({ serial: "x" }).usesPushAuth).toBe(false);
|
||||
expect(dingtianQrReaderDriver.pushesToBackend).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DT-008 discover (LAN search → wizard rows)", () => {
|
||||
it("maps each reader to serial/host config + mode/target info", async () => {
|
||||
qr.discoverReaders.mockResolvedValue([
|
||||
{ serial: "HC009E84", ip: "10.0.10.7", netmask: "255.255.255.0", gateway: "0.0.0.0", dns1: "0.0.0.0", dns2: "0.0.0.0", server: "10.0.10.101", serverPort: 3000, httpLanguage: 1, replyFrom: "10.0.10.7" },
|
||||
]);
|
||||
qr.readFirmware.mockResolvedValue(fw);
|
||||
qr.readParams.mockResolvedValue(park2Params);
|
||||
const found = await (dingtianQrReaderDriver as unknown as { discover(): Promise<unknown[]> }).discover();
|
||||
expect(found).toEqual([
|
||||
{
|
||||
id: "HC009E84",
|
||||
label: "HC009E84 @ 10.0.10.7",
|
||||
config: { serial: "HC009E84", host: "10.0.10.7" },
|
||||
info: { output: "WG26", server: "10.0.10.101:3000", url: "/qa/mcardsea.jsp", cardFormat: "6H", firmware: "ver_client1_1.1" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,31 @@
|
||||
import type { DeviceHealth, ReaderDevice, ReaderEvent } from "../interfaces.js";
|
||||
import type { DeviceConfig, ReaderDriver } from "../registry.js";
|
||||
import type {
|
||||
DeviceHealth,
|
||||
PreconditionDevice,
|
||||
PreconditionIssue,
|
||||
PreconditionResult,
|
||||
PushConfig,
|
||||
PushConfigurableDevice,
|
||||
ReaderDevice,
|
||||
ReaderEvent,
|
||||
} from "../interfaces.js";
|
||||
import type { DeviceConfig, DiscoverableDriver, DiscoveredDevice, ReaderDriver } from "../registry.js";
|
||||
import { hostField, portField, stubLog } from "./common.js";
|
||||
import {
|
||||
QR_CARD_INPUT_FORMATS,
|
||||
QR_CMD,
|
||||
QR_HTTP_LANGUAGES,
|
||||
QR_OUTPUT_HTTP,
|
||||
QR_PORT_UNICAST,
|
||||
discoverReaders,
|
||||
outputTypeName,
|
||||
readFirmware,
|
||||
readParams,
|
||||
setNetwork,
|
||||
subnetBroadcastFor,
|
||||
writeSetting,
|
||||
type QrFirmware,
|
||||
type QrParams,
|
||||
} from "./dingtian-qr-config.js";
|
||||
import { icmpPing } from "./icmp.js";
|
||||
|
||||
// Reader drivers (RF / optical). Two integration paths: Wiegand reads reach the
|
||||
@@ -78,33 +103,201 @@ export const tcpipReaderDriver: ReaderDriver = {
|
||||
// Dingtian DT-008 QR/RFID access reader (same vendor as the relay board). Scans QR/barcode
|
||||
// + ID/IC/NFC cards. A PUSH device: on each scan it HTTP-GETs our backend (/qa/mcardsea.<ext>)
|
||||
// carrying its serial (cjihao); the backend resolves the lane by matching that serial to this
|
||||
// device's `serial` config, decides, and replies the verdict (drives the beep). No host-side
|
||||
// connection — the adapter is a stub; the real integration is the HTTP endpoint (apps/server
|
||||
// routes/qr-reader.ts). Interfaces: Wiegand 26/34, TCP/IP, USB, RS485. See
|
||||
// wiki/entities/dingtian-dt008-reader.md.
|
||||
export const dingtianQrReaderDriver: ReaderDriver = {
|
||||
// device's `serial` config, decides, and replies the verdict (drives the beep). The scan path
|
||||
// is the HTTP endpoint (apps/server routes/qr-reader.ts) — this adapter never receives reads.
|
||||
//
|
||||
// What the adapter DOES do is CONFIGURE the reader over the vendor's UDP protocol
|
||||
// (dingtian-qr-config.ts), the job that used to need the Windows exe on site:
|
||||
// - discover(): find readers on the device VLAN (serial, IP, current push target);
|
||||
// - preconditions: the reader must be in HTTP output mode — in WG26/RS232/USB… it beeps
|
||||
// locally and NEVER contacts the booth (park-2, 2026-10-08: both readers in WG26, every
|
||||
// enrolment "beeped but captured nothing"); and the serial typed must be the serial the
|
||||
// reader reports, else scans resolve to the wrong device row;
|
||||
// - configureInputPush(): point the reader's server/port at THIS booth (set-network).
|
||||
// All of it needs the reader's IP (unicast). Without an IP the adapter configures nothing
|
||||
// and the admin must use the vendor tool / scripts/dingtian_qr.py.
|
||||
// See wiki/entities/dingtian-dt008-reader.md, wiki/sources/dingtian-qr-linux-tool.md.
|
||||
class DingtianQrReader extends StubReader implements PreconditionDevice, PushConfigurableDevice {
|
||||
/** The scan GET carries no credentials — identity is the serial. */
|
||||
readonly usesPushAuth = false;
|
||||
|
||||
#host(): string {
|
||||
return this.config.host ? String(this.config.host).trim() : "";
|
||||
}
|
||||
|
||||
#serial(): string {
|
||||
return String(this.config.serial ?? "").trim();
|
||||
}
|
||||
|
||||
/** Read firmware + params; throws a precise message when the reader doesn't answer. */
|
||||
async #read(host: string): Promise<{ fw: QrFirmware; params: QrParams }> {
|
||||
const [fw, params] = await Promise.all([readFirmware(host), readParams(host)]);
|
||||
if (!fw || !params) {
|
||||
throw new Error(
|
||||
`reader at ${host} did not answer on UDP ${QR_PORT_UNICAST} — check the IP (is it on the device VLAN?), or clear the IP to save without configuring the reader`,
|
||||
);
|
||||
}
|
||||
return { fw, params };
|
||||
}
|
||||
|
||||
#issues(fw: QrFirmware, params: QrParams): PreconditionIssue[] {
|
||||
const issues: PreconditionIssue[] = [];
|
||||
const typed = this.#serial();
|
||||
if (typed && typed.toUpperCase() !== fw.serial.toUpperCase()) {
|
||||
issues.push({
|
||||
key: "serial-mismatch",
|
||||
fixable: false,
|
||||
message: `the reader at ${this.#host()} reports serial ${fw.serial}, not ${typed} — scans would resolve to the wrong device; enter ${fw.serial}`,
|
||||
});
|
||||
}
|
||||
if (params.outputType !== QR_OUTPUT_HTTP) {
|
||||
issues.push({
|
||||
key: "output-type",
|
||||
fixable: true,
|
||||
message: `output type is ${outputTypeName(params.outputType)} — must be HTTP, otherwise the reader beeps but never contacts the booth (currently targets ${params.server}:${params.serverPort})`,
|
||||
});
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
async checkPreconditions(): Promise<PreconditionResult> {
|
||||
const host = this.#host();
|
||||
if (!host) return { ok: true, issues: [] }; // nothing to talk to — legacy, vendor-tool-configured
|
||||
try {
|
||||
const { fw, params } = await this.#read(host);
|
||||
const issues = this.#issues(fw, params);
|
||||
return { ok: issues.length === 0, issues };
|
||||
} catch (err) {
|
||||
return { ok: false, issues: [{ key: "unreachable", fixable: false, message: (err as Error).message }] };
|
||||
}
|
||||
}
|
||||
|
||||
async fixPreconditions(): Promise<PreconditionResult> {
|
||||
const host = this.#host();
|
||||
if (!host) return { ok: true, issues: [] };
|
||||
const { params } = await this.#read(host);
|
||||
if (params.outputType !== QR_OUTPUT_HTTP) {
|
||||
const status = await writeSetting(host, QR_CMD.outputType, QR_OUTPUT_HTTP);
|
||||
if (status !== 0) {
|
||||
throw new Error(
|
||||
`reader at ${host} did not accept output type HTTP (${status == null ? "no acknowledgement" : `status ${status}`})`,
|
||||
);
|
||||
}
|
||||
stubLog(this.driverId, `${host}: output type ${outputTypeName(params.outputType)} → HTTP`);
|
||||
}
|
||||
return this.checkPreconditions();
|
||||
}
|
||||
|
||||
/** Re-read the params once a second until they show `server:port` or `deadlineMs`
|
||||
* passes; resolves the last read (null = never answered). */
|
||||
async #waitForTarget(host: string, server: string, port: number, deadlineMs = 12_000): Promise<QrParams | null> {
|
||||
const end = Date.now() + deadlineMs;
|
||||
let last: QrParams | null = null;
|
||||
while (Date.now() < end) {
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
last = await readParams(host, { timeoutMs: 1000, retries: 0 });
|
||||
if (last && last.server === server && last.serverPort === port) return last;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the reader push to THIS booth: server = our IP on its subnet, port = our listen
|
||||
* port. `pathBase`/`auth` are ignored — the reader's URL is fixed (/qa/mcardsea.<ext>)
|
||||
* and unauthenticated. set-network is an L2 broadcast the reader applies WITHOUT an
|
||||
* ack, so the result is confirmed by re-reading the params.
|
||||
*/
|
||||
async configureInputPush(opts: PushConfig): Promise<void> {
|
||||
const host = this.#host();
|
||||
if (!host) return;
|
||||
const { fw, params } = await this.#read(host);
|
||||
if (params.server === opts.host && params.serverPort === opts.port) return; // already us
|
||||
const broadcast = subnetBroadcastFor(host);
|
||||
if (!broadcast) {
|
||||
throw new Error(
|
||||
`cannot set the reader's server: ${host} is not on a directly attached subnet (set-network is an L2 broadcast) — set server ${opts.host}:${opts.port} with the vendor tool`,
|
||||
);
|
||||
}
|
||||
await setNetwork(
|
||||
{
|
||||
serial: fw.serial, // the reader matches on ITS serial, never the typed one
|
||||
ip: params.ip,
|
||||
netmask: params.netmask,
|
||||
gateway: params.gateway,
|
||||
dns1: params.dns1,
|
||||
dns2: params.dns2,
|
||||
server: opts.host,
|
||||
serverPort: opts.port,
|
||||
httpLanguage: params.httpLanguage, // any extension is served (/qa/mcardsea.<ext>)
|
||||
},
|
||||
broadcast,
|
||||
);
|
||||
// The reader re-initialises its network stack after set-network and answers nothing
|
||||
// for a few seconds (bench: silent at 1.5 s, back by ~5 s) — poll, don't read once.
|
||||
const after = await this.#waitForTarget(host, opts.host, opts.port);
|
||||
if (!after || after.server !== opts.host || after.serverPort !== opts.port) {
|
||||
throw new Error(
|
||||
`reader at ${host} did not apply server ${opts.host}:${opts.port} (still ${after?.server ?? "?"}:${after?.serverPort ?? "?"})`,
|
||||
);
|
||||
}
|
||||
stubLog(
|
||||
this.driverId,
|
||||
`${host}: push target ${params.server}:${params.serverPort} → ${opts.host}:${opts.port}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** LAN search + a params read per reader so the admin sees the mode and target at a glance. */
|
||||
async function discoverDingtianReaders(): Promise<DiscoveredDevice[]> {
|
||||
const found = await discoverReaders();
|
||||
return Promise.all(
|
||||
found.map(async (r) => {
|
||||
const [fw, params] = await Promise.all([readFirmware(r.ip), readParams(r.ip)]);
|
||||
const info: Record<string, string> = {
|
||||
output: params ? outputTypeName(params.outputType) : "unknown",
|
||||
server: `${r.server}:${r.serverPort}`,
|
||||
url: `/qa/mcardsea.${(QR_HTTP_LANGUAGES[r.httpLanguage] ?? "php").toLowerCase().replace("c#", "aspx")}`,
|
||||
};
|
||||
if (params) info.cardFormat = QR_CARD_INPUT_FORMATS[params.cardInputFormat] ?? String(params.cardInputFormat);
|
||||
if (fw) info.firmware = fw.firmware;
|
||||
return {
|
||||
id: r.serial,
|
||||
label: `${r.serial} @ ${r.ip}`,
|
||||
config: { serial: r.serial, host: r.ip },
|
||||
info,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const dingtianQrReaderDriver: ReaderDriver & DiscoverableDriver = {
|
||||
id: "dingtian-qr-reader",
|
||||
category: "reader",
|
||||
label: "Dingtian DT-008 QR/RFID reader (HTTP push)",
|
||||
description:
|
||||
"Dingtian DT-008 QR/barcode/RFID access reader that HTTP-pushes each scan to the backend. Set its server IP/port to this host in the vendor tool; enter its serial here so scans resolve to this lane.",
|
||||
"Dingtian DT-008 QR/barcode/RFID access reader that HTTP-pushes each scan to the backend. Scan the LAN to find it; with its IP, saving puts it in HTTP mode pointing at this booth (no vendor tool). Its serial maps scans to this device.",
|
||||
transports: ["tcp-ip"],
|
||||
// Pushes scans to the backend → the wizard offers the backend-IP picker; the save
|
||||
// pipeline then runs configureInputPush (set-network) with that IP + our port.
|
||||
pushesToBackend: true,
|
||||
configFields: [
|
||||
{
|
||||
key: "serial",
|
||||
label: "Device serial (cjihao)",
|
||||
type: "string",
|
||||
required: true,
|
||||
help: "The reader's serial as it reports in each scan (the `cjihao` field). Used to map scans to this lane.",
|
||||
help: "The reader's serial as it reports in each scan (the `cjihao` field). Used to map scans to this lane. Must match what the reader reports (checked on test/save when the IP is set).",
|
||||
},
|
||||
{
|
||||
// OPTIONAL: the reader pushes by serial (operation needs no IP), but giving its
|
||||
// IP lets the status monitor ICMP-ping it for a real online/offline dot instead
|
||||
// of an always-green stub. Leave blank to skip monitoring (shows "set IP").
|
||||
// OPTIONAL for operation (the reader pushes by serial), but it is what lets the
|
||||
// wizard CONFIGURE the reader (HTTP mode + server target) and the status monitor
|
||||
// ping it. Blank = nothing is configured; the reader must be set up with the vendor
|
||||
// tool / scripts/dingtian_qr.py, and liveness shows "set IP".
|
||||
...hostField,
|
||||
required: false,
|
||||
help: "Optional: the reader's IP, used ONLY to monitor it (ping). Scans still resolve by serial. Leave blank to skip liveness monitoring.",
|
||||
help: "The reader's IP on the device VLAN. With it, save sets the reader to HTTP mode pointing at this booth and the monitor pings it. Blank = configure the reader manually; no liveness.",
|
||||
},
|
||||
],
|
||||
create: (c) => new StubReader("dingtian-qr-reader", c),
|
||||
discover: discoverDingtianReaders,
|
||||
create: (c) => new DingtianQrReader("dingtian-qr-reader", c),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user