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:
@@ -191,31 +191,44 @@ async function configureDevice(
|
|||||||
|
|
||||||
if (hasPushConfig(device)) {
|
if (hasPushConfig(device)) {
|
||||||
const host = String(config.host ?? "");
|
const host = String(config.host ?? "");
|
||||||
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
|
if (!host) {
|
||||||
const pushHost = backendIp ?? backendIpForDevice(host);
|
// Only reachable for a push device whose host is OPTIONAL (the DT-008 reader:
|
||||||
if (!pushHost) {
|
// scans resolve by serial, the IP is what lets us configure it). Nothing to talk
|
||||||
return {
|
// to → save, but say so: the reader must then be set up by hand.
|
||||||
error: {
|
hardenWarnings.push(
|
||||||
code: 400,
|
"no IP given — the reader was NOT configured: set its output type to HTTP and its server to this booth with the vendor tool (or add its IP here and save again)",
|
||||||
message: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
|
);
|
||||||
},
|
} else {
|
||||||
};
|
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
|
||||||
|
const pushHost = backendIp ?? backendIpForDevice(host);
|
||||||
|
if (!pushHost) {
|
||||||
|
return {
|
||||||
|
error: {
|
||||||
|
code: 400,
|
||||||
|
message: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const pushUser = "dingtian";
|
||||||
|
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
|
||||||
|
// (longer is silently truncated → auth mismatch), so keep it short.
|
||||||
|
const pushPassword = randomBytes(12).toString("hex");
|
||||||
|
await device.configureInputPush({
|
||||||
|
host: pushHost,
|
||||||
|
port: backendPort(),
|
||||||
|
pathBase: `/api/devices/${driverId}/${id}/input`,
|
||||||
|
auth: { user: pushUser, password: pushPassword },
|
||||||
|
});
|
||||||
|
// A device whose push carries no credentials (the DT-008 scan GET) has no use
|
||||||
|
// for these — don't persist a secret nothing checks.
|
||||||
|
if (device.usesPushAuth !== false) {
|
||||||
|
fullConfig.pushUser = pushUser;
|
||||||
|
fullConfig.pushPassword = pushPassword;
|
||||||
|
}
|
||||||
|
// Record the backend IP the device was told to push to — lets us detect
|
||||||
|
// a later mismatch if the host's IP changes.
|
||||||
|
fullConfig.backendIp = pushHost;
|
||||||
}
|
}
|
||||||
const pushUser = "dingtian";
|
|
||||||
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
|
|
||||||
// (longer is silently truncated → auth mismatch), so keep it short.
|
|
||||||
const pushPassword = randomBytes(12).toString("hex");
|
|
||||||
await device.configureInputPush({
|
|
||||||
host: pushHost,
|
|
||||||
port: backendPort(),
|
|
||||||
pathBase: `/api/devices/${driverId}/${id}/input`,
|
|
||||||
auth: { user: pushUser, password: pushPassword },
|
|
||||||
});
|
|
||||||
fullConfig.pushUser = pushUser;
|
|
||||||
fullConfig.pushPassword = pushPassword;
|
|
||||||
// Record the backend IP the device was told to push to — lets us detect
|
|
||||||
// a later mismatch if the host's IP changes.
|
|
||||||
fullConfig.backendIp = pushHost;
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { error: { code: 502, message: `device configuration failed: ${(err as Error).message}` } };
|
return { error: { code: 502, message: `device configuration failed: ${(err as Error).message}` } };
|
||||||
|
|||||||
@@ -855,7 +855,7 @@ function DeviceForm({
|
|||||||
{scanning ? t("setup.scanning") : t("setup.scan")}
|
{scanning ? t("setup.scanning") : t("setup.scan")}
|
||||||
</button>
|
</button>
|
||||||
{scanError && <span className="ml-2 text-[0.75rem] text-term-red">{scanError}</span>}
|
{scanError && <span className="ml-2 text-[0.75rem] text-term-red">{scanError}</span>}
|
||||||
{found && found.length === 0 && <p className="mt-2 text-[0.75rem] text-term-muted">{t("setup.noControllersFound")}</p>}
|
{found && found.length === 0 && <p className="mt-2 text-[0.75rem] text-term-muted">{t("setup.noDevicesFound")}</p>}
|
||||||
{found && found.length > 0 && (
|
{found && found.length > 0 && (
|
||||||
<ul className="mt-2 list-none p-0">
|
<ul className="mt-2 list-none p-0">
|
||||||
{found.map((d) => (
|
{found.map((d) => (
|
||||||
@@ -865,7 +865,15 @@ function DeviceForm({
|
|||||||
</button>
|
</button>
|
||||||
<strong className="text-term-text">{d.label}</strong>
|
<strong className="text-term-text">{d.label}</strong>
|
||||||
<HealthBadge status={d.health.status} />
|
<HealthBadge status={d.health.status} />
|
||||||
{d.info?.firmware && <span className="text-term-muted"> · fw {d.info.firmware}</span>}
|
{/* Whatever the driver reports (firmware; for a reader its output mode +
|
||||||
|
current push target — so a reader still in WG26 or pointing at another
|
||||||
|
server is visible BEFORE it is assigned). */}
|
||||||
|
{d.info &&
|
||||||
|
Object.entries(d.info).map(([k, v]) => (
|
||||||
|
<span key={k} className="text-term-muted">
|
||||||
|
{" "}· {k} {v}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -532,9 +532,9 @@ export const en: Catalog = {
|
|||||||
unbound: "unbound",
|
unbound: "unbound",
|
||||||
noDrivers: "No drivers registered.",
|
noDrivers: "No drivers registered.",
|
||||||
chooseDevice: "Choose a device…",
|
chooseDevice: "Choose a device…",
|
||||||
scan: "Scan for controllers",
|
scan: "Scan the LAN",
|
||||||
scanning: "Scanning…",
|
scanning: "Scanning…",
|
||||||
noControllersFound: "No controllers found on the LAN.",
|
noDevicesFound: "No devices found on the LAN (the booth and the device must share the device VLAN).",
|
||||||
usbNoneFound: "No USB printer found (/dev/usb/lpN) — check cable/power; the path can be typed manually.",
|
usbNoneFound: "No USB printer found (/dev/usb/lpN) — check cable/power; the path can be typed manually.",
|
||||||
usbSavedMissing: "saved — not present now",
|
usbSavedMissing: "saved — not present now",
|
||||||
use: "Use",
|
use: "Use",
|
||||||
@@ -553,7 +553,7 @@ export const en: Catalog = {
|
|||||||
chooseAddress: "Choose an address…",
|
chooseAddress: "Choose an address…",
|
||||||
onDeviceSubnet: "— on device subnet",
|
onDeviceSubnet: "— on device subnet",
|
||||||
noNicOnSubnet: "⚠ no NIC on the device's subnet — the device may not reach the backend",
|
noNicOnSubnet: "⚠ no NIC on the device's subnet — the device may not reach the backend",
|
||||||
backendIpHint: "The address this device will POST input events to.",
|
backendIpHint: "The address this device will push its events/scans to.",
|
||||||
relaysTitle: "Relays on this controller",
|
relaysTitle: "Relays on this controller",
|
||||||
relaysHint:
|
relaysHint:
|
||||||
"Each relay opens one barrier. Set its direction; for transient entry, set which input terminal the entry button is wired to.",
|
"Each relay opens one barrier. Set its direction; for transient entry, set which input terminal the entry button is wired to.",
|
||||||
|
|||||||
@@ -540,9 +540,9 @@ export const sq = {
|
|||||||
// Device form.
|
// Device form.
|
||||||
noDrivers: "Asnjë drejtues i regjistruar.",
|
noDrivers: "Asnjë drejtues i regjistruar.",
|
||||||
chooseDevice: "Zgjidh një pajisje…",
|
chooseDevice: "Zgjidh një pajisje…",
|
||||||
scan: "Skano për kontroller",
|
scan: "Skano LAN-in",
|
||||||
scanning: "Duke skanuar…",
|
scanning: "Duke skanuar…",
|
||||||
noControllersFound: "Asnjë kontroller në LAN.",
|
noDevicesFound: "Asnjë pajisje në LAN (kabina dhe pajisja duhet të jenë në të njëjtin VLAN).",
|
||||||
usbNoneFound: "Nuk u gjet asnjë printer USB (/dev/usb/lpN) — kontrollo kabllon/ushqimin; rruga mund të shkruhet me dorë.",
|
usbNoneFound: "Nuk u gjet asnjë printer USB (/dev/usb/lpN) — kontrollo kabllon/ushqimin; rruga mund të shkruhet me dorë.",
|
||||||
usbSavedMissing: "i ruajtur — jo i pranishëm tani",
|
usbSavedMissing: "i ruajtur — jo i pranishëm tani",
|
||||||
use: "Përdor",
|
use: "Përdor",
|
||||||
@@ -561,7 +561,7 @@ export const sq = {
|
|||||||
chooseAddress: "Zgjidh një adresë…",
|
chooseAddress: "Zgjidh një adresë…",
|
||||||
onDeviceSubnet: "— në subnetin e pajisjes",
|
onDeviceSubnet: "— në subnetin e pajisjes",
|
||||||
noNicOnSubnet: "⚠ asnjë NIC në subnetin e pajisjes — pajisja mund të mos arrijë backend-in",
|
noNicOnSubnet: "⚠ asnjë NIC në subnetin e pajisjes — pajisja mund të mos arrijë backend-in",
|
||||||
backendIpHint: "Adresa te e cila kjo pajisje do të dërgojë eventet e hyrjes.",
|
backendIpHint: "Adresa te e cila kjo pajisje do të dërgojë eventet/skanimet.",
|
||||||
// Relay editor.
|
// Relay editor.
|
||||||
relaysTitle: "Relet në këtë kontroller",
|
relaysTitle: "Relet në këtë kontroller",
|
||||||
relaysHint:
|
relaysHint:
|
||||||
|
|||||||
@@ -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
|
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 {
|
||||||
import type { DeviceConfig, ReaderDriver } from "../registry.js";
|
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 { 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";
|
import { icmpPing } from "./icmp.js";
|
||||||
|
|
||||||
// Reader drivers (RF / optical). Two integration paths: Wiegand reads reach the
|
// 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
|
// 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>)
|
// + 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
|
// 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
|
// device's `serial` config, decides, and replies the verdict (drives the beep). The scan path
|
||||||
// connection — the adapter is a stub; the real integration is the HTTP endpoint (apps/server
|
// is the HTTP endpoint (apps/server routes/qr-reader.ts) — this adapter never receives reads.
|
||||||
// routes/qr-reader.ts). Interfaces: Wiegand 26/34, TCP/IP, USB, RS485. See
|
//
|
||||||
// wiki/entities/dingtian-dt008-reader.md.
|
// What the adapter DOES do is CONFIGURE the reader over the vendor's UDP protocol
|
||||||
export const dingtianQrReaderDriver: ReaderDriver = {
|
// (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",
|
id: "dingtian-qr-reader",
|
||||||
category: "reader",
|
category: "reader",
|
||||||
label: "Dingtian DT-008 QR/RFID reader (HTTP push)",
|
label: "Dingtian DT-008 QR/RFID reader (HTTP push)",
|
||||||
description:
|
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"],
|
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: [
|
configFields: [
|
||||||
{
|
{
|
||||||
key: "serial",
|
key: "serial",
|
||||||
label: "Device serial (cjihao)",
|
label: "Device serial (cjihao)",
|
||||||
type: "string",
|
type: "string",
|
||||||
required: true,
|
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
|
// OPTIONAL for operation (the reader pushes by serial), but it is what lets the
|
||||||
// IP lets the status monitor ICMP-ping it for a real online/offline dot instead
|
// wizard CONFIGURE the reader (HTTP mode + server target) and the status monitor
|
||||||
// of an always-green stub. Leave blank to skip monitoring (shows "set IP").
|
// 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,
|
...hostField,
|
||||||
required: false,
|
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),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -124,6 +124,10 @@ export function hasPreconditions(
|
|||||||
// See wiki/concepts/device-input-flow.md.
|
// See wiki/concepts/device-input-flow.md.
|
||||||
export interface PushConfigurableDevice {
|
export interface PushConfigurableDevice {
|
||||||
configureInputPush(opts: PushConfig): Promise<void>;
|
configureInputPush(opts: PushConfig): Promise<void>;
|
||||||
|
/** False for a device whose push carries NO credentials (the DT-008 reader's scan GET
|
||||||
|
* is identified by its serial, not Digest auth) — the backend then skips persisting
|
||||||
|
* the generated push user/password. Absent = true (the Dingtian relay). */
|
||||||
|
readonly usesPushAuth?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PushConfig {
|
export interface PushConfig {
|
||||||
|
|||||||
Binary file not shown.
Executable
+485
@@ -0,0 +1,485 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
dingtian_qr.py - cross-platform (Linux/Windows/macOS) command line tool for
|
||||||
|
Dingtian QR code / RFID readers. Replacement for the Windows-only
|
||||||
|
QRCode_v1_6_5.exe configuration tool. Pure Python 3, no dependencies.
|
||||||
|
|
||||||
|
Protocol (reverse engineered from QRCode_v1_6_5.exe + packet captures, Oct 2026)
|
||||||
|
---------------------------------------------------------------------------------
|
||||||
|
Transport: UDP. The reader listens on 24680 (unicast commands) and 24582
|
||||||
|
(broadcast search / network set). Every message starts with a 17 byte header:
|
||||||
|
|
||||||
|
off size field notes
|
||||||
|
0 4 'XXXX' magic
|
||||||
|
4 4 id LE u32, PC sends 0, reader echoes an arbitrary value
|
||||||
|
8 4 cmd LE u32, even = request, odd (cmd+1) = reply
|
||||||
|
12 4 len LE u32, payload length
|
||||||
|
16 1 checksum (0xFF - sum(payload bytes)) & 0xFF (0xFF when no payload)
|
||||||
|
17 payload
|
||||||
|
|
||||||
|
The Windows tool sends header and payload as TWO datagrams (17 byte header
|
||||||
|
first, then the raw payload). Reader replies are a single datagram.
|
||||||
|
|
||||||
|
Commands:
|
||||||
|
2 search broadcast to :24582, no payload -> 3 96 byte DeviceInfo
|
||||||
|
0 firmware info no payload -> 1 64 bytes
|
||||||
|
30 get parameters no payload -> 31 720 byte Params
|
||||||
|
32 set network broadcast to :24582, 96 byte DeviceInfo (reader matches serial)
|
||||||
|
6 output type u32 1..10 (OUTPUT_TYPES)
|
||||||
|
8 card input format u32 1..5 (CARD_INPUT)
|
||||||
|
10 enter / newline u32 = add_enter | (add_newline << 8)
|
||||||
|
38 serial + QR format 5 x u32: baud, data bits, stop bits, parity, qr_output_format
|
||||||
|
12 QR prefix u32 prefix/suffix type (0 HEX, 1 ASCII) + 32 raw bytes
|
||||||
|
14 QR suffix u32 prefix/suffix type (same value) + 32 raw bytes
|
||||||
|
44 card output u32 card_output_format (0 HEX,1 ASCII), u32 prefix/suffix type,
|
||||||
|
32 bytes prefix, 32 bytes suffix
|
||||||
|
28 wiegand pulses 2 x u32: high_pulse/100, low_pulse/100 (units of 100 us)
|
||||||
|
40 scan fill light u32 0 close, 1 open
|
||||||
|
18 work mode u32 0 normal, 1 single, 2 interval
|
||||||
|
16 restart interval u32 0 no, 1 every 12 h, 2 every 24 h
|
||||||
|
22 buzzer u32 0 off, 1 on
|
||||||
|
|
||||||
|
Every write is acknowledged with cmd+1 and a one byte status: 0 = applied,
|
||||||
|
1 = rejected (value out of range). A frame sent as ONE datagram (header+payload
|
||||||
|
together) is ignored by the reader, so the two-datagram form is mandatory.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
PORT_UNICAST = 24680
|
||||||
|
PORT_BCAST = 24582
|
||||||
|
MAGIC = b'XXXX'
|
||||||
|
|
||||||
|
OUTPUT_TYPES = {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'}
|
||||||
|
CARD_INPUT = {1: '6H', 2: '8H', 3: '8H10D', 4: '6H10D', 5: '2H3D+4H5D'}
|
||||||
|
QR_FORMAT = {0: 'Decimal', 1: 'HEX', 2: 'Decimal Reverse', 3: 'HEX Reverse', 4: 'ASCII'}
|
||||||
|
HEX_ASCII = {0: 'HEX', 1: 'ASCII'}
|
||||||
|
PARITY = {0: 'Even', 1: 'Odd', 2: 'None', 3: 'Space', 4: 'Mark'}
|
||||||
|
RESTART = {0: 'No', 1: '12Hours', 2: '24Hours'}
|
||||||
|
WORKMODE = {0: 'Normal', 1: 'Single', 2: 'Interval'}
|
||||||
|
ONOFF = {0: 'Off', 1: 'On'}
|
||||||
|
FILL_LIGHT = {0: 'Close', 1: 'Open'}
|
||||||
|
DHCP = {0: 'Static IP', 1: 'DHCP'}
|
||||||
|
HTTP_LANG = {0: 'PHP', 1: 'JSP', 2: 'C#', 3: 'ASP', 4: 'CGI'}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- framing
|
||||||
|
def checksum(payload):
|
||||||
|
return (0xFF - sum(payload)) & 0xFF
|
||||||
|
|
||||||
|
|
||||||
|
def header(cmd, payload=b'', ident=0):
|
||||||
|
return MAGIC + struct.pack('<III', ident, cmd, len(payload)) + bytes([checksum(payload)])
|
||||||
|
|
||||||
|
|
||||||
|
def parse(datagram):
|
||||||
|
"""Return (ident, cmd, payload) or None if the datagram is not a valid frame."""
|
||||||
|
if len(datagram) < 17 or datagram[:4] != MAGIC:
|
||||||
|
return None
|
||||||
|
ident, cmd, ln = struct.unpack_from('<III', datagram, 4)
|
||||||
|
payload = datagram[17:17 + ln]
|
||||||
|
if len(payload) != ln or checksum(payload) != datagram[16]:
|
||||||
|
return None
|
||||||
|
return ident, cmd, payload
|
||||||
|
|
||||||
|
|
||||||
|
def send(sock, addr, cmd, payload=b''):
|
||||||
|
"""Send exactly like the Windows tool: header datagram first, then payload datagram."""
|
||||||
|
sock.sendto(header(cmd, payload), addr)
|
||||||
|
if payload:
|
||||||
|
sock.sendto(payload, addr)
|
||||||
|
|
||||||
|
|
||||||
|
def ip2b(s):
|
||||||
|
"""IPv4 as stored by the reader: little-endian u32 (= inet_aton reversed)."""
|
||||||
|
return socket.inet_aton(s)[::-1]
|
||||||
|
|
||||||
|
|
||||||
|
def b2ip(b):
|
||||||
|
return socket.inet_ntoa(bytes(b[:4])[::-1])
|
||||||
|
|
||||||
|
|
||||||
|
def cstr(b):
|
||||||
|
return bytes(b).split(b'\0', 1)[0].decode('utf-8', 'replace')
|
||||||
|
|
||||||
|
|
||||||
|
def u32(b, off):
|
||||||
|
return struct.unpack_from('<I', b, off)[0]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- blocks
|
||||||
|
def parse_device_info(d):
|
||||||
|
"""96 byte block: search reply (cmd 3) and set-network payload (cmd 32)."""
|
||||||
|
return {
|
||||||
|
'serial': cstr(d[0:20]),
|
||||||
|
'ip': b2ip(d[20:24]), 'netmask': b2ip(d[24:28]), 'gateway': b2ip(d[28:32]),
|
||||||
|
'dns1': b2ip(d[32:36]), 'dns2': b2ip(d[36:40]),
|
||||||
|
'server': cstr(d[40:88]),
|
||||||
|
'server_port': u32(d, 88),
|
||||||
|
'http_language': u32(d, 92),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_device_info(serial, ip, netmask, gateway, dns1, dns2, server, server_port, http_language=0):
|
||||||
|
d = bytearray(96)
|
||||||
|
d[0:20] = serial.encode()[:20].ljust(20, b'\0')
|
||||||
|
d[20:24] = ip2b(ip)
|
||||||
|
d[24:28] = ip2b(netmask)
|
||||||
|
d[28:32] = ip2b(gateway)
|
||||||
|
d[32:36] = ip2b(dns1)
|
||||||
|
d[36:40] = ip2b(dns2)
|
||||||
|
d[40:88] = server.encode()[:47].ljust(48, b'\0')
|
||||||
|
d[88:92] = struct.pack('<I', server_port)
|
||||||
|
d[92:96] = struct.pack('<I', http_language)
|
||||||
|
return bytes(d)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_firmware(d):
|
||||||
|
return {'model': cstr(d[0:16]), 'firmware': cstr(d[16:32]), 'chip': cstr(d[32:40]),
|
||||||
|
'hardware': cstr(d[40:48]), 'serial': cstr(d[48:64])}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_params(d):
|
||||||
|
"""720 byte parameter struct (reply 31 to cmd 30)."""
|
||||||
|
return {
|
||||||
|
'dhcp': u32(d, 0x000),
|
||||||
|
'ip': b2ip(d[0x004:0x008]),
|
||||||
|
'netmask': b2ip(d[0x008:0x00c]),
|
||||||
|
'gateway': b2ip(d[0x00c:0x010]),
|
||||||
|
'dns1': b2ip(d[0x010:0x014]),
|
||||||
|
'dns2': b2ip(d[0x014:0x018]),
|
||||||
|
'server': cstr(d[0x018:0x048]),
|
||||||
|
'server_port': u32(d, 0x048),
|
||||||
|
'http_language': u32(d, 0x04c),
|
||||||
|
'output_type': d[0x198],
|
||||||
|
'card_input_format': d[0x19c],
|
||||||
|
'last_add_enter': d[0x1a0],
|
||||||
|
'last_add_newline': d[0x1a1],
|
||||||
|
'qr_prefix_type': u32(d, 0x1a4), # 0 HEX / 1 ASCII
|
||||||
|
'qr_prefix': bytes(d[0x1a8:0x1c8]).rstrip(b'\0'),
|
||||||
|
'qr_suffix_type': u32(d, 0x1c8), # written with the same value as qr_prefix_type
|
||||||
|
'qr_suffix': bytes(d[0x1cc:0x1ec]).rstrip(b'\0'),
|
||||||
|
'restart_interval': u32(d, 0x1ec),
|
||||||
|
'work_mode': u32(d, 0x1f0),
|
||||||
|
'unknown_1f4': u32(d, 0x1f4),
|
||||||
|
'buzzer': u32(d, 0x1f8),
|
||||||
|
'high_pulse_us': u32(d, 0x1fc) * 100,
|
||||||
|
'low_pulse_us': u32(d, 0x200) * 100,
|
||||||
|
'baudrate': u32(d, 0x204),
|
||||||
|
'data_bits': u32(d, 0x208),
|
||||||
|
'stop_bits': u32(d, 0x20c),
|
||||||
|
'parity': u32(d, 0x210),
|
||||||
|
'qr_output_format': u32(d, 0x214),
|
||||||
|
'fill_light': u32(d, 0x218),
|
||||||
|
'card_output_format': u32(d, 0x288), # 0 HEX / 1 ASCII
|
||||||
|
'card_prefix_type': u32(d, 0x28c), # 0 HEX / 1 ASCII
|
||||||
|
'card_prefix': bytes(d[0x290:0x2b0]).rstrip(b'\0'),
|
||||||
|
'card_suffix': bytes(d[0x2b0:0x2d0]).rstrip(b'\0'),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def describe(p):
|
||||||
|
"""Human readable version of parse_params()."""
|
||||||
|
out = dict(p)
|
||||||
|
out['dhcp'] = DHCP.get(p['dhcp'], p['dhcp'])
|
||||||
|
out['http_language'] = HTTP_LANG.get(p['http_language'], p['http_language'])
|
||||||
|
out['output_type'] = OUTPUT_TYPES.get(p['output_type'], p['output_type'])
|
||||||
|
out['card_input_format'] = CARD_INPUT.get(p['card_input_format'], p['card_input_format'])
|
||||||
|
out['qr_prefix_type'] = HEX_ASCII.get(p['qr_prefix_type'], p['qr_prefix_type'])
|
||||||
|
out['qr_suffix_type'] = HEX_ASCII.get(p['qr_suffix_type'], p['qr_suffix_type'])
|
||||||
|
out['restart_interval'] = RESTART.get(p['restart_interval'], p['restart_interval'])
|
||||||
|
out['work_mode'] = WORKMODE.get(p['work_mode'], p['work_mode'])
|
||||||
|
out['buzzer'] = ONOFF.get(p['buzzer'], p['buzzer'])
|
||||||
|
out['parity'] = PARITY.get(p['parity'], p['parity'])
|
||||||
|
out['qr_output_format'] = QR_FORMAT.get(p['qr_output_format'], p['qr_output_format'])
|
||||||
|
out['fill_light'] = FILL_LIGHT.get(p['fill_light'], p['fill_light'])
|
||||||
|
out['card_output_format'] = HEX_ASCII.get(p['card_output_format'], p['card_output_format'])
|
||||||
|
out['card_prefix_type'] = HEX_ASCII.get(p['card_prefix_type'], p['card_prefix_type'])
|
||||||
|
for k in ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix'):
|
||||||
|
out[k] = p[k].decode('utf-8', 'replace') if p[k] else ''
|
||||||
|
if p[k]:
|
||||||
|
out[k + '_hex'] = p[k].hex()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- transport helpers
|
||||||
|
def open_socket(timeout=1.0, bind_ip='0.0.0.0'):
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||||
|
s.bind((bind_ip, 0))
|
||||||
|
s.settimeout(timeout)
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def discover(timeout=2.0, broadcast='255.255.255.255', bind_ip='0.0.0.0'):
|
||||||
|
"""Broadcast cmd 2 and collect cmd 3 replies. Returns list of (reply_ip, DeviceInfo)."""
|
||||||
|
s = open_socket(timeout, bind_ip)
|
||||||
|
send(s, (broadcast, PORT_BCAST), 2)
|
||||||
|
found = {}
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
try:
|
||||||
|
data, addr = s.recvfrom(65535)
|
||||||
|
except socket.timeout:
|
||||||
|
break
|
||||||
|
f = parse(data)
|
||||||
|
if f and f[1] == 3 and len(f[2]) >= 96:
|
||||||
|
info = parse_device_info(f[2])
|
||||||
|
found[info['serial']] = (addr[0], info)
|
||||||
|
s.close()
|
||||||
|
return list(found.values())
|
||||||
|
|
||||||
|
|
||||||
|
def request(ip, cmd, payload=b'', expect=None, timeout=2.0, retries=2):
|
||||||
|
"""Send a unicast command and wait for the reply (cmd + 1 unless `expect` given).
|
||||||
|
Returns the reply payload or None on timeout. For write commands the payload is
|
||||||
|
one status byte: b'\\x00' = applied, b'\\x01' = rejected."""
|
||||||
|
expect = cmd + 1 if expect is None else expect
|
||||||
|
s = open_socket(timeout)
|
||||||
|
try:
|
||||||
|
for _ in range(retries + 1):
|
||||||
|
send(s, (ip, PORT_UNICAST), cmd, payload)
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
try:
|
||||||
|
data, addr = s.recvfrom(65535)
|
||||||
|
except socket.timeout:
|
||||||
|
break
|
||||||
|
f = parse(data)
|
||||||
|
if f and f[1] == expect:
|
||||||
|
return f[2]
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_firmware(ip):
|
||||||
|
d = request(ip, 0)
|
||||||
|
return parse_firmware(d) if d else None
|
||||||
|
|
||||||
|
|
||||||
|
def get_params(ip):
|
||||||
|
d = request(ip, 30)
|
||||||
|
return parse_params(d) if d else None
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- set commands
|
||||||
|
def _set(ip, cmd, payload, wait):
|
||||||
|
"""Write command; True only if the reader acknowledged with status 0."""
|
||||||
|
if wait:
|
||||||
|
r = request(ip, cmd, payload)
|
||||||
|
if r is None:
|
||||||
|
print('cmd %d: no acknowledgement' % cmd, file=sys.stderr)
|
||||||
|
elif r != b'\x00':
|
||||||
|
print('cmd %d: rejected by reader (status %s)' % (cmd, r.hex()), file=sys.stderr)
|
||||||
|
return r == b'\x00'
|
||||||
|
s = open_socket()
|
||||||
|
send(s, (ip, PORT_UNICAST), cmd, payload)
|
||||||
|
s.close()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def set_simple(ip, cmd, value, wait=True):
|
||||||
|
return _set(ip, cmd, struct.pack('<I', value & 0xFFFFFFFF), wait)
|
||||||
|
|
||||||
|
|
||||||
|
def _pad32(b):
|
||||||
|
return bytes(b)[:32].ljust(32, b'\0')
|
||||||
|
|
||||||
|
|
||||||
|
def set_format(ip, p, wait=True):
|
||||||
|
"""Send the eight commands behind the 'Format parameter' Set button.
|
||||||
|
p: dict with parse_params() keys."""
|
||||||
|
ok = True
|
||||||
|
ok &= set_simple(ip, 6, p['output_type'], wait)
|
||||||
|
ok &= set_simple(ip, 8, p['card_input_format'], wait)
|
||||||
|
ok &= set_simple(ip, 10, (p['last_add_enter'] & 0xff) | ((p['last_add_newline'] & 0xff) << 8), wait)
|
||||||
|
ok &= _set(ip, 38, struct.pack('<5I', p['baudrate'], p['data_bits'], p['stop_bits'],
|
||||||
|
p['parity'], p['qr_output_format']), wait)
|
||||||
|
ok &= _set(ip, 12, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_prefix']), wait)
|
||||||
|
ok &= _set(ip, 14, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_suffix']), wait)
|
||||||
|
ok &= _set(ip, 44, struct.pack('<II', p['card_output_format'], p['card_prefix_type'])
|
||||||
|
+ _pad32(p['card_prefix']) + _pad32(p['card_suffix']), wait)
|
||||||
|
ok &= _set(ip, 28, struct.pack('<II', p['high_pulse_us'] // 100, p['low_pulse_us'] // 100), wait)
|
||||||
|
return bool(ok)
|
||||||
|
|
||||||
|
|
||||||
|
def set_external(ip, p, wait=True):
|
||||||
|
"""Send the four commands behind the 'External parameter' Set button."""
|
||||||
|
ok = True
|
||||||
|
ok &= set_simple(ip, 40, p['fill_light'], wait) # -> Params 0x218
|
||||||
|
ok &= set_simple(ip, 18, p['work_mode'], wait) # -> Params 0x1f0 (verified on real reader)
|
||||||
|
ok &= set_simple(ip, 16, p['restart_interval'], wait) # -> Params 0x1ec
|
||||||
|
ok &= set_simple(ip, 22, p['buzzer'], wait) # -> Params 0x1f8 (verified on real reader)
|
||||||
|
return bool(ok)
|
||||||
|
|
||||||
|
|
||||||
|
def set_network(info, broadcast='255.255.255.255', timeout=2.0):
|
||||||
|
"""Broadcast cmd 32 with a DeviceInfo block; the reader whose serial matches applies it.
|
||||||
|
Returns (addr, payload) of a cmd 33 reply, or None."""
|
||||||
|
payload = build_device_info(info['serial'], info['ip'], info['netmask'], info['gateway'],
|
||||||
|
info['dns1'], info['dns2'], info['server'], info['server_port'],
|
||||||
|
info.get('http_language', 0))
|
||||||
|
s = open_socket(timeout)
|
||||||
|
send(s, (broadcast, PORT_BCAST), 32, payload)
|
||||||
|
got = None
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
try:
|
||||||
|
data, addr = s.recvfrom(65535)
|
||||||
|
except socket.timeout:
|
||||||
|
break
|
||||||
|
f = parse(data)
|
||||||
|
if f and f[1] == 33:
|
||||||
|
got = (addr, f[2])
|
||||||
|
break
|
||||||
|
s.close()
|
||||||
|
return got
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- CLI
|
||||||
|
SET_FIELDS_INT = ('output_type', 'card_input_format', 'last_add_enter', 'last_add_newline', 'baudrate',
|
||||||
|
'data_bits', 'stop_bits', 'parity', 'qr_output_format', 'qr_prefix_type',
|
||||||
|
'card_output_format', 'card_prefix_type', 'high_pulse_us', 'low_pulse_us',
|
||||||
|
'fill_light', 'buzzer', 'restart_interval', 'work_mode')
|
||||||
|
SET_FIELDS_STR = ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix')
|
||||||
|
EXTERNAL_FIELDS = ('fill_light', 'buzzer', 'restart_interval', 'work_mode') # External Set button
|
||||||
|
# everything else in SET_FIELDS_INT / SET_FIELDS_STR belongs to the Format Set button
|
||||||
|
|
||||||
|
|
||||||
|
def _enum_help(table):
|
||||||
|
return ', '.join('%d %s' % (k, v) for k, v in table.items())
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_bytes(text):
|
||||||
|
"""CLI prefix/suffix value: plain text, or 'hex:0d0a' for binary bytes. Max 32 bytes."""
|
||||||
|
if text.lower().startswith('hex:'):
|
||||||
|
b = bytes.fromhex(text[4:])
|
||||||
|
else:
|
||||||
|
b = text.encode('utf-8')
|
||||||
|
if len(b) > 32:
|
||||||
|
raise SystemExit('prefix/suffix longer than 32 bytes: %r' % text)
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
ap = argparse.ArgumentParser(
|
||||||
|
description='Dingtian QR/RFID reader configuration tool (UDP 24680/24582). '
|
||||||
|
'See PROTOCOL.md for the wire format.',
|
||||||
|
epilog='Examples: %(prog)s discover --broadcast 192.168.1.255 | %(prog)s get 192.168.1.99 | '
|
||||||
|
'%(prog)s set 192.168.1.99 --output-type 3 --buzzer 1')
|
||||||
|
sub = ap.add_subparsers(dest='cmd', required=True)
|
||||||
|
|
||||||
|
d = sub.add_parser('discover', help='broadcast search for readers (cmd 2)')
|
||||||
|
d.add_argument('--broadcast', default='255.255.255.255', help='broadcast address, e.g. 192.168.1.255')
|
||||||
|
d.add_argument('--timeout', type=float, default=2.0)
|
||||||
|
|
||||||
|
i = sub.add_parser('info', help='firmware info (cmd 0)')
|
||||||
|
i.add_argument('ip')
|
||||||
|
|
||||||
|
g = sub.add_parser('get', help='read all parameters (cmd 30)')
|
||||||
|
g.add_argument('ip')
|
||||||
|
g.add_argument('--raw', action='store_true', help='print numeric codes instead of names')
|
||||||
|
g.add_argument('--hexdump', action='store_true', help='also hexdump the 720 byte struct')
|
||||||
|
|
||||||
|
n = sub.add_parser('set-network', help='broadcast new network settings (cmd 32)')
|
||||||
|
for k in ('serial', 'ip', 'netmask', 'gateway', 'dns1', 'dns2', 'server'):
|
||||||
|
n.add_argument('--' + k, required=True)
|
||||||
|
n.add_argument('--server-port', type=int, required=True)
|
||||||
|
n.add_argument('--http-language', type=int, default=0, help='0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI')
|
||||||
|
n.add_argument('--broadcast', default='255.255.255.255')
|
||||||
|
|
||||||
|
f = sub.add_parser('set', help='change format/external parameters (reads current values first)',
|
||||||
|
description='Reads the reader\'s current parameters (cmd 30), applies the given '
|
||||||
|
'changes and sends the full Format (6,8,10,38,12,14,44,28) and '
|
||||||
|
'External (40,18,16,22) command sequences, exactly like the Windows tool.')
|
||||||
|
f.add_argument('ip')
|
||||||
|
helps = {
|
||||||
|
'output_type': _enum_help(OUTPUT_TYPES), 'card_input_format': _enum_help(CARD_INPUT),
|
||||||
|
'last_add_enter': '0/1 append Enter after the code', 'last_add_newline': '0/1 append new line',
|
||||||
|
'baudrate': 'e.g. 9600, 115200', 'data_bits': '5..8', 'stop_bits': '1 or 2',
|
||||||
|
'parity': _enum_help(PARITY), 'qr_output_format': _enum_help(QR_FORMAT),
|
||||||
|
'qr_prefix_type': _enum_help(HEX_ASCII) + ' (applies to QR prefix and suffix)',
|
||||||
|
'card_output_format': _enum_help(HEX_ASCII), 'card_prefix_type': _enum_help(HEX_ASCII),
|
||||||
|
'high_pulse_us': 'Wiegand high pulse in microseconds (multiple of 100, default 2000)',
|
||||||
|
'low_pulse_us': 'Wiegand low pulse in microseconds (multiple of 100, default 400)',
|
||||||
|
'fill_light': _enum_help(FILL_LIGHT), 'buzzer': _enum_help(ONOFF),
|
||||||
|
'restart_interval': _enum_help(RESTART), 'work_mode': _enum_help(WORKMODE),
|
||||||
|
}
|
||||||
|
for k in SET_FIELDS_INT:
|
||||||
|
f.add_argument('--' + k.replace('_', '-'), type=int, metavar='N', help=helps[k])
|
||||||
|
for k in SET_FIELDS_STR:
|
||||||
|
f.add_argument('--' + k.replace('_', '-'), type=str, metavar='TEXT',
|
||||||
|
help='up to 32 bytes; plain text, or "hex:0d0a" for binary bytes, "" to clear')
|
||||||
|
f.add_argument('--no-wait', action='store_true', help='do not wait for acknowledgements')
|
||||||
|
|
||||||
|
a = ap.parse_args(argv)
|
||||||
|
|
||||||
|
if a.cmd == 'discover':
|
||||||
|
for ip, info in discover(a.timeout, a.broadcast):
|
||||||
|
print(json.dumps({'reply_from': ip, **info}, indent=2))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if a.cmd == 'info':
|
||||||
|
r = get_firmware(a.ip)
|
||||||
|
print(json.dumps(r, indent=2) if r else 'no reply')
|
||||||
|
return 0 if r else 1
|
||||||
|
|
||||||
|
if a.cmd == 'get':
|
||||||
|
raw = request(a.ip, 30)
|
||||||
|
if raw is None:
|
||||||
|
print('no reply')
|
||||||
|
return 1
|
||||||
|
if a.hexdump:
|
||||||
|
for o in range(0, len(raw), 32):
|
||||||
|
print('%04x: %s' % (o, raw[o:o + 32].hex(' ')))
|
||||||
|
p = parse_params(raw)
|
||||||
|
print(json.dumps(p if a.raw else describe(p), indent=2, default=lambda b: b.hex()))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if a.cmd == 'set-network':
|
||||||
|
info = {'serial': a.serial, 'ip': a.ip, 'netmask': a.netmask, 'gateway': a.gateway,
|
||||||
|
'dns1': a.dns1, 'dns2': a.dns2, 'server': a.server, 'server_port': a.server_port,
|
||||||
|
'http_language': a.http_language}
|
||||||
|
r = set_network(info, a.broadcast)
|
||||||
|
print('acknowledged by', r[0] if r else 'nobody (no cmd 33 reply within timeout)')
|
||||||
|
return 0 if r else 1
|
||||||
|
|
||||||
|
if a.cmd == 'set':
|
||||||
|
p = get_params(a.ip)
|
||||||
|
if p is None:
|
||||||
|
print('no reply from reader')
|
||||||
|
return 1
|
||||||
|
fmt_changed = ext_changed = False
|
||||||
|
for k in SET_FIELDS_INT + SET_FIELDS_STR:
|
||||||
|
v = getattr(a, k)
|
||||||
|
if v is None:
|
||||||
|
continue
|
||||||
|
p[k] = _parse_bytes(v) if k in SET_FIELDS_STR else v
|
||||||
|
if k in EXTERNAL_FIELDS:
|
||||||
|
ext_changed = True
|
||||||
|
else:
|
||||||
|
fmt_changed = True
|
||||||
|
if not (fmt_changed or ext_changed):
|
||||||
|
print('nothing to change')
|
||||||
|
return 0
|
||||||
|
# only the button group(s) that contain a changed field are sent, like pressing that Set button
|
||||||
|
ok = True
|
||||||
|
if fmt_changed:
|
||||||
|
r = set_format(a.ip, p, not a.no_wait)
|
||||||
|
print('format parameters:', 'ok' if r else 'FAILED')
|
||||||
|
ok &= r
|
||||||
|
if ext_changed:
|
||||||
|
r = set_external(a.ip, p, not a.no_wait)
|
||||||
|
print('external parameters:', 'ok' if r else 'FAILED')
|
||||||
|
ok &= r
|
||||||
|
return 0 if ok else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
type: concept
|
type: concept
|
||||||
tags: [parking, architecture, devices, setup]
|
tags: [parking, architecture, devices, setup]
|
||||||
sources: [parking-system-architecture]
|
sources: [parking-system-architecture]
|
||||||
updated: 2026-06-15
|
updated: 2026-10-08
|
||||||
---
|
---
|
||||||
|
|
||||||
# Device Discovery
|
# Device Discovery
|
||||||
@@ -20,10 +20,23 @@ device carries an `id`, a `label`, a `config` blob to **auto-fill** the setup fo
|
|||||||
(firmware, MAC, …). The [[device-registry]]'s `isDiscoverable()` guard lets the system treat it
|
(firmware, MAC, …). The [[device-registry]]'s `isDiscoverable()` guard lets the system treat it
|
||||||
as optional; the setup catalog returns a `discoverable` list of driver ids.
|
as optional; the setup catalog returns a `discoverable` list of driver ids.
|
||||||
|
|
||||||
> **No current driver implements discovery.** The [[dingtian-relay]] board uses a fixed IP
|
> **Implemented by one driver (2026-10-08): the [[dingtian-dt008-reader|Dingtian DT-008 QR/RFID
|
||||||
> (entered/known at setup). The capability remains for future UDP-discoverable devices (cameras
|
> reader]]** (`dingtian-qr-reader`), via the vendor tool's UDP protocol reversed in
|
||||||
> via ONVIF, etc.). The worked example below is the (removed) UHPPOTE driver — kept because the
|
> [[dingtian-qr-linux-tool]] (`packages/devices/src/drivers/dingtian-qr-config.ts`). The
|
||||||
> **broadcast gotchas are transferable** to any UDP discovery we add later.
|
> [[dingtian-relay]] board still uses a fixed IP. The UHPPOTE example below is historical, kept
|
||||||
|
> because the **broadcast gotchas are transferable** — the DT-008 driver applies all of them.
|
||||||
|
|
||||||
|
## DT-008 reader discovery (current)
|
||||||
|
|
||||||
|
`discover()` sends the search command (2) to the **subnet-directed broadcast of every local
|
||||||
|
IPv4 interface** on UDP 24582 and collects the DeviceInfo replies (3) for 2 s, deduped by serial;
|
||||||
|
then, per reader, a unicast params read (30) so the wizard row shows what matters **before**
|
||||||
|
assigning: `output` mode (HTTP vs WG26/RS232/…), current `server:port` target, push `url`
|
||||||
|
extension, `cardFormat`, `firmware`. "Use" fills `serial` + `host`. Verified on the bench unit
|
||||||
|
(HC002721 @ 10.0.10.12) and, read-only, on park-2's two readers. Needs an L2 segment shared
|
||||||
|
with the readers: works from the booth (host-network server) and the device VLAN; **not** from a
|
||||||
|
bridged dev container (`docker-compose.dev.yml`) nor across Netbird — there, use
|
||||||
|
`scripts/dingtian_qr.py get <ip>` on the booth instead.
|
||||||
|
|
||||||
## UHPPOTE discovery (historical example)
|
## UHPPOTE discovery (historical example)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
type: concept
|
type: concept
|
||||||
tags: [parking, architecture, devices, admin]
|
tags: [parking, architecture, devices, admin]
|
||||||
sources: [parking-system-architecture]
|
sources: [parking-system-architecture]
|
||||||
updated: 2026-06-15
|
updated: 2026-10-08
|
||||||
---
|
---
|
||||||
|
|
||||||
# First-Run Setup (device selection)
|
# First-Run Setup (device selection)
|
||||||
@@ -30,6 +30,16 @@ lane** — the pool-of-spaces model; see [[entry-exit-points]].
|
|||||||
authenticated input push ([[device-input-flow]]) — the admin never touches the device's own web
|
authenticated input push ([[device-input-flow]]) — the admin never touches the device's own web
|
||||||
UI. **Fails the save** (no DB row) if the device can't be configured, so there are no
|
UI. **Fails the save** (no DB row) if the device can't be configured, so there are no
|
||||||
orphan/half-configured rows. On success persists to `devices`.
|
orphan/half-configured rows. On success persists to `devices`.
|
||||||
|
**DT-008 readers (2026-10-08)** go through the same pipeline when their IP is given: the
|
||||||
|
precondition check reads the reader over the vendor UDP protocol ([[dingtian-qr-linux-tool]])
|
||||||
|
and reports *output type ≠ HTTP* (fixable — the save switches it) and *typed serial ≠ reported
|
||||||
|
serial* (not fixable — the admin must enter the real one); `configureInputPush` then
|
||||||
|
set-networks the reader's push target to this booth's IP + listen port and confirms it by
|
||||||
|
re-reading (the reader is silent for a few seconds after the write, so it polls). The reader's
|
||||||
|
scan GET carries no credentials, so no push user/password is persisted for it
|
||||||
|
(`usesPushAuth = false`). With **no IP** nothing is configured and the save succeeds with a
|
||||||
|
warning — the reader must then be set up with the vendor tool / `scripts/dingtian_qr.py`
|
||||||
|
([[site-device-installation]] §2).
|
||||||
4. **Remove** — `DELETE /api/setup/assign/:id` (admin-only) drops one instance's row. Only our
|
4. **Remove** — `DELETE /api/setup/assign/:id` (admin-only) drops one instance's row. Only our
|
||||||
row is removed; the device itself is not un-hardened/un-configured (a stale push from an
|
row is removed; the device itself is not un-hardened/un-configured (a stale push from an
|
||||||
unknown device id is already rejected, and re-assigning reconfigures it).
|
unknown device id is already rejected, and re-assigning reconfigures it).
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
type: reference
|
type: reference
|
||||||
tags: [parking, runbook, installation, devices, network, field]
|
tags: [parking, runbook, installation, devices, network, field]
|
||||||
sources: []
|
sources: []
|
||||||
updated: 2026-09-09
|
updated: 2026-10-08
|
||||||
---
|
---
|
||||||
|
|
||||||
# Site device installation — know it BEFORE you are standing in the booth
|
# Site device installation — know it BEFORE you are standing in the booth
|
||||||
@@ -26,8 +26,10 @@ plan, and only then does anything else see it.
|
|||||||
- A laptop with an Ethernet port and the right to add a **second static IPv4 address** to it
|
- A laptop with an Ethernet port and the right to add a **second static IPv4 address** to it
|
||||||
(Windows: adapter → IPv4 → Advanced → add). Under WSL, remember the source-address bug
|
(Windows: adapter → IPv4 → Advanced → add). Under WSL, remember the source-address bug
|
||||||
([[wsl-dev-networking]]): after adding a temporary address, `ping` may work while HTTP times out.
|
([[wsl-dev-networking]]): after adding a temporary address, `ping` may work while HTTP times out.
|
||||||
- The Dingtian reader tool **`QRCode_v1_6_5.exe`** (Windows) — the only way to set a DT-008's IP,
|
- The Dingtian reader tool **`QRCode_v1_6_5.exe`** (Windows) **or `scripts/dingtian_qr.py`**
|
||||||
server target, prefixes and symbologies. A browser is enough for everything else.
|
(Python 3, runs on the booth itself — see [[dingtian-qr-linux-tool]]) for a DT-008's IP, server
|
||||||
|
target, output type, prefixes and card format. Symbologies are set in neither (no known path).
|
||||||
|
A browser is enough for everything else.
|
||||||
- Patch cables, a USB A–B cable (printers), the site's **address plan** (below) filled in, the
|
- Patch cables, a USB A–B cable (printers), the site's **address plan** (below) filled in, the
|
||||||
app **admin** password, and a fresh Komodo **onboarding key** if the booth PC is new
|
app **admin** password, and a fresh Komodo **onboarding key** if the booth PC is new
|
||||||
([[appliance-provisioning]] §7a).
|
([[appliance-provisioning]] §7a).
|
||||||
@@ -87,16 +89,27 @@ edges reach the booth PC. You enter the relay map (which relay is entry/exit/bot
|
|||||||
|
|
||||||
## 2. Dingtian DT-008 QR + RFID readers
|
## 2. Dingtian DT-008 QR + RFID readers
|
||||||
|
|
||||||
**Factory:** IP `192.168.1.99`; no web UI — everything is set with **`QRCode_v1_6_5.exe`** over the
|
**Factory:** IP `192.168.1.99`; no web UI — everything is set over the network with
|
||||||
network. See [[dingtian-dt008-reader]].
|
**`QRCode_v1_6_5.exe`** (Windows) or **`scripts/dingtian_qr.py`** (any OS; same UDP protocol,
|
||||||
|
reversed 2026-10 — [[dingtian-qr-linux-tool]]). See [[dingtian-dt008-reader]].
|
||||||
|
|
||||||
**By hand, in the tool, per reader:**
|
**From the wizard (app builds after 2026-10-08):** add a reader → **Skano LAN-in / Scan the
|
||||||
|
LAN** lists every DT-008 on the device VLAN with its mode and current server; **Use** fills
|
||||||
|
serial + IP; **Test** says whether it is in HTTP mode and whether the serial matches; **Save**
|
||||||
|
switches it to HTTP and points its server at this booth (items 2 and 6 below, done for you).
|
||||||
|
Items 1, 3, 4, 5 are still manual (IP via `set-network`, prefixes/card format via `set`, both in
|
||||||
|
`scripts/dingtian_qr.py`; symbologies only in the exe). Needs the reader's IP in the form — with
|
||||||
|
it blank the save warns and configures nothing.
|
||||||
|
|
||||||
|
**By hand (vendor tool, or `scripts/dingtian_qr.py` from the booth), per reader:**
|
||||||
|
|
||||||
1. **Unique device IP** (`.7` entry, `.8` exit). Two readers on one IP was the 2026-06-18
|
1. **Unique device IP** (`.7` entry, `.8` exit). Two readers on one IP was the 2026-06-18
|
||||||
"wrong barrier" incident — scans land on the wrong device row.
|
"wrong barrier" incident — scans land on the wrong device row.
|
||||||
2. **Server IP** = the booth PC (`10.0.10.203`), **server port** = the booth's HTTP port (80 behind
|
2. **Output type = `HTTP`** (the tool also offers RS232 / WG26 / WG34 / RS485 / USB keyboard /
|
||||||
the prod proxy); "server language" can stay whatever it is (php/jsp/asp/aspx/cgi are all
|
USB serial — in any of those the reader beeps locally and never contacts the booth), **Server
|
||||||
served — the reader GETs `/qa/mcardsea.<ext>`).
|
IP = THIS site's booth** (park-2 is `10.0.10.101`; `10.0.10.203` is the lab — never copy it),
|
||||||
|
**server port** = the booth's HTTP port (80 behind the prod proxy); "server language" can stay
|
||||||
|
whatever it is (php/jsp/asp/aspx/cgi are all served — the reader GETs `/qa/mcardsea.<ext>`).
|
||||||
3. **Output prefixes:** `QRCode Output Prefix` = `Q:`, `Card Output Prefix` = `K:` (channel
|
3. **Output prefixes:** `QRCode Output Prefix` = `Q:`, `Card Output Prefix` = `K:` (channel
|
||||||
tagging — a printed clone of a card cannot pass as the card).
|
tagging — a printed clone of a card cannot pass as the card).
|
||||||
4. **Card Input format = `6H`** (defines the UID shape enrolled; changing it later orphans every
|
4. **Card Input format = `6H`** (defines the UID shape enrolled; changing it later orphans every
|
||||||
@@ -110,8 +123,32 @@ network. See [[dingtian-dt008-reader]].
|
|||||||
`READ serial=… → device=… verdict=… dir=…`; the reader beeps **twice** on accept, once on refuse,
|
`READ serial=… → device=… verdict=… dir=…`; the reader beeps **twice** on accept, once on refuse,
|
||||||
and only after the server's reply (no reply = no beep, the scan still happened).
|
and only after the server's reply (no reply = no beep, the scan still happened).
|
||||||
|
|
||||||
|
**From the booth, no Windows (2026-10-08):** `get` / `set` are unicast UDP, so they run on the
|
||||||
|
booth host over SSH (Python 3 is on every booth; the server container has none):
|
||||||
|
|
||||||
|
```
|
||||||
|
scp scripts/dingtian_qr.py <booth>:/tmp/ && ssh <booth> python3 -I /tmp/dingtian_qr.py get 10.0.10.7
|
||||||
|
ssh <booth> python3 -I /tmp/dingtian_qr.py set 10.0.10.7 --output-type 3 # item 2: HTTP mode
|
||||||
|
```
|
||||||
|
|
||||||
|
`get` prints every field above by name (`output_type`, `server`, `server_port`, `card_input_format`,
|
||||||
|
`qr_prefix`, `card_prefix`…). `set` changes only the fields given and re-sends the rest as read.
|
||||||
|
Only `discover` / `set-network` need the L2 broadcast (run them on the booth, not across Netbird).
|
||||||
|
|
||||||
**Trap:** a factory reset or a swapped unit silently loses items 3–5. Re-apply all of them.
|
**Trap:** a factory reset or a swapped unit silently loses items 3–5. Re-apply all of them.
|
||||||
|
|
||||||
|
**Trap (park-2, 2026-10-08): "it beeps, so it works" is false.** Enrolling a card failed on both
|
||||||
|
readers although each beeped. The booth log held **zero** `/qa/mcardsea` requests over 21 h and the
|
||||||
|
capture window saw only the form's own polls: the readers never contact the booth at all. A beep
|
||||||
|
without a `READ` line in the log means the reader is **not in HTTP mode or points at another
|
||||||
|
server** — fix it on the reader (item 2), nothing in the app or the wizard can. Diagnose in one
|
||||||
|
command on the booth: `docker logs <server> --since 1h 2>&1 | grep -c mcardsea` while a card is
|
||||||
|
presented — `0` = reader-side; then **read the reader itself** with `dingtian_qr.py get` (above).
|
||||||
|
park-2's answer: both readers `output_type = WG26` (server `10.0.10.101:3000`, JSP, 6H, no
|
||||||
|
prefixes) — they were left in Wiegand mode at install, so every scan went to a Wiegand line
|
||||||
|
nobody is listening on. (Port 3000 is fine: the host-net server listens there directly; 80 via
|
||||||
|
Caddy works too.) Fix = `set <ip> --output-type 3` per reader, then re-run the enrolment.
|
||||||
|
|
||||||
**Trap (2026-09-17): two DT-008 units read disjoint card sets.** park-buzi's units (`H05M…`)
|
**Trap (2026-09-17): two DT-008 units read disjoint card sets.** park-buzi's units (`H05M…`)
|
||||||
read the site's 125 kHz cards and the fresh lab unit (`HC002721`) reads only 13.56 MHz cards,
|
read the site's 125 kHz cards and the fresh lab unit (`HC002721`) reads only 13.56 MHz cards,
|
||||||
although the box leaflet claims both. Batch variant, a dead 125 kHz front end, or a non-EM 125 kHz
|
although the box leaflet claims both. Batch variant, a dead 125 kHz front end, or a non-EM 125 kHz
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
---
|
---
|
||||||
type: entity
|
type: entity
|
||||||
tags: [parking, hardware, readers, qr, dingtian]
|
tags: [parking, hardware, readers, qr, dingtian]
|
||||||
sources: [dingtian-dt008]
|
sources: [dingtian-dt008, dingtian-qr-linux-tool]
|
||||||
updated: 2026-09-17
|
updated: 2026-10-08
|
||||||
status: open
|
status: open
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -21,6 +21,26 @@ or RFID [[subscription]]** credentials. Product page: dingtian-tech.com/en_us/qr
|
|||||||
> (migration 0015 rewrites existing rows). All *protocol/behaviour* facts below were observed on the
|
> (migration 0015 rewrites existing rows). All *protocol/behaviour* facts below were observed on the
|
||||||
> real hardware and remain correct — only the device identity was wrong.
|
> real hardware and remain correct — only the device identity was wrong.
|
||||||
|
|
||||||
|
## Configuring it from Linux (2026-10-08)
|
||||||
|
|
||||||
|
The Windows exe's Search / Get parameter / Set are a small binary **UDP protocol** (reader ports
|
||||||
|
24680 unicast, 24582 broadcast), reversed in [[dingtian-qr-linux-tool]]; **`scripts/dingtian_qr.py`**
|
||||||
|
reimplements it. `get <ip>` returns every setting (output type, server/port/language, card input
|
||||||
|
format, prefixes, Wiegand pulses, buzzer, fill light…), `set <ip> --field value` writes one, and
|
||||||
|
both are unicast — so they run **on the booth over SSH**, no site visit. The output-type write was
|
||||||
|
proven on the bench unit (struct diff = the one byte). Not in the protocol: symbologies, DHCP
|
||||||
|
(the exe never sends it either). First use: park-2's readers read back as **`WG26`** — the
|
||||||
|
"beeps but never pushes" case ([[site-device-installation]] §2 trap).
|
||||||
|
|
||||||
|
**In the app (same day):** the driver now speaks this protocol itself
|
||||||
|
(`packages/devices/src/drivers/dingtian-qr-config.ts`, Node `dgram`, runs in the host-network
|
||||||
|
server container). The [[first-run-setup|wizard]] **Scan** button lists readers with their mode
|
||||||
|
and current target ([[device-discovery]]); **Test** reports *not in HTTP mode* / *serial
|
||||||
|
mismatch* / *no UDP answer*; **Save** switches the reader to HTTP and set-networks its server to
|
||||||
|
this booth's IP + port, confirmed by re-read. All verified on the bench unit (WG26→HTTP; target
|
||||||
|
8080→8081→8080; struct byte-identical after). The scan GET stays unauthenticated — the reader is
|
||||||
|
identified by serial, so no push secret is stored for it.
|
||||||
|
|
||||||
## What it is
|
## What it is
|
||||||
|
|
||||||
- **QR/barcode + card.** Reads **QR / simple barcode** AND **ID/IC/NFC cards** (~0.2 s, 0–10 cm).
|
- **QR/barcode + card.** Reads **QR / simple barcode** AND **ID/IC/NFC cards** (~0.2 s, 0–10 cm).
|
||||||
@@ -56,7 +76,8 @@ barrier. ([[device-input-flow]] is the analogous push pattern; this one also ret
|
|||||||
- Pushes over plain **HTTP** to our `10.0.10.x` host (on the device subnet); no serial wiring, no
|
- Pushes over plain **HTTP** to our `10.0.10.x` host (on the device subnet); no serial wiring, no
|
||||||
Wiegand-decode hardware. Suits the host-in-the-loop model; autonomy is moot anyway
|
Wiegand-decode hardware. Suits the host-in-the-loop model; autonomy is moot anyway
|
||||||
([[dingtian-relay]] has no onboard ACL).
|
([[dingtian-relay]] has no onboard ACL).
|
||||||
- Default IP `192.168.1.99` (set its server IP/port to this host in the vendor tool).
|
- Default IP `192.168.1.99` (set its server IP/port to this host in the vendor tool or with
|
||||||
|
`scripts/dingtian_qr.py`).
|
||||||
|
|
||||||
## Resolved (2026-06-16)
|
## Resolved (2026-06-16)
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ Counts: 4 sources · 19 entities · 47 concepts · 8 decision records.
|
|||||||
- [[dingtian-dt008]] — Dingtian DT-008 product page: QR/RFID access reader (QR/barcode + ID/IC/NFC; Wiegand/TCP-IP/USB/RS485; HTTP-GET push).
|
- [[dingtian-dt008]] — Dingtian DT-008 product page: QR/RFID access reader (QR/barcode + ID/IC/NFC; Wiegand/TCP-IP/USB/RS485; HTTP-GET push).
|
||||||
- [[dingtian-dt008-box-manual]] — the leaflet from the box: claims EM-ID + M1 + ISO 14443A/B + 15693 in one unit, RS232 listed.
|
- [[dingtian-dt008-box-manual]] — the leaflet from the box: claims EM-ID + M1 + ISO 14443A/B + 15693 in one unit, RS232 listed.
|
||||||
- [[qrcode-sdk]] — QRCode SDK v1.6.5: the reader's HTTP-GET-poll protocol + JSON verdict (beep/output).
|
- [[qrcode-sdk]] — QRCode SDK v1.6.5: the reader's HTTP-GET-poll protocol + JSON verdict (beep/output).
|
||||||
|
- [[dingtian-qr-linux-tool]] — the exe's config protocol reversed (UDP 24680/24582) + `scripts/dingtian_qr.py`: read/set a DT-008 from the booth over SSH; output-type write proven on the bench.
|
||||||
- [[parksql2017-legacy-schema]] — predecessor SQL Server schema (Albanian market): legacy tariff/discount/membership/shift/fiscal model; confirms blocks, adds time-windows + categories, lacks postpaid sponsors.
|
- [[parksql2017-legacy-schema]] — predecessor SQL Server schema (Albanian market): legacy tariff/discount/membership/shift/fiscal model; confirms blocks, adds time-windows + categories, lacks postpaid sponsors.
|
||||||
- [[ds-2cd1047g3h-liu]] — HIKVISION DS-2CD1047G3H-LIU-F datasheet: 4MP, main stream has no MJPEG option (sub does) — likely explains the model's persistent ISAPI snapshot 503 on main; confirms ISAPI/RTSP both fully in-spec.
|
- [[ds-2cd1047g3h-liu]] — HIKVISION DS-2CD1047G3H-LIU-F datasheet: 4MP, main stream has no MJPEG option (sub does) — likely explains the model's persistent ISAPI snapshot 503 on main; confirms ISAPI/RTSP both fully in-spec.
|
||||||
|
|
||||||
|
|||||||
+36
@@ -3379,3 +3379,39 @@ service's. `HTTP_PORT` / `SERVER_PORT` / `VISION_HOST_PORT` now flow from the st
|
|||||||
`docker-compose.prod.yml` into Caddy (`{$HTTP_PORT:80}` / `{$SERVER_PORT:3000}`), the host-net
|
`docker-compose.prod.yml` into Caddy (`{$HTTP_PORT:80}` / `{$SERVER_PORT:3000}`), the host-net
|
||||||
server (`PORT`) and vision's loopback publish; defaults reproduce the booth layout exactly. park-lab
|
server (`PORT`) and vision's loopback publish; defaults reproduce the booth layout exactly. park-lab
|
||||||
sets 8080 / 3100 / 8189. Pages: [[container-deployment]], [[fleet-deployment-komodo]] §park-lab.
|
sets 8080 / 3100 / 8189. Pages: [[container-deployment]], [[fleet-deployment-komodo]] §park-lab.
|
||||||
|
|
||||||
|
## 2026-10-08 — park-2: card enrolment "beeps but captures nothing" = the readers never push
|
||||||
|
|
||||||
|
Three capture arms at 07:37–07:38Z, 37 polls, not one reader request; the whole 21 h server log has
|
||||||
|
zero `/qa/mcardsea` hits and `device_events` has no reader category at all — the two DT-008s
|
||||||
|
(serials HC009E84 / HC00D3B0, added to the wizard 2026-09-08) have never reached the booth. The beep
|
||||||
|
is therefore local (non-HTTP output type) or another server's. Fix = the vendor tool on-site:
|
||||||
|
Output type HTTP, server `10.0.10.101`:80. Runbook §2 corrected (output type explicit; "server IP"
|
||||||
|
no longer printed as the lab's `10.0.10.203`). Pages: [[site-device-installation]] §2.
|
||||||
|
|
||||||
|
## [2026-10-08] ingest | Dingtian QR reader — Linux configuration tool (raw/dingtian_qr_linux)
|
||||||
|
|
||||||
|
The exe's UDP protocol is reversed and `dingtian_qr.py` replaces it on Linux; copied to
|
||||||
|
`scripts/dingtian_qr.py`. Verified: discover/info/get on the bench unit; `set --output-type` 3→6→3
|
||||||
|
with a struct diff of exactly byte 0x198 (the whole Format sequence is now proven on hardware).
|
||||||
|
Then, read-only over SSH from the booth, **park-2's readers answered `output_type = WG26`** — the
|
||||||
|
root cause of the morning's "beeps but captures nothing": Wiegand mode, never HTTP. Server target
|
||||||
|
was already right (`10.0.10.101:3000`). The §2 trap's "needs a Windows laptop on the VLAN" claim
|
||||||
|
from earlier today is withdrawn. Fix pending the operator's go: `set <ip> --output-type 3` on `.7`
|
||||||
|
and `.8`. Pages: [[dingtian-qr-linux-tool]], [[dingtian-dt008-reader]], [[site-device-installation]]
|
||||||
|
§2, [[qrcode-sdk]], [[index]].
|
||||||
|
|
||||||
|
## [2026-10-08] ingest | DT-008 reader discovery + auto-configuration in the app
|
||||||
|
|
||||||
|
The `dingtian-qr-reader` driver now speaks the reversed UDP protocol itself
|
||||||
|
(`dingtian-qr-config.ts`, Node dgram): `discover()` (first driver to implement
|
||||||
|
[[device-discovery]]), preconditions (output type must be HTTP — fixable; typed serial must equal
|
||||||
|
the reported one — not fixable; no UDP answer — not fixable) and `configureInputPush` (set-network
|
||||||
|
to this booth's IP + port, confirmed by polling because the reader is silent after the write and
|
||||||
|
never acks). The wizard's existing Scan / Test / Save seams carry it; discovery rows show mode +
|
||||||
|
current target; no push secret is persisted for the reader (`usesPushAuth = false`); a reader
|
||||||
|
saved without an IP warns instead of failing. Verified end to end on the bench unit (WG26→HTTP,
|
||||||
|
target 8080→8081→8080, struct byte-identical), 17 adapter + 15 protocol tests. Not yet deployed:
|
||||||
|
needs a new image (push → CI) and a stack bump; park-2's readers still await the one-line fix.
|
||||||
|
Pages: [[device-discovery]], [[first-run-setup]], [[dingtian-dt008-reader]],
|
||||||
|
[[site-device-installation]] §2, [[dingtian-qr-linux-tool]].
|
||||||
|
|||||||
@@ -0,0 +1,307 @@
|
|||||||
|
# Dingtian QR code / RFID reader – configuration protocol
|
||||||
|
|
||||||
|
Reverse engineered from `QRCode_v1_6_5.exe` (Dingtian-Tech QRCode V1.6.5, statically
|
||||||
|
linked Qt 5 Win32 application) by static analysis of the binary plus packet captures
|
||||||
|
against a real reader (serial HC002721, model `doorqrcode`, firmware `ver_client1_1.1`,
|
||||||
|
chip `v3s`, hardware `h42`) and a fake reader used to exercise the Set buttons.
|
||||||
|
|
||||||
|
`dingtian_qr.py` in this folder is a working, dependency-free Python 3 implementation
|
||||||
|
(discover / info / get / set / set-network) that runs on Linux.
|
||||||
|
|
||||||
|
## 1. What the exe does
|
||||||
|
|
||||||
|
The exe has two tabs.
|
||||||
|
|
||||||
|
* **Setting** – the configuration tool. It talks to readers over **UDP**:
|
||||||
|
* `Search device` broadcasts command 2 to `<interface broadcast>:24582` on every
|
||||||
|
local IPv4 interface. Readers answer with command 3 (96 byte DeviceInfo block).
|
||||||
|
Discovered readers are kept in an in-memory list (one 768 byte record per reader)
|
||||||
|
and shown by serial number.
|
||||||
|
* `Get parameter` sends commands 0 and 30 unicast to `<reader ip>:24680` and fills the
|
||||||
|
form from the 64 byte firmware block and the 720 byte parameter struct.
|
||||||
|
* The three `Set` buttons send a fixed sequence of small commands (below). Each write
|
||||||
|
is acknowledged by the reader with `cmd+1` and a 1 byte status (0 = OK); the exe
|
||||||
|
prints "... success!" when the acknowledgement arrives.
|
||||||
|
* The form shows the *stored record* of the selected reader. A new record is filled
|
||||||
|
with built-in defaults until a Get parameter reply has been received, which is the
|
||||||
|
behaviour you see as "the UI does not show the selected device params". Reading the
|
||||||
|
parameters directly (command 30) every time avoids this.
|
||||||
|
* **Test device** – a tiny HTTP (or raw TCP / UDP) server on a configurable port
|
||||||
|
(default 80) that receives the scan pushes the reader makes in HTTP output mode and
|
||||||
|
answers with the JSON documented in the SDK (`qrcode_HTTP_GET.txt`). The "TCP" and
|
||||||
|
"UDP" listener types of that tab were not analysed. The HTTP push is:
|
||||||
|
`GET /qa/mcardsea.php?cardid=<data>&mjihao=<device id>&cjihao=<serial>&status=<2 digits>&time=<unix>`
|
||||||
|
and the reply is
|
||||||
|
`{"data":[{"cardid":"...","cjihao":"...","mjihao":"...","status":1,"time":<unix>,"output":0}],"code":0,"message":"success"}`
|
||||||
|
(status 1 = valid, beep twice; 0 = invalid, beep once; `time` syncs the reader clock;
|
||||||
|
`output` 0 access, 1 WG26, 2 WG34). This part is independent of the UDP protocol.
|
||||||
|
|
||||||
|
The reader's default IP is 192.168.1.99 (see `readme.txt`). A reset hole on the back
|
||||||
|
restores factory settings.
|
||||||
|
|
||||||
|
## 2. Frame format (UDP, both directions)
|
||||||
|
|
||||||
|
```
|
||||||
|
offset size field notes
|
||||||
|
0 4 'XXXX' magic (0x58 0x58 0x58 0x58)
|
||||||
|
4 4 id little-endian u32; PC sends 0, reader echoes an arbitrary value
|
||||||
|
8 4 cmd little-endian u32; even = request/write, odd = reply (cmd + 1)
|
||||||
|
12 4 len little-endian u32; payload length in bytes
|
||||||
|
16 1 checksum (0xFF - sum(payload bytes)) & 0xFF -> 0xFF when len == 0
|
||||||
|
17 len payload
|
||||||
|
```
|
||||||
|
|
||||||
|
All integers are little-endian. The exe sends the header and the payload as **two
|
||||||
|
separate datagrams** (17 byte header, then the raw payload). Reader replies arrive as a
|
||||||
|
single datagram (header + payload). The Python tool mimics the two-datagram write.
|
||||||
|
|
||||||
|
Ports: reader listens on **24680/udp** (unicast) and **24582/udp** (broadcast, used for
|
||||||
|
search and set-network). Replies are sent to the IP:port the request came from, but the
|
||||||
|
reader's *source* port is not fixed: unicast replies came from 24680, search replies came
|
||||||
|
from an ephemeral port (52512 in the capture). A host firewall therefore has to allow
|
||||||
|
inbound UDP to the tool's socket (or track UDP "related" traffic); filtering on the
|
||||||
|
reader's source port does not work.
|
||||||
|
|
||||||
|
Broadcast address: the exe computes `ip | ~netmask` for every local IPv4 interface and
|
||||||
|
sends the search to each one (it does not use 255.255.255.255). Readers and PC must be on
|
||||||
|
the same layer 2 segment for search and set-network; get/set commands are plain unicast
|
||||||
|
and are routable. The exe also binds its own socket to 24582 so it can receive readers
|
||||||
|
that announce themselves; two copies of the exe on one PC therefore fight over that port.
|
||||||
|
|
||||||
|
### Worked examples
|
||||||
|
|
||||||
|
Search request, no payload (checksum of nothing = 0xFF):
|
||||||
|
|
||||||
|
```
|
||||||
|
58 58 58 58 00 00 00 00 02 00 00 00 00 00 00 00 ff
|
||||||
|
magic id = 0 cmd = 2 len = 0 checksum
|
||||||
|
```
|
||||||
|
|
||||||
|
Set buzzer on (command 18, payload = u32 1): payload bytes sum to 1, checksum = 0xFF - 1 = 0xFE.
|
||||||
|
Sent as two datagrams:
|
||||||
|
|
||||||
|
```
|
||||||
|
datagram 1: 58 58 58 58 00 00 00 00 12 00 00 00 04 00 00 00 fe
|
||||||
|
datagram 2: 01 00 00 00
|
||||||
|
```
|
||||||
|
|
||||||
|
Reader acknowledgement (cmd 19 = 18 + 1, one status byte 0x00, checksum 0xFF - 0 = 0xFF):
|
||||||
|
|
||||||
|
```
|
||||||
|
58 58 58 58 00 00 00 00 13 00 00 00 01 00 00 00 ff 00
|
||||||
|
```
|
||||||
|
|
||||||
|
Only status 0 has been observed; treat anything else as an error.
|
||||||
|
|
||||||
|
Set card prefix "AB" with ASCII type (command 44, 72 byte payload):
|
||||||
|
|
||||||
|
```
|
||||||
|
01 00 00 00 card output format = 1 (ASCII)
|
||||||
|
01 00 00 00 card prefix/suffix type = 1 (ASCII)
|
||||||
|
41 42 00 .. 00 prefix "AB", 32 bytes NUL padded
|
||||||
|
00 00 .. 00 suffix empty, 32 bytes
|
||||||
|
```
|
||||||
|
|
||||||
|
Python reference: `checksum = (0xFF - sum(payload)) & 0xFF`;
|
||||||
|
`header = b'XXXX' + struct.pack('<III', 0, cmd, len(payload)) + bytes([checksum])`.
|
||||||
|
|
||||||
|
## 3. Commands
|
||||||
|
|
||||||
|
| cmd | dir | payload | meaning |
|
||||||
|
|----:|-----|---------|---------|
|
||||||
|
| 2 | PC → bcast :24582 | none | search; every reader replies with 3 |
|
||||||
|
| 3 | reader → PC | 96 B DeviceInfo | search reply |
|
||||||
|
| 0 | PC → reader | none | firmware info; reply 1 |
|
||||||
|
| 1 | reader → PC | 64 B FirmwareInfo | |
|
||||||
|
| 30 | PC → reader | none | get parameters; reply 31 |
|
||||||
|
| 31 | reader → PC | 720 B Params | |
|
||||||
|
| 32 | PC → bcast :24582 | 96 B DeviceInfo | set network parameters. Reader matches the serial in the block. Reply 33 |
|
||||||
|
| 6 | PC → reader | u32 | output type (1..10, table below) |
|
||||||
|
| 8 | PC → reader | u32 | card input format (1..5) |
|
||||||
|
| 10 | PC → reader | u32 | byte0 = "last add Enter" (0/1), byte1 = "last add new line" (0/1) |
|
||||||
|
| 38 | PC → reader | 5 × u32 | baud, data bits (5..8), stop bits (1/2), parity (0..4), QR output format (0..4) |
|
||||||
|
| 12 | PC → reader | u32 + 32 B | QR prefix/suffix type (0 HEX, 1 ASCII) + QR prefix (raw bytes, NUL padded) |
|
||||||
|
| 14 | PC → reader | u32 + 32 B | same type value + QR suffix |
|
||||||
|
| 44 | PC → reader | u32, u32, 32 B, 32 B | card output format (0 HEX, 1 ASCII), card prefix/suffix type (0 HEX, 1 ASCII), card prefix, card suffix |
|
||||||
|
| 28 | PC → reader | 2 × u32 | Wiegand high pulse / 100, low pulse / 100 (microseconds; UI shows 2000 / 400) |
|
||||||
|
| 40 | PC → reader | u32 | scan code fill light: 0 close, 1 open (Params 0x218) |
|
||||||
|
| 18 | PC → reader | u32 | work mode: 0 normal, 1 single, 2 interval (Params 0x1f0) |
|
||||||
|
| 16 | PC → reader | u32 | restart interval: 0 no, 1 every 12 h, 2 every 24 h (Params 0x1ec; the test reader rejected 2) |
|
||||||
|
| 22 | PC → reader | u32 | buzzer: 0 off, 1 on (Params 0x1f8) |
|
||||||
|
|
||||||
|
Every write is answered with `cmd+1`, `len = 1`, payload = 1 status byte:
|
||||||
|
`00` = value applied (the parameter struct changes immediately, no commit or reboot
|
||||||
|
needed), `01` = value rejected (out of range), struct unchanged. A write whose header
|
||||||
|
and payload are sent in **one** datagram gets no answer and is ignored.
|
||||||
|
|
||||||
|
The 18/22 and 40/16 assignments were confirmed on the real reader by sending each
|
||||||
|
command alone and diffing the 720 byte struct afterwards (the exe's two Set passes
|
||||||
|
alone could not tell them apart because both fields of each pair changed together).
|
||||||
|
|
||||||
|
Button → command sequence in the exe:
|
||||||
|
|
||||||
|
* **Network Set**: 32 (broadcast).
|
||||||
|
* **Format Set**: 6, 8, 10, 38, 12, 14, 44, 28 (in this order, back to back).
|
||||||
|
* **External Set**: 40, 18, 16, 22.
|
||||||
|
|
||||||
|
The exe's receive dispatcher accepts reply commands 1..41; other odd commands exist in
|
||||||
|
the jump table but are not used by the UI.
|
||||||
|
|
||||||
|
### Enumerations (values as sent on the wire)
|
||||||
|
|
||||||
|
| field | values |
|
||||||
|
|-------|--------|
|
||||||
|
| output type (cmd 6, Params 0x198) | 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 |
|
||||||
|
| card input format (cmd 8, Params 0x19c) | 1 6H, 2 8H, 3 8H10D, 4 6H10D, 5 2H3D+4H5D |
|
||||||
|
| QR output format (cmd 38[4], Params 0x214) | 0 Decimal, 1 HEX, 2 Decimal Reverse, 3 HEX Reverse, 4 ASCII |
|
||||||
|
| prefix/suffix type, card output format | 0 HEX, 1 ASCII (HEX only changes how the exe displays/enters the bytes; the wire always carries raw bytes) |
|
||||||
|
| parity (cmd 38[3], Params 0x210) | 0 Even, 1 Odd, 2 None, 3 Space, 4 Mark |
|
||||||
|
| baud (cmd 38[0]) | actual value; exe list: 110 134 150 300 600 1200 1800 2400 4800 7200 9600 14400 19200 38400 57600 115200 128000 256000 |
|
||||||
|
| restart interval | 0 No, 1 12Hours, 2 24Hours |
|
||||||
|
| work mode | 0 Normal, 1 Single, 2 Interval |
|
||||||
|
| buzzer | 0 Off, 1 On |
|
||||||
|
| fill light | 0 Close, 1 Open |
|
||||||
|
| DHCP (Params 0x000) | 0 Static IP, 1 DHCP |
|
||||||
|
| HTTP server language (Params 0x04c, DeviceInfo 92) | 0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI |
|
||||||
|
|
||||||
|
## 4. Data blocks
|
||||||
|
|
||||||
|
IPv4 addresses are stored as a little-endian u32, i.e. the bytes of `inet_aton()`
|
||||||
|
reversed: 10.0.10.12 is `0c 0a 00 0a`.
|
||||||
|
|
||||||
|
### DeviceInfo – 96 bytes (reply 3, payload of 32)
|
||||||
|
|
||||||
|
```
|
||||||
|
0 20 serial number, NUL padded ASCII ("HC002721")
|
||||||
|
20 4 ip
|
||||||
|
24 4 netmask
|
||||||
|
28 4 gateway
|
||||||
|
32 4 dns1
|
||||||
|
36 4 dns2
|
||||||
|
40 48 server address, NUL padded string (hostname or IP, e.g. "10.0.10.204";
|
||||||
|
factory default is "ipc.fondvision.com")
|
||||||
|
88 4 server port (u32, e.g. 8080)
|
||||||
|
92 4 HTTP server language (0 PHP .. 4 CGI)
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: the exe's set-network code builds this block by writing the 20 byte serial over
|
||||||
|
the first 20 bytes of its 80 byte network record (dhcp, ip, ..., language). The DHCP
|
||||||
|
word is therefore overwritten by the serial and **DHCP is never transmitted** by the
|
||||||
|
exe; the DHCP combobox has no effect on the wire.
|
||||||
|
|
||||||
|
### FirmwareInfo – 64 bytes (reply 1)
|
||||||
|
|
||||||
|
```
|
||||||
|
0 16 model "doorqrcode"
|
||||||
|
16 16 firmware "ver_client1_1.1"
|
||||||
|
32 8 chip "v3s"
|
||||||
|
40 8 hardware "h42"
|
||||||
|
48 16 serial "HC002721"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Params – 720 bytes (reply 31)
|
||||||
|
|
||||||
|
```
|
||||||
|
0x000 4 dhcp (0 static, 1 dhcp)
|
||||||
|
0x004 4 ip
|
||||||
|
0x008 4 netmask
|
||||||
|
0x00c 4 gateway
|
||||||
|
0x010 4 dns1
|
||||||
|
0x014 4 dns2
|
||||||
|
0x018 48 server address string
|
||||||
|
0x048 4 server port
|
||||||
|
0x04c 4 HTTP server language
|
||||||
|
0x050 .. 0x197 reserved / zero on the test reader (MQTT and other hidden settings
|
||||||
|
probably live here; the exe never reads them)
|
||||||
|
0x198 1 output type (cmd 6)
|
||||||
|
0x19c 1 card input format (cmd 8)
|
||||||
|
0x1a0 1 last add Enter (cmd 10 byte 0)
|
||||||
|
0x1a1 1 last add new line (cmd 10 byte 1)
|
||||||
|
0x1a4 4 QR prefix/suffix type (cmd 12 word)
|
||||||
|
0x1a8 32 QR prefix (cmd 12 bytes)
|
||||||
|
0x1c8 4 QR prefix/suffix type again (cmd 14 word)
|
||||||
|
0x1cc 32 QR suffix (cmd 14 bytes)
|
||||||
|
0x1ec 4 restart interval (cmd 16)
|
||||||
|
0x1f0 4 work mode (cmd 18)
|
||||||
|
0x1f4 4 unknown (0 on test reader, not shown by the exe)
|
||||||
|
0x1f8 4 buzzer (cmd 22)
|
||||||
|
0x1fc 4 high pulse / 100 (cmd 28[0])
|
||||||
|
0x200 4 low pulse / 100 (cmd 28[1])
|
||||||
|
0x204 4 baud rate (cmd 38[0])
|
||||||
|
0x208 4 data bits (cmd 38[1])
|
||||||
|
0x20c 4 stop bits (cmd 38[2])
|
||||||
|
0x210 4 parity (cmd 38[3])
|
||||||
|
0x214 4 QR output format (cmd 38[4])
|
||||||
|
0x218 4 scan fill light (cmd 40)
|
||||||
|
0x21c .. 0x287 zero on the test reader
|
||||||
|
0x288 4 card output format (cmd 44[0])
|
||||||
|
0x28c 4 card prefix/suffix type (cmd 44[1])
|
||||||
|
0x290 32 card prefix (cmd 44 bytes 8..39)
|
||||||
|
0x2b0 32 card suffix (cmd 44 bytes 40..71)
|
||||||
|
```
|
||||||
|
|
||||||
|
Reference capture from the test reader (HTTP mode, server 10.0.10.204:8080, PHP,
|
||||||
|
card input 8H, add Enter on, 9600 8N1, ASCII formats, pulses 2000/400 µs, restart 12 h,
|
||||||
|
normal mode, buzzer off, fill light open):
|
||||||
|
|
||||||
|
```
|
||||||
|
0000: 00000000 0c0a000a 00ffffff 010a000a 08080808 04040808 "10.0.10.204"...
|
||||||
|
0048: 901f0000 00000000 ...
|
||||||
|
0198: 03 00 00 00 02 00 00 00 01 00 00 00 01 00 00 00 ...
|
||||||
|
01c8: 01 00 00 00 ...
|
||||||
|
01ec: 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|
||||||
|
01fc: 14 00 00 00 04 00 00 00 80 25 00 00 08 00 00 00 01 00 00 00 02 00 00 00 04 00 00 00 01 00 00 00
|
||||||
|
0288: 01 00 00 00 01 00 00 00 ...
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. Implementation notes for other tools
|
||||||
|
|
||||||
|
* Build the header with the checksum of the payload, send header then payload (two
|
||||||
|
datagrams), then wait for a datagram whose command equals `cmd + 1`. The exe does not
|
||||||
|
retry; the Python tool retries twice with a 2 s timeout.
|
||||||
|
* Discovery: send command 2 to the subnet broadcast, collect command 3 replies for about
|
||||||
|
2 s, de-duplicate by serial. The reply block already contains the IP to use for
|
||||||
|
unicast commands.
|
||||||
|
* Reading: command 30 is enough for the whole form; command 0 only adds firmware info.
|
||||||
|
* Writing a single field: there is no "write the whole struct" command. Read the struct
|
||||||
|
first, then send only the small command that owns the field (table in section 3).
|
||||||
|
Commands 38, 12, 14 and 44 carry several fields at once, so fill the untouched ones
|
||||||
|
from the struct you just read.
|
||||||
|
* Changing IP/server: broadcast command 32 with the 96 byte block; the serial selects the
|
||||||
|
reader. Expect the reader to answer 33 (not captured on the real unit because that
|
||||||
|
would have changed its configuration).
|
||||||
|
* Prefix/suffix fields are raw bytes (max 32). "HEX" vs "ASCII" type only tells the
|
||||||
|
reader (and the exe's form) how to interpret them.
|
||||||
|
* Pulse widths are stored in units of 100 µs (2000 µs on the wire is 20).
|
||||||
|
|
||||||
|
## 6. Verification status
|
||||||
|
|
||||||
|
* Search, firmware info, get parameters and the acknowledgement format were captured
|
||||||
|
from the real reader and reproduced with `dingtian_qr.py`.
|
||||||
|
* The write payloads (commands 6, 8, 10, 12, 14, 16, 18, 22, 28, 32, 38, 40, 44) were
|
||||||
|
captured from the exe while it talked to a fake reader, with two different sets of
|
||||||
|
form values, and matched against the parameter struct and the disassembly.
|
||||||
|
* Real writes verified on the HC002721 reader: commands 18, 22 and 40 each change
|
||||||
|
exactly the struct word listed above and are acknowledged with status 0; out-of-range
|
||||||
|
values (22 ← 2, 16 ← 2) are acknowledged with status 1 and change nothing; a
|
||||||
|
single-datagram frame is ignored. The reader was restored to its original
|
||||||
|
configuration afterwards (struct byte-identical to the first capture).
|
||||||
|
* Not verified on a real reader: the Format commands (6, 8, 10, 12, 14, 28, 38, 44) and
|
||||||
|
set-network (32); their byte layouts are identical to the exe's.
|
||||||
|
* Not understood: Params 0x1f4, the reserved area 0x050..0x197 (likely MQTT settings),
|
||||||
|
and what the reader does with a DHCP = 1 flag.
|
||||||
|
|
||||||
|
## 7. Linux quick start
|
||||||
|
|
||||||
|
```
|
||||||
|
python3 dingtian_qr.py discover --broadcast 192.168.1.255
|
||||||
|
python3 dingtian_qr.py info 192.168.1.99
|
||||||
|
python3 dingtian_qr.py get 192.168.1.99
|
||||||
|
python3 dingtian_qr.py set 192.168.1.99 --output-type 3 --buzzer 1 --fill-light 1
|
||||||
|
python3 dingtian_qr.py set-network --serial HC002721 --ip 192.168.1.50 --netmask 255.255.255.0 \
|
||||||
|
--gateway 192.168.1.1 --dns1 8.8.8.8 --dns2 8.8.4.4 --server 192.168.1.10 --server-port 8080 \
|
||||||
|
--http-language 0 --broadcast 192.168.1.255
|
||||||
|
```
|
||||||
|
|
||||||
|
`set` reads the current parameters first and only changes the fields you pass, then
|
||||||
|
sends the full Format and External sequences exactly like the exe.
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# Dingtian QR reader – Linux configuration tool
|
||||||
|
|
||||||
|
Replacement for the Windows-only `QRCode_v1_6_5.exe` shipped in the Dingtian QR code
|
||||||
|
reader SDK. Lets you find readers on the LAN, read their configuration and change
|
||||||
|
network, output-format and behaviour settings from Linux (or any OS with Python 3).
|
||||||
|
|
||||||
|
| file | purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `PROTOCOL.md` | the reverse engineered UDP protocol: frame format, command list, field tables, 720 byte parameter struct, verification status |
|
||||||
|
| `dingtian_qr.py` | reference implementation and CLI (`discover`, `info`, `get`, `set`, `set-network`); importable as a module |
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
* Python 3.6 or newer, standard library only.
|
||||||
|
* The PC must be on the same layer 2 network as the readers for `discover` and
|
||||||
|
`set-network` (they use UDP broadcast). `info`, `get` and `set` are unicast and work
|
||||||
|
across routers.
|
||||||
|
* Host firewall: allow inbound UDP replies to the tool's socket. Readers reply from
|
||||||
|
arbitrary source ports, so do not filter on the reader's source port.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```
|
||||||
|
python3 dingtian_qr.py discover --broadcast 192.168.1.255 # list readers (serial, ip, server...)
|
||||||
|
python3 dingtian_qr.py info 192.168.1.99 # model / firmware / serial
|
||||||
|
python3 dingtian_qr.py get 192.168.1.99 # full configuration (add --raw for numeric codes)
|
||||||
|
python3 dingtian_qr.py set 192.168.1.99 --output-type 3 --buzzer 1 --qr-suffix "hex:0d"
|
||||||
|
python3 dingtian_qr.py set-network --serial HC002721 --ip 192.168.1.50 --netmask 255.255.255.0 \
|
||||||
|
--gateway 192.168.1.1 --dns1 8.8.8.8 --dns2 8.8.4.4 --server 192.168.1.10 \
|
||||||
|
--server-port 8080 --http-language 0 --broadcast 192.168.1.255
|
||||||
|
python3 dingtian_qr.py set --help # every field with its numeric codes
|
||||||
|
```
|
||||||
|
|
||||||
|
`set` reads the current configuration first and only changes the fields you pass; it
|
||||||
|
then sends the same command sequence as the exe's Set button that owns those fields
|
||||||
|
(Format group and/or External group). `set-network`
|
||||||
|
broadcasts and the reader whose serial matches applies the new values, so it also works
|
||||||
|
for a reader whose current IP is in the wrong subnet.
|
||||||
|
|
||||||
|
A factory reset (pin in the RESET hole on the back) returns the reader to 192.168.1.99.
|
||||||
|
|
||||||
|
## Using it from your own code
|
||||||
|
|
||||||
|
```python
|
||||||
|
import dingtian_qr as dq
|
||||||
|
for ip, info in dq.discover(broadcast='192.168.1.255'):
|
||||||
|
print(info['serial'], ip)
|
||||||
|
params = dq.get_params('192.168.1.99') # dict, keys documented in parse_params()
|
||||||
|
params['output_type'] = 3 # HTTP
|
||||||
|
params['buzzer'] = 1
|
||||||
|
dq.set_format('192.168.1.99', params) # commands 6,8,10,38,12,14,44,28
|
||||||
|
dq.set_external('192.168.1.99', params) # commands 40,18,16,22
|
||||||
|
```
|
||||||
|
|
||||||
|
## Caveats
|
||||||
|
|
||||||
|
* The DHCP setting cannot be written: the original exe never transmits it (see
|
||||||
|
PROTOCOL.md), so the reader's behaviour for it is unknown.
|
||||||
|
* The External commands (buzzer, work mode, fill light, restart interval) were verified
|
||||||
|
on a real reader. The Format commands and set-network were validated only against
|
||||||
|
the exe's own packets and a simulated reader. Test on one reader before rolling out.
|
||||||
|
* Parameter struct words 0x1f4 and the area 0x050–0x197 are not understood (the exe
|
||||||
|
does not use them either).
|
||||||
@@ -0,0 +1,485 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
dingtian_qr.py - cross-platform (Linux/Windows/macOS) command line tool for
|
||||||
|
Dingtian QR code / RFID readers. Replacement for the Windows-only
|
||||||
|
QRCode_v1_6_5.exe configuration tool. Pure Python 3, no dependencies.
|
||||||
|
|
||||||
|
Protocol (reverse engineered from QRCode_v1_6_5.exe + packet captures, Oct 2026)
|
||||||
|
---------------------------------------------------------------------------------
|
||||||
|
Transport: UDP. The reader listens on 24680 (unicast commands) and 24582
|
||||||
|
(broadcast search / network set). Every message starts with a 17 byte header:
|
||||||
|
|
||||||
|
off size field notes
|
||||||
|
0 4 'XXXX' magic
|
||||||
|
4 4 id LE u32, PC sends 0, reader echoes an arbitrary value
|
||||||
|
8 4 cmd LE u32, even = request, odd (cmd+1) = reply
|
||||||
|
12 4 len LE u32, payload length
|
||||||
|
16 1 checksum (0xFF - sum(payload bytes)) & 0xFF (0xFF when no payload)
|
||||||
|
17 payload
|
||||||
|
|
||||||
|
The Windows tool sends header and payload as TWO datagrams (17 byte header
|
||||||
|
first, then the raw payload). Reader replies are a single datagram.
|
||||||
|
|
||||||
|
Commands:
|
||||||
|
2 search broadcast to :24582, no payload -> 3 96 byte DeviceInfo
|
||||||
|
0 firmware info no payload -> 1 64 bytes
|
||||||
|
30 get parameters no payload -> 31 720 byte Params
|
||||||
|
32 set network broadcast to :24582, 96 byte DeviceInfo (reader matches serial)
|
||||||
|
6 output type u32 1..10 (OUTPUT_TYPES)
|
||||||
|
8 card input format u32 1..5 (CARD_INPUT)
|
||||||
|
10 enter / newline u32 = add_enter | (add_newline << 8)
|
||||||
|
38 serial + QR format 5 x u32: baud, data bits, stop bits, parity, qr_output_format
|
||||||
|
12 QR prefix u32 prefix/suffix type (0 HEX, 1 ASCII) + 32 raw bytes
|
||||||
|
14 QR suffix u32 prefix/suffix type (same value) + 32 raw bytes
|
||||||
|
44 card output u32 card_output_format (0 HEX,1 ASCII), u32 prefix/suffix type,
|
||||||
|
32 bytes prefix, 32 bytes suffix
|
||||||
|
28 wiegand pulses 2 x u32: high_pulse/100, low_pulse/100 (units of 100 us)
|
||||||
|
40 scan fill light u32 0 close, 1 open
|
||||||
|
18 work mode u32 0 normal, 1 single, 2 interval
|
||||||
|
16 restart interval u32 0 no, 1 every 12 h, 2 every 24 h
|
||||||
|
22 buzzer u32 0 off, 1 on
|
||||||
|
|
||||||
|
Every write is acknowledged with cmd+1 and a one byte status: 0 = applied,
|
||||||
|
1 = rejected (value out of range). A frame sent as ONE datagram (header+payload
|
||||||
|
together) is ignored by the reader, so the two-datagram form is mandatory.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
PORT_UNICAST = 24680
|
||||||
|
PORT_BCAST = 24582
|
||||||
|
MAGIC = b'XXXX'
|
||||||
|
|
||||||
|
OUTPUT_TYPES = {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'}
|
||||||
|
CARD_INPUT = {1: '6H', 2: '8H', 3: '8H10D', 4: '6H10D', 5: '2H3D+4H5D'}
|
||||||
|
QR_FORMAT = {0: 'Decimal', 1: 'HEX', 2: 'Decimal Reverse', 3: 'HEX Reverse', 4: 'ASCII'}
|
||||||
|
HEX_ASCII = {0: 'HEX', 1: 'ASCII'}
|
||||||
|
PARITY = {0: 'Even', 1: 'Odd', 2: 'None', 3: 'Space', 4: 'Mark'}
|
||||||
|
RESTART = {0: 'No', 1: '12Hours', 2: '24Hours'}
|
||||||
|
WORKMODE = {0: 'Normal', 1: 'Single', 2: 'Interval'}
|
||||||
|
ONOFF = {0: 'Off', 1: 'On'}
|
||||||
|
FILL_LIGHT = {0: 'Close', 1: 'Open'}
|
||||||
|
DHCP = {0: 'Static IP', 1: 'DHCP'}
|
||||||
|
HTTP_LANG = {0: 'PHP', 1: 'JSP', 2: 'C#', 3: 'ASP', 4: 'CGI'}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- framing
|
||||||
|
def checksum(payload):
|
||||||
|
return (0xFF - sum(payload)) & 0xFF
|
||||||
|
|
||||||
|
|
||||||
|
def header(cmd, payload=b'', ident=0):
|
||||||
|
return MAGIC + struct.pack('<III', ident, cmd, len(payload)) + bytes([checksum(payload)])
|
||||||
|
|
||||||
|
|
||||||
|
def parse(datagram):
|
||||||
|
"""Return (ident, cmd, payload) or None if the datagram is not a valid frame."""
|
||||||
|
if len(datagram) < 17 or datagram[:4] != MAGIC:
|
||||||
|
return None
|
||||||
|
ident, cmd, ln = struct.unpack_from('<III', datagram, 4)
|
||||||
|
payload = datagram[17:17 + ln]
|
||||||
|
if len(payload) != ln or checksum(payload) != datagram[16]:
|
||||||
|
return None
|
||||||
|
return ident, cmd, payload
|
||||||
|
|
||||||
|
|
||||||
|
def send(sock, addr, cmd, payload=b''):
|
||||||
|
"""Send exactly like the Windows tool: header datagram first, then payload datagram."""
|
||||||
|
sock.sendto(header(cmd, payload), addr)
|
||||||
|
if payload:
|
||||||
|
sock.sendto(payload, addr)
|
||||||
|
|
||||||
|
|
||||||
|
def ip2b(s):
|
||||||
|
"""IPv4 as stored by the reader: little-endian u32 (= inet_aton reversed)."""
|
||||||
|
return socket.inet_aton(s)[::-1]
|
||||||
|
|
||||||
|
|
||||||
|
def b2ip(b):
|
||||||
|
return socket.inet_ntoa(bytes(b[:4])[::-1])
|
||||||
|
|
||||||
|
|
||||||
|
def cstr(b):
|
||||||
|
return bytes(b).split(b'\0', 1)[0].decode('utf-8', 'replace')
|
||||||
|
|
||||||
|
|
||||||
|
def u32(b, off):
|
||||||
|
return struct.unpack_from('<I', b, off)[0]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- blocks
|
||||||
|
def parse_device_info(d):
|
||||||
|
"""96 byte block: search reply (cmd 3) and set-network payload (cmd 32)."""
|
||||||
|
return {
|
||||||
|
'serial': cstr(d[0:20]),
|
||||||
|
'ip': b2ip(d[20:24]), 'netmask': b2ip(d[24:28]), 'gateway': b2ip(d[28:32]),
|
||||||
|
'dns1': b2ip(d[32:36]), 'dns2': b2ip(d[36:40]),
|
||||||
|
'server': cstr(d[40:88]),
|
||||||
|
'server_port': u32(d, 88),
|
||||||
|
'http_language': u32(d, 92),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_device_info(serial, ip, netmask, gateway, dns1, dns2, server, server_port, http_language=0):
|
||||||
|
d = bytearray(96)
|
||||||
|
d[0:20] = serial.encode()[:20].ljust(20, b'\0')
|
||||||
|
d[20:24] = ip2b(ip)
|
||||||
|
d[24:28] = ip2b(netmask)
|
||||||
|
d[28:32] = ip2b(gateway)
|
||||||
|
d[32:36] = ip2b(dns1)
|
||||||
|
d[36:40] = ip2b(dns2)
|
||||||
|
d[40:88] = server.encode()[:47].ljust(48, b'\0')
|
||||||
|
d[88:92] = struct.pack('<I', server_port)
|
||||||
|
d[92:96] = struct.pack('<I', http_language)
|
||||||
|
return bytes(d)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_firmware(d):
|
||||||
|
return {'model': cstr(d[0:16]), 'firmware': cstr(d[16:32]), 'chip': cstr(d[32:40]),
|
||||||
|
'hardware': cstr(d[40:48]), 'serial': cstr(d[48:64])}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_params(d):
|
||||||
|
"""720 byte parameter struct (reply 31 to cmd 30)."""
|
||||||
|
return {
|
||||||
|
'dhcp': u32(d, 0x000),
|
||||||
|
'ip': b2ip(d[0x004:0x008]),
|
||||||
|
'netmask': b2ip(d[0x008:0x00c]),
|
||||||
|
'gateway': b2ip(d[0x00c:0x010]),
|
||||||
|
'dns1': b2ip(d[0x010:0x014]),
|
||||||
|
'dns2': b2ip(d[0x014:0x018]),
|
||||||
|
'server': cstr(d[0x018:0x048]),
|
||||||
|
'server_port': u32(d, 0x048),
|
||||||
|
'http_language': u32(d, 0x04c),
|
||||||
|
'output_type': d[0x198],
|
||||||
|
'card_input_format': d[0x19c],
|
||||||
|
'last_add_enter': d[0x1a0],
|
||||||
|
'last_add_newline': d[0x1a1],
|
||||||
|
'qr_prefix_type': u32(d, 0x1a4), # 0 HEX / 1 ASCII
|
||||||
|
'qr_prefix': bytes(d[0x1a8:0x1c8]).rstrip(b'\0'),
|
||||||
|
'qr_suffix_type': u32(d, 0x1c8), # written with the same value as qr_prefix_type
|
||||||
|
'qr_suffix': bytes(d[0x1cc:0x1ec]).rstrip(b'\0'),
|
||||||
|
'restart_interval': u32(d, 0x1ec),
|
||||||
|
'work_mode': u32(d, 0x1f0),
|
||||||
|
'unknown_1f4': u32(d, 0x1f4),
|
||||||
|
'buzzer': u32(d, 0x1f8),
|
||||||
|
'high_pulse_us': u32(d, 0x1fc) * 100,
|
||||||
|
'low_pulse_us': u32(d, 0x200) * 100,
|
||||||
|
'baudrate': u32(d, 0x204),
|
||||||
|
'data_bits': u32(d, 0x208),
|
||||||
|
'stop_bits': u32(d, 0x20c),
|
||||||
|
'parity': u32(d, 0x210),
|
||||||
|
'qr_output_format': u32(d, 0x214),
|
||||||
|
'fill_light': u32(d, 0x218),
|
||||||
|
'card_output_format': u32(d, 0x288), # 0 HEX / 1 ASCII
|
||||||
|
'card_prefix_type': u32(d, 0x28c), # 0 HEX / 1 ASCII
|
||||||
|
'card_prefix': bytes(d[0x290:0x2b0]).rstrip(b'\0'),
|
||||||
|
'card_suffix': bytes(d[0x2b0:0x2d0]).rstrip(b'\0'),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def describe(p):
|
||||||
|
"""Human readable version of parse_params()."""
|
||||||
|
out = dict(p)
|
||||||
|
out['dhcp'] = DHCP.get(p['dhcp'], p['dhcp'])
|
||||||
|
out['http_language'] = HTTP_LANG.get(p['http_language'], p['http_language'])
|
||||||
|
out['output_type'] = OUTPUT_TYPES.get(p['output_type'], p['output_type'])
|
||||||
|
out['card_input_format'] = CARD_INPUT.get(p['card_input_format'], p['card_input_format'])
|
||||||
|
out['qr_prefix_type'] = HEX_ASCII.get(p['qr_prefix_type'], p['qr_prefix_type'])
|
||||||
|
out['qr_suffix_type'] = HEX_ASCII.get(p['qr_suffix_type'], p['qr_suffix_type'])
|
||||||
|
out['restart_interval'] = RESTART.get(p['restart_interval'], p['restart_interval'])
|
||||||
|
out['work_mode'] = WORKMODE.get(p['work_mode'], p['work_mode'])
|
||||||
|
out['buzzer'] = ONOFF.get(p['buzzer'], p['buzzer'])
|
||||||
|
out['parity'] = PARITY.get(p['parity'], p['parity'])
|
||||||
|
out['qr_output_format'] = QR_FORMAT.get(p['qr_output_format'], p['qr_output_format'])
|
||||||
|
out['fill_light'] = FILL_LIGHT.get(p['fill_light'], p['fill_light'])
|
||||||
|
out['card_output_format'] = HEX_ASCII.get(p['card_output_format'], p['card_output_format'])
|
||||||
|
out['card_prefix_type'] = HEX_ASCII.get(p['card_prefix_type'], p['card_prefix_type'])
|
||||||
|
for k in ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix'):
|
||||||
|
out[k] = p[k].decode('utf-8', 'replace') if p[k] else ''
|
||||||
|
if p[k]:
|
||||||
|
out[k + '_hex'] = p[k].hex()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- transport helpers
|
||||||
|
def open_socket(timeout=1.0, bind_ip='0.0.0.0'):
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||||
|
s.bind((bind_ip, 0))
|
||||||
|
s.settimeout(timeout)
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def discover(timeout=2.0, broadcast='255.255.255.255', bind_ip='0.0.0.0'):
|
||||||
|
"""Broadcast cmd 2 and collect cmd 3 replies. Returns list of (reply_ip, DeviceInfo)."""
|
||||||
|
s = open_socket(timeout, bind_ip)
|
||||||
|
send(s, (broadcast, PORT_BCAST), 2)
|
||||||
|
found = {}
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
try:
|
||||||
|
data, addr = s.recvfrom(65535)
|
||||||
|
except socket.timeout:
|
||||||
|
break
|
||||||
|
f = parse(data)
|
||||||
|
if f and f[1] == 3 and len(f[2]) >= 96:
|
||||||
|
info = parse_device_info(f[2])
|
||||||
|
found[info['serial']] = (addr[0], info)
|
||||||
|
s.close()
|
||||||
|
return list(found.values())
|
||||||
|
|
||||||
|
|
||||||
|
def request(ip, cmd, payload=b'', expect=None, timeout=2.0, retries=2):
|
||||||
|
"""Send a unicast command and wait for the reply (cmd + 1 unless `expect` given).
|
||||||
|
Returns the reply payload or None on timeout. For write commands the payload is
|
||||||
|
one status byte: b'\\x00' = applied, b'\\x01' = rejected."""
|
||||||
|
expect = cmd + 1 if expect is None else expect
|
||||||
|
s = open_socket(timeout)
|
||||||
|
try:
|
||||||
|
for _ in range(retries + 1):
|
||||||
|
send(s, (ip, PORT_UNICAST), cmd, payload)
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
try:
|
||||||
|
data, addr = s.recvfrom(65535)
|
||||||
|
except socket.timeout:
|
||||||
|
break
|
||||||
|
f = parse(data)
|
||||||
|
if f and f[1] == expect:
|
||||||
|
return f[2]
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_firmware(ip):
|
||||||
|
d = request(ip, 0)
|
||||||
|
return parse_firmware(d) if d else None
|
||||||
|
|
||||||
|
|
||||||
|
def get_params(ip):
|
||||||
|
d = request(ip, 30)
|
||||||
|
return parse_params(d) if d else None
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- set commands
|
||||||
|
def _set(ip, cmd, payload, wait):
|
||||||
|
"""Write command; True only if the reader acknowledged with status 0."""
|
||||||
|
if wait:
|
||||||
|
r = request(ip, cmd, payload)
|
||||||
|
if r is None:
|
||||||
|
print('cmd %d: no acknowledgement' % cmd, file=sys.stderr)
|
||||||
|
elif r != b'\x00':
|
||||||
|
print('cmd %d: rejected by reader (status %s)' % (cmd, r.hex()), file=sys.stderr)
|
||||||
|
return r == b'\x00'
|
||||||
|
s = open_socket()
|
||||||
|
send(s, (ip, PORT_UNICAST), cmd, payload)
|
||||||
|
s.close()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def set_simple(ip, cmd, value, wait=True):
|
||||||
|
return _set(ip, cmd, struct.pack('<I', value & 0xFFFFFFFF), wait)
|
||||||
|
|
||||||
|
|
||||||
|
def _pad32(b):
|
||||||
|
return bytes(b)[:32].ljust(32, b'\0')
|
||||||
|
|
||||||
|
|
||||||
|
def set_format(ip, p, wait=True):
|
||||||
|
"""Send the eight commands behind the 'Format parameter' Set button.
|
||||||
|
p: dict with parse_params() keys."""
|
||||||
|
ok = True
|
||||||
|
ok &= set_simple(ip, 6, p['output_type'], wait)
|
||||||
|
ok &= set_simple(ip, 8, p['card_input_format'], wait)
|
||||||
|
ok &= set_simple(ip, 10, (p['last_add_enter'] & 0xff) | ((p['last_add_newline'] & 0xff) << 8), wait)
|
||||||
|
ok &= _set(ip, 38, struct.pack('<5I', p['baudrate'], p['data_bits'], p['stop_bits'],
|
||||||
|
p['parity'], p['qr_output_format']), wait)
|
||||||
|
ok &= _set(ip, 12, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_prefix']), wait)
|
||||||
|
ok &= _set(ip, 14, struct.pack('<I', p['qr_prefix_type']) + _pad32(p['qr_suffix']), wait)
|
||||||
|
ok &= _set(ip, 44, struct.pack('<II', p['card_output_format'], p['card_prefix_type'])
|
||||||
|
+ _pad32(p['card_prefix']) + _pad32(p['card_suffix']), wait)
|
||||||
|
ok &= _set(ip, 28, struct.pack('<II', p['high_pulse_us'] // 100, p['low_pulse_us'] // 100), wait)
|
||||||
|
return bool(ok)
|
||||||
|
|
||||||
|
|
||||||
|
def set_external(ip, p, wait=True):
|
||||||
|
"""Send the four commands behind the 'External parameter' Set button."""
|
||||||
|
ok = True
|
||||||
|
ok &= set_simple(ip, 40, p['fill_light'], wait) # -> Params 0x218
|
||||||
|
ok &= set_simple(ip, 18, p['work_mode'], wait) # -> Params 0x1f0 (verified on real reader)
|
||||||
|
ok &= set_simple(ip, 16, p['restart_interval'], wait) # -> Params 0x1ec
|
||||||
|
ok &= set_simple(ip, 22, p['buzzer'], wait) # -> Params 0x1f8 (verified on real reader)
|
||||||
|
return bool(ok)
|
||||||
|
|
||||||
|
|
||||||
|
def set_network(info, broadcast='255.255.255.255', timeout=2.0):
|
||||||
|
"""Broadcast cmd 32 with a DeviceInfo block; the reader whose serial matches applies it.
|
||||||
|
Returns (addr, payload) of a cmd 33 reply, or None."""
|
||||||
|
payload = build_device_info(info['serial'], info['ip'], info['netmask'], info['gateway'],
|
||||||
|
info['dns1'], info['dns2'], info['server'], info['server_port'],
|
||||||
|
info.get('http_language', 0))
|
||||||
|
s = open_socket(timeout)
|
||||||
|
send(s, (broadcast, PORT_BCAST), 32, payload)
|
||||||
|
got = None
|
||||||
|
end = time.time() + timeout
|
||||||
|
while time.time() < end:
|
||||||
|
try:
|
||||||
|
data, addr = s.recvfrom(65535)
|
||||||
|
except socket.timeout:
|
||||||
|
break
|
||||||
|
f = parse(data)
|
||||||
|
if f and f[1] == 33:
|
||||||
|
got = (addr, f[2])
|
||||||
|
break
|
||||||
|
s.close()
|
||||||
|
return got
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- CLI
|
||||||
|
SET_FIELDS_INT = ('output_type', 'card_input_format', 'last_add_enter', 'last_add_newline', 'baudrate',
|
||||||
|
'data_bits', 'stop_bits', 'parity', 'qr_output_format', 'qr_prefix_type',
|
||||||
|
'card_output_format', 'card_prefix_type', 'high_pulse_us', 'low_pulse_us',
|
||||||
|
'fill_light', 'buzzer', 'restart_interval', 'work_mode')
|
||||||
|
SET_FIELDS_STR = ('qr_prefix', 'qr_suffix', 'card_prefix', 'card_suffix')
|
||||||
|
EXTERNAL_FIELDS = ('fill_light', 'buzzer', 'restart_interval', 'work_mode') # External Set button
|
||||||
|
# everything else in SET_FIELDS_INT / SET_FIELDS_STR belongs to the Format Set button
|
||||||
|
|
||||||
|
|
||||||
|
def _enum_help(table):
|
||||||
|
return ', '.join('%d %s' % (k, v) for k, v in table.items())
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_bytes(text):
|
||||||
|
"""CLI prefix/suffix value: plain text, or 'hex:0d0a' for binary bytes. Max 32 bytes."""
|
||||||
|
if text.lower().startswith('hex:'):
|
||||||
|
b = bytes.fromhex(text[4:])
|
||||||
|
else:
|
||||||
|
b = text.encode('utf-8')
|
||||||
|
if len(b) > 32:
|
||||||
|
raise SystemExit('prefix/suffix longer than 32 bytes: %r' % text)
|
||||||
|
return b
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
ap = argparse.ArgumentParser(
|
||||||
|
description='Dingtian QR/RFID reader configuration tool (UDP 24680/24582). '
|
||||||
|
'See PROTOCOL.md for the wire format.',
|
||||||
|
epilog='Examples: %(prog)s discover --broadcast 192.168.1.255 | %(prog)s get 192.168.1.99 | '
|
||||||
|
'%(prog)s set 192.168.1.99 --output-type 3 --buzzer 1')
|
||||||
|
sub = ap.add_subparsers(dest='cmd', required=True)
|
||||||
|
|
||||||
|
d = sub.add_parser('discover', help='broadcast search for readers (cmd 2)')
|
||||||
|
d.add_argument('--broadcast', default='255.255.255.255', help='broadcast address, e.g. 192.168.1.255')
|
||||||
|
d.add_argument('--timeout', type=float, default=2.0)
|
||||||
|
|
||||||
|
i = sub.add_parser('info', help='firmware info (cmd 0)')
|
||||||
|
i.add_argument('ip')
|
||||||
|
|
||||||
|
g = sub.add_parser('get', help='read all parameters (cmd 30)')
|
||||||
|
g.add_argument('ip')
|
||||||
|
g.add_argument('--raw', action='store_true', help='print numeric codes instead of names')
|
||||||
|
g.add_argument('--hexdump', action='store_true', help='also hexdump the 720 byte struct')
|
||||||
|
|
||||||
|
n = sub.add_parser('set-network', help='broadcast new network settings (cmd 32)')
|
||||||
|
for k in ('serial', 'ip', 'netmask', 'gateway', 'dns1', 'dns2', 'server'):
|
||||||
|
n.add_argument('--' + k, required=True)
|
||||||
|
n.add_argument('--server-port', type=int, required=True)
|
||||||
|
n.add_argument('--http-language', type=int, default=0, help='0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI')
|
||||||
|
n.add_argument('--broadcast', default='255.255.255.255')
|
||||||
|
|
||||||
|
f = sub.add_parser('set', help='change format/external parameters (reads current values first)',
|
||||||
|
description='Reads the reader\'s current parameters (cmd 30), applies the given '
|
||||||
|
'changes and sends the full Format (6,8,10,38,12,14,44,28) and '
|
||||||
|
'External (40,18,16,22) command sequences, exactly like the Windows tool.')
|
||||||
|
f.add_argument('ip')
|
||||||
|
helps = {
|
||||||
|
'output_type': _enum_help(OUTPUT_TYPES), 'card_input_format': _enum_help(CARD_INPUT),
|
||||||
|
'last_add_enter': '0/1 append Enter after the code', 'last_add_newline': '0/1 append new line',
|
||||||
|
'baudrate': 'e.g. 9600, 115200', 'data_bits': '5..8', 'stop_bits': '1 or 2',
|
||||||
|
'parity': _enum_help(PARITY), 'qr_output_format': _enum_help(QR_FORMAT),
|
||||||
|
'qr_prefix_type': _enum_help(HEX_ASCII) + ' (applies to QR prefix and suffix)',
|
||||||
|
'card_output_format': _enum_help(HEX_ASCII), 'card_prefix_type': _enum_help(HEX_ASCII),
|
||||||
|
'high_pulse_us': 'Wiegand high pulse in microseconds (multiple of 100, default 2000)',
|
||||||
|
'low_pulse_us': 'Wiegand low pulse in microseconds (multiple of 100, default 400)',
|
||||||
|
'fill_light': _enum_help(FILL_LIGHT), 'buzzer': _enum_help(ONOFF),
|
||||||
|
'restart_interval': _enum_help(RESTART), 'work_mode': _enum_help(WORKMODE),
|
||||||
|
}
|
||||||
|
for k in SET_FIELDS_INT:
|
||||||
|
f.add_argument('--' + k.replace('_', '-'), type=int, metavar='N', help=helps[k])
|
||||||
|
for k in SET_FIELDS_STR:
|
||||||
|
f.add_argument('--' + k.replace('_', '-'), type=str, metavar='TEXT',
|
||||||
|
help='up to 32 bytes; plain text, or "hex:0d0a" for binary bytes, "" to clear')
|
||||||
|
f.add_argument('--no-wait', action='store_true', help='do not wait for acknowledgements')
|
||||||
|
|
||||||
|
a = ap.parse_args(argv)
|
||||||
|
|
||||||
|
if a.cmd == 'discover':
|
||||||
|
for ip, info in discover(a.timeout, a.broadcast):
|
||||||
|
print(json.dumps({'reply_from': ip, **info}, indent=2))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if a.cmd == 'info':
|
||||||
|
r = get_firmware(a.ip)
|
||||||
|
print(json.dumps(r, indent=2) if r else 'no reply')
|
||||||
|
return 0 if r else 1
|
||||||
|
|
||||||
|
if a.cmd == 'get':
|
||||||
|
raw = request(a.ip, 30)
|
||||||
|
if raw is None:
|
||||||
|
print('no reply')
|
||||||
|
return 1
|
||||||
|
if a.hexdump:
|
||||||
|
for o in range(0, len(raw), 32):
|
||||||
|
print('%04x: %s' % (o, raw[o:o + 32].hex(' ')))
|
||||||
|
p = parse_params(raw)
|
||||||
|
print(json.dumps(p if a.raw else describe(p), indent=2, default=lambda b: b.hex()))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if a.cmd == 'set-network':
|
||||||
|
info = {'serial': a.serial, 'ip': a.ip, 'netmask': a.netmask, 'gateway': a.gateway,
|
||||||
|
'dns1': a.dns1, 'dns2': a.dns2, 'server': a.server, 'server_port': a.server_port,
|
||||||
|
'http_language': a.http_language}
|
||||||
|
r = set_network(info, a.broadcast)
|
||||||
|
print('acknowledged by', r[0] if r else 'nobody (no cmd 33 reply within timeout)')
|
||||||
|
return 0 if r else 1
|
||||||
|
|
||||||
|
if a.cmd == 'set':
|
||||||
|
p = get_params(a.ip)
|
||||||
|
if p is None:
|
||||||
|
print('no reply from reader')
|
||||||
|
return 1
|
||||||
|
fmt_changed = ext_changed = False
|
||||||
|
for k in SET_FIELDS_INT + SET_FIELDS_STR:
|
||||||
|
v = getattr(a, k)
|
||||||
|
if v is None:
|
||||||
|
continue
|
||||||
|
p[k] = _parse_bytes(v) if k in SET_FIELDS_STR else v
|
||||||
|
if k in EXTERNAL_FIELDS:
|
||||||
|
ext_changed = True
|
||||||
|
else:
|
||||||
|
fmt_changed = True
|
||||||
|
if not (fmt_changed or ext_changed):
|
||||||
|
print('nothing to change')
|
||||||
|
return 0
|
||||||
|
# only the button group(s) that contain a changed field are sent, like pressing that Set button
|
||||||
|
ok = True
|
||||||
|
if fmt_changed:
|
||||||
|
r = set_format(a.ip, p, not a.no_wait)
|
||||||
|
print('format parameters:', 'ok' if r else 'FAILED')
|
||||||
|
ok &= r
|
||||||
|
if ext_changed:
|
||||||
|
r = set_external(a.ip, p, not a.no_wait)
|
||||||
|
print('external parameters:', 'ok' if r else 'FAILED')
|
||||||
|
ok &= r
|
||||||
|
return 0 if ok else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
---
|
||||||
|
type: source
|
||||||
|
tags: [parking, hardware, readers, qr, dingtian, protocol, linux, tooling]
|
||||||
|
sources: [dingtian-qr-linux-tool]
|
||||||
|
updated: 2026-10-08
|
||||||
|
---
|
||||||
|
|
||||||
|
# Source: Dingtian QR reader — Linux configuration tool + reversed UDP protocol
|
||||||
|
|
||||||
|
`raw/dingtian_qr_linux/` (`README.md`, `PROTOCOL.md`, `dingtian_qr.py`; October 2026). A
|
||||||
|
reverse engineering of `QRCode_v1_6_5.exe` ([[qrcode-sdk]]) — static analysis of the Qt binary
|
||||||
|
plus captures against the bench reader `HC002721` and a fake reader — and a dependency-free
|
||||||
|
Python 3 replacement for the Windows tool. The script is copied to **`scripts/dingtian_qr.py`**
|
||||||
|
for use on booths. Entity: [[dingtian-dt008-reader]]; runbook: [[site-device-installation]] §2.
|
||||||
|
|
||||||
|
## Why it matters
|
||||||
|
|
||||||
|
Until now a DT-008's settings (IP, server target, output type, prefixes, card format) could only
|
||||||
|
be read or changed with the vendor's Windows exe on a laptop plugged into the device VLAN. The
|
||||||
|
exe's "Search device" / "Get parameter" / "Set" are a small binary **UDP** protocol; `get` and
|
||||||
|
`set` are **unicast**, so they run from the booth itself over SSH/Netbird. The 2026-10-08
|
||||||
|
park-2 enrolment failure ([[site-device-installation]] §2 trap) was diagnosed in one command
|
||||||
|
this way instead of a site visit.
|
||||||
|
|
||||||
|
## Protocol (PROTOCOL.md §2–4)
|
||||||
|
|
||||||
|
- Frame: `'XXXX'` + id u32 + cmd u32 + len u32 + checksum byte (`0xFF − Σpayload`) + payload;
|
||||||
|
all little-endian. Even cmd = request, reply = cmd+1.
|
||||||
|
- **Quirk:** the exe sends header and payload as **two datagrams**; a single-datagram frame is
|
||||||
|
silently ignored by the reader. The script mimics this.
|
||||||
|
- Ports: reader listens on **24680/udp** (unicast: 0 firmware info → 64 B, 30 get params →
|
||||||
|
720 B struct, every write) and **24582/udp** (broadcast: 2 search → 3 with a 96 B DeviceInfo,
|
||||||
|
32 set-network matched by serial). Replies come from arbitrary source ports — a host firewall
|
||||||
|
must allow inbound UDP to the tool's socket.
|
||||||
|
- Writes: one small command per field group (6 output type, 8 card input format, 10 enter/
|
||||||
|
newline, 38 serial+QR format, 12/14 QR prefix/suffix, 44 card output+prefix/suffix, 28 Wiegand
|
||||||
|
pulses; 40 fill light, 18 work mode, 16 restart interval, 22 buzzer). Ack = cmd+1 with one
|
||||||
|
status byte (0 applied immediately, 1 rejected). The exe's Format Set button sends 6, 8, 10,
|
||||||
|
38, 12, 14, 44, 28 back to back; External Set sends 40, 18, 16, 22; `set` reproduces whichever
|
||||||
|
group owns the changed field, after reading the struct so untouched fields are re-sent as-is.
|
||||||
|
- Enumerations on the wire: output type 1 USB keyboard, 2 USB serial, **3 HTTP**, 4 MQTT,
|
||||||
|
5 RS232, 6 WG26, 7 WG34, 8 RS485, 9 AC Output, 10 TCP; card input 1 6H, 2 8H, 3 8H10D,
|
||||||
|
4 6H10D, 5 2H3D+4H5D; HTTP language 0 PHP, 1 JSP, 2 C#, 3 ASP, 4 CGI.
|
||||||
|
- IPv4 fields are little-endian u32 (bytes of `inet_aton` reversed).
|
||||||
|
- **DHCP is never transmitted** by the exe (its set-network code overwrites the DHCP word with
|
||||||
|
the serial) — the combobox has no effect; the script cannot write it either.
|
||||||
|
- Not understood: Params `0x1f4` and the reserved area `0x050–0x197` (probably MQTT/TCP
|
||||||
|
settings). **Symbologies are not in this protocol** (the exe has no such field) — the
|
||||||
|
phantom-read fix in [[dingtian-dt008-reader]] still has no known configuration path.
|
||||||
|
|
||||||
|
## Verification status
|
||||||
|
|
||||||
|
- By the author: search/info/get and the ack format captured from the real reader; the write
|
||||||
|
payloads matched against the exe talking to a fake reader; commands 18, 22, 40 proven on the
|
||||||
|
real reader by diffing the struct.
|
||||||
|
- **Ours, 2026-10-08, bench `HC002721` @ `10.0.10.12`:** `set --output-type 6` then
|
||||||
|
`--output-type 3` — all eight Format commands acked with status 0, the diff of the 720 B struct
|
||||||
|
was exactly byte `0x198` (3 → 6 → 3), final struct byte-identical to the original. So the full
|
||||||
|
Format sequence (6, 8, 10, 38, 12, 14, 44, 28) is now proven on real hardware too.
|
||||||
|
- **Ours, park-2, read-only** from the booth over SSH: both readers answered `info` + `get`
|
||||||
|
(`HC009E84` @ `.7`, `HC00D3B0` @ `.8`, firmware `ver_client1_1.1`, chip `v3s`, hw `h42`).
|
||||||
|
- Still unverified on a real reader: `set-network` (cmd 32).
|
||||||
|
|
||||||
|
## In the app
|
||||||
|
|
||||||
|
`packages/devices/src/drivers/dingtian-qr-config.ts` is a TypeScript port of the protocol
|
||||||
|
(frame, DeviceInfo/Firmware/Params codecs, two-datagram writes, discover, set-network) with a
|
||||||
|
fake-reader test suite; `reader.ts` uses it for the DT-008 driver's `discover()`,
|
||||||
|
preconditions and `configureInputPush()` ([[first-run-setup]], [[device-discovery]]). Extra
|
||||||
|
hardware facts learned while wiring it (2026-10-08, bench HC002721): **cmd 6 alone** (no Format
|
||||||
|
group) is accepted and applied; **set-network is applied but never acknowledged**, and the
|
||||||
|
reader answers nothing for ~2–6 s afterwards (poll the params; the driver waits up to 12 s);
|
||||||
|
the Python and TS tools build byte-identical set-network payloads.
|
||||||
|
|
||||||
|
## Usage (from a booth)
|
||||||
|
|
||||||
|
```
|
||||||
|
python3 -I scripts/dingtian_qr.py discover --broadcast 10.0.10.255 # LAN search (same L2 only)
|
||||||
|
python3 -I scripts/dingtian_qr.py get 10.0.10.7 # full config, human-readable
|
||||||
|
python3 -I scripts/dingtian_qr.py get 10.0.10.7 --raw --hexdump # numeric codes + 720 B dump
|
||||||
|
python3 -I scripts/dingtian_qr.py set 10.0.10.7 --output-type 3 # HTTP mode (reads first, re-sends the Format group)
|
||||||
|
```
|
||||||
|
|
||||||
|
Booth hosts ship Python 3 (park-2: 3.14); copy the one file over `scp` and run it on the host
|
||||||
|
(the server container has no Python). Readers are per-site on `10.0.10.x`; `set-network` needs the
|
||||||
|
L2 broadcast, so it works from the booth but not across Netbird.
|
||||||
@@ -11,7 +11,8 @@ Vendor SDK for the QR access reader (the Dingtian [[dingtian-dt008-reader]]). De
|
|||||||
reader↔server **HTTP protocol** — the missing piece the datasheet omitted. Files at
|
reader↔server **HTTP protocol** — the missing piece the datasheet omitted. Files at
|
||||||
`QRCode_sdk - QRCode_v1_6_5/sdk/` (config tool `QRCode_v1_6_5.exe`, demos in C#/PHP/VC++, protocol
|
`QRCode_sdk - QRCode_v1_6_5/sdk/` (config tool `QRCode_v1_6_5.exe`, demos in C#/PHP/VC++, protocol
|
||||||
docs `readme.txt`, `qrcode_HTTP_GET.txt`, `VC++/how to.txt`). **Not copied into `raw/`** — bulky +
|
docs `readme.txt`, `qrcode_HTTP_GET.txt`, `VC++/how to.txt`). **Not copied into `raw/`** — bulky +
|
||||||
binaries; this summary is the faithful capture. Entity: [[dingtian-dt008-reader]].
|
binaries; this summary is the faithful capture. Entity: [[dingtian-dt008-reader]]. The SDK documents
|
||||||
|
only the HTTP push; the exe's *configuration* protocol (UDP) is reversed in [[dingtian-qr-linux-tool]].
|
||||||
|
|
||||||
## The protocol — HTTP GET poll, server replies the verdict
|
## The protocol — HTTP GET poll, server replies the verdict
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user