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.) 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 = { 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 = { 1: "6H", 2: "8H", 3: "8H10D", 4: "6H10D", 5: "2H3D+4H5D", }; export const QR_HTTP_LANGUAGES: Record = { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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 { 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(); 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(); 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; }