#!/usr/bin/env python3 """OSDP Control Panel with Secure Channel for checking an OSDP reader. Unlike osdp_cp_client.py this tool runs the full LibOSDP stack (the PyPI package "libosdp", the same 3.2.x library as the firmware), so it checks Secure Channel, writing a key in install mode, KEYSET and COMSET. python -m pip install pyserial libosdp==3.2.9 python osdp_sc_client.py --port /dev/ttyUSB0 --scbk-file reader.key \\ --led --buzzer --status --cards 1 The key file holds the 16-byte SCBK as 32 hex digits. The key is never printed; "key id" is the first 8 hex digits of its SHA-256 and lets you match a key with a record without revealing it. Exit status: 0 when every requested check passed, 1 otherwise, 2 on usage or setup errors. """ from __future__ import annotations import argparse import hashlib import json import sys import time from pathlib import Path try: import serial except ImportError: # pragma: no cover - depends on the installation sys.exit("pyserial is required: python -m pip install pyserial") try: from osdp import (Capability, Channel, Command, CommandLEDColor, ControlPanel, Event, LibFlag, LogLevel, PDInfo, StatusReportType) except ImportError: # pragma: no cover - depends on the installation sys.exit("libosdp is required: python -m pip install libosdp==3.2.9") MFG_WIFI = 1 MFG_SECURE = 2 CAPABILITIES = { "contact status": Capability.ContactStatusMonitoring, "output": Capability.OutputControl, "card format": Capability.CardDataFormat, "LED": Capability.LEDControl, "buzzer": Capability.AudibleControl, "secure channel": Capability.CommunicationSecurity, } STATUS_NAMES = { StatusReportType.Input: "input", StatusReportType.Output: "output", StatusReportType.Local: "local", StatusReportType.Remote: "remote", } class SerialChannel(Channel): """RS485 line through a USB adapter (8N1).""" def __init__(self, port: str, baud: int) -> None: super().__init__() self.port = serial.Serial(port, baudrate=baud, timeout=0) def read(self, max_bytes: int) -> bytes: return self.port.read(max_bytes) def write(self, buf: bytes) -> int: return self.port.write(buf) def flush(self) -> None: self.port.reset_input_buffer() def close(self) -> None: self.port.close() def read_key(path: str) -> bytes: text = "".join(Path(path).read_text(encoding="ascii").split()) try: key = bytes.fromhex(text) except ValueError: key = b"" if len(key) != 16: raise SystemExit(f"{path}: SCBK must be 32 hex digits") return key def key_id(key: bytes) -> str: return hashlib.sha256(key).hexdigest()[:8] class Check: def __init__(self) -> None: self.results: dict = {"checks": {}} self.failed = False def record(self, name: str, ok: bool, detail: str = "") -> bool: self.results["checks"][name] = {"ok": ok, "detail": detail} print(f"{'PASS' if ok else 'FAIL'} {name}{': ' + detail if detail else ''}", flush=True) self.failed |= not ok return ok def wait_until(predicate, timeout: float, step: float = 0.05) -> bool: deadline = time.monotonic() + timeout while time.monotonic() < deadline: if predicate(): return True time.sleep(step) return predicate() def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--port", required=True, help="serial port of the USB-RS485 adapter") parser.add_argument("--baud", type=int, default=9600) parser.add_argument("--address", type=int, default=101) keys = parser.add_mutually_exclusive_group(required=True) keys.add_argument("--scbk-file", help="SCBK of the reader (with --install: the key to write)") keys.add_argument("--plain", action="store_true", help="no key, plain OSDP") parser.add_argument("--install", action="store_true", help="install mode: write --scbk-file into a reader that has no key") parser.add_argument("--no-enforce", action="store_true", help="do not require the secure channel on this side") parser.add_argument("--online-timeout", type=float, default=10) parser.add_argument("--led", action="store_true", help="green LED blinks for 2 s") parser.add_argument("--buzzer", action="store_true", help="two short beeps") parser.add_argument("--output", type=float, metavar="SECONDS", help="switch output 0 on for SECONDS (check the lock first!)") parser.add_argument("--status", action="store_true", help="request input/output/local status") parser.add_argument("--cards", type=int, default=0, metavar="N", help="wait for N card reads") parser.add_argument("--timeout", type=float, default=30, help="time for --cards") parser.add_argument("--listen", type=float, default=0, metavar="SECONDS", help="print events for SECONDS") parser.add_argument("--require-secure", choices=("on", "off"), help="ODNFC MFG command: require the secure channel; the reader restarts") parser.add_argument("--wifi", action="store_true", help="ODNFC MFG command: start the Wi-Fi access point of the web editor") parser.add_argument("--comset", metavar="ADDRESS:BAUD", help="COMSET: new address and baud rate; the reader restarts") parser.add_argument("--new-scbk-file", help="KEYSET: replace the key inside the secure channel") parser.add_argument("--json", help="write the results to this file") parser.add_argument("--debug", action="store_true", help="LibOSDP debug log") args = parser.parse_args() if args.install and args.plain: parser.error("--install needs --scbk-file with the key to write") key = read_key(args.scbk_file) if args.scbk_file else None new_key = read_key(args.new_scbk_file) if args.new_scbk_file else None if new_key and (args.install or args.plain): parser.error("--new-scbk-file needs a working --scbk-file") flags = [] if args.install: flags.append(LibFlag.InstallMode) elif key and not args.no_enforce: flags.append(LibFlag.EnforceSecure) check = Check() results = check.results results.update(port=args.port, baud=args.baud, address=args.address, mode="install" if args.install else "plain" if args.plain else "secure") if key: results["key_id"] = key_id(key) print(f"key id {key_id(key)}") events: list[dict] = [] completions: list[tuple] = [] def on_event(_pd, event): events.append(event) print("event", describe(event), flush=True) return 0 def on_completion(_address, command, status): completions.append((command.get("command"), status)) channel = SerialChannel(args.port, args.baud) cp = ControlPanel( [PDInfo(args.address, channel, scbk=key, flags=flags, name="reader")], log_level=LogLevel.Debug if args.debug else LogLevel.Warning, event_handler=on_event, command_completion_handler=on_completion, ) cp.start() try: run_checks(args, cp, check, events, completions, key, new_key) finally: cp.teardown() channel.close() results["events"] = [describe(e) for e in events] results["ok"] = not check.failed if args.json: Path(args.json).write_text(json.dumps(results, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print("RESULT", "PASS" if not check.failed else "FAIL", flush=True) return 0 if not check.failed else 1 def describe(event: dict) -> str: kind = event.get("event") if kind == Event.CardRead: data = bytes(event.get("data", b"")) return (f"card reader={event.get('reader_no')} format={event.get('format')} " f"bits={event.get('length')} data={data.hex().upper()}") if kind == Event.Status: report = bytes(event.get("report", b"")) name = STATUS_NAMES.get(event.get("type"), event.get("type")) return f"status {name} report={report.hex().upper()}" if kind == Event.ManufacturerReply: return f"mfgrep vendor=0x{event.get('vendor_code', 0):06X} data={bytes(event.get('data', b'')).hex()}" return f"event {event}" def command_ok(cp, completions, address, command, name, check, wait=1.5) -> bool: before = len(completions) if not cp.submit_command(address, command): return check.record(name, False, "not queued (reader offline?)") done = wait_until(lambda: len(completions) > before, wait) if done: status = completions[before][1] return check.record(name, status == 0, "ACK" if status == 0 else f"completion {status}") # Older libosdp builds have no completion callback: the reader must stay online. time.sleep(0.5) return check.record(name, cp.is_online(address), "sent") def run_checks(args, cp, check, events, completions, key, new_key) -> None: address = args.address results = check.results online = cp.online_wait(address, args.online_timeout) check.record("online", online, f"address {address}, {args.baud} baud") if not online: return if key: secure = cp.sc_wait(address, 8) check.record("secure channel", secure, "SCBK written" if args.install and secure else "") if not secure: return else: results["secure"] = cp.is_sc_active(address) pd_id = cp.get_pd_id(address) results["pd_id"] = { "vendor_code": f"0x{pd_id.vendor_code:06X}", "model": pd_id.model, "version": pd_id.version, "serial_number": f"0x{pd_id.serial_number:08X}", "firmware_version": f"0x{pd_id.firmware_version:06X}", } print("pd id", json.dumps(results["pd_id"])) caps = {} for name, code in CAPABILITIES.items(): level, items = cp.check_capability(address, code) caps[name] = {"level": level, "items": items} results["capabilities"] = caps print("capabilities", json.dumps(caps)) if args.led: command_ok(cp, completions, address, { "command": Command.LED, "reader": 0, "led_number": 0, "control_code": 2, "on_count": 3, "off_count": 3, "on_color": CommandLEDColor.Green, "off_color": CommandLEDColor.Black, "timer_count": 20, "temporary": True, }, "LED", check) if args.buzzer: command_ok(cp, completions, address, { "command": Command.Buzzer, "reader": 0, "control_code": 2, "on_count": 1, "off_count": 1, "rep_count": 2, }, "buzzer", check) if args.output is not None: command_ok(cp, completions, address, { "command": Command.Output, "output_no": 0, "control_code": 5, "timer_count": max(1, min(65535, round(args.output * 10))), }, "output", check) if args.status: for name, kind in (("input", StatusReportType.Input), ("output", StatusReportType.Output), ("local", StatusReportType.Local)): before = len(events) cp.submit_command(address, {"command": Command.Status, "type": kind}) got = wait_until(lambda: any(e.get("event") == Event.Status and e.get("type") == kind for e in events[before:]), 2) check.record(f"{name} status", got) if args.cards: print(f"present {args.cards} card(s) within {args.timeout:.0f} s", flush=True) got = wait_until(lambda: sum(e.get("event") == Event.CardRead for e in events) >= args.cards, args.timeout) reads = [describe(e) for e in events if e.get("event") == Event.CardRead] check.record("cards", got, f"{len(reads)} read") if args.listen: time.sleep(args.listen) restart = False if args.wifi or args.require_secure: if args.wifi: command_ok(cp, completions, address, { "command": Command.Manufacturer, "vendor_code": pd_id.vendor_code, "data": bytes([MFG_WIFI]), }, "Wi-Fi access point", check) if args.require_secure: restart = command_ok(cp, completions, address, { "command": Command.Manufacturer, "vendor_code": pd_id.vendor_code, "data": bytes([MFG_SECURE, 1 if args.require_secure == "on" else 0]), }, f"secure channel required: {args.require_secure}", check) if new_key: command_ok(cp, completions, address, { "command": Command.Keyset, "type": 1, "data": new_key, }, "KEYSET", check, wait=3) results["new_key_id"] = key_id(new_key) print(f"new key id {key_id(new_key)}") if args.comset: try: new_address, new_baud = (int(x) for x in args.comset.split(":")) except ValueError: raise SystemExit("--comset expects ADDRESS:BAUD, for example 102:19200") restart = command_ok(cp, completions, address, { "command": Command.Comset, "address": new_address, "baud_rate": new_baud, }, "COMSET", check, wait=3) or restart if restart: print("the reader restarts with the new settings", flush=True) if __name__ == "__main__": sys.exit(main())