#!/usr/bin/env python3 """Bench sink for the Dingtian DT-008 QR/RFID reader. Answers the reader's HTTP-GET push on any path (/qa/mcardsea.php|jsp|asp|aspx|cgi) with the vendor-SDK verdict JSON and `Connection: close`, and prints one line per read. Stdlib only. python3 scripts/reader-sink.py # port 80 (needs sudo/admin), refuse = 1 beep python3 scripts/reader-sink.py -p 3000 --accept # accept = 2 beeps, output 0 Point the reader's Server address/port at this machine (QRCode tool → Setting → Network parameter). See wiki/entities/dingtian-dt008-reader.md. """ import argparse import json import time from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs, urlsplit ACCEPT = False class Sink(BaseHTTPRequestHandler): protocol_version = "HTTP/1.0" def log_message(self, *_): # silence the default access log; we print our own line pass def _handle(self): q = {k: v[0] for k, v in parse_qs(urlsplit(self.path).query).items()} cardid = q.get("cardid", "") status = q.get("status", "") channel = "qr" if cardid.startswith("Q:") else "card" if cardid.startswith("K:") else "?" print( f"{time.strftime('%H:%M:%S')} {self.client_address[0]:15} serial={q.get('cjihao', '?'):10} " f"dev={q.get('mjihao', '?'):3} dir={'in' if status[-1:] == '1' else 'out' if status[-1:] == '0' else '?':3} " f"ch={channel:4} cardid={cardid!r} path={urlsplit(self.path).path}", flush=True, ) body = json.dumps( { "data": [ { "cardid": cardid, "cjihao": q.get("cjihao", ""), "mjihao": q.get("mjihao", ""), "status": 1 if ACCEPT else 0, # 1 = valid (2 beeps), 0 = invalid (1 beep) "time": str(int(time.time())), "output": 0, } ], "code": 0, "message": "", } ).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.send_header("Connection", "close") # the reader only acts once the socket closes self.end_headers() self.wfile.write(body) do_GET = _handle do_POST = _handle def main(): global ACCEPT ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("-p", "--port", type=int, default=80) ap.add_argument("-b", "--bind", default="0.0.0.0") ap.add_argument("--accept", action="store_true", help="reply status=1 (valid, 2 beeps) instead of 0") a = ap.parse_args() ACCEPT = a.accept print(f"reader sink on {a.bind}:{a.port} verdict={'ACCEPT' if ACCEPT else 'REFUSE'} (Ctrl-C to stop)", flush=True) HTTPServer((a.bind, a.port), Sink).serve_forever() if __name__ == "__main__": main()