feat(devices): DT-008 reader discovery + auto-configuration over the vendor UDP protocol
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:
2026-10-08 15:22:33 +02:00
parent 08351a09bf
commit b7efa081ec
22 changed files with 2873 additions and 65 deletions
+307
View File
@@ -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.
+63
View File
@@ -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).
+485
View File
@@ -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())