#!/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('= 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(' 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())