#!/usr/bin/env python3 """Offline 6400 Host HEX encoder; never opens a serial or hardware device.""" from __future__ import annotations import argparse import json from pathlib import Path import sys from typing import Iterable ROOT = Path(__file__).resolve().parents[1] DEFAULT_CONTRACT = ROOT / "generated" / "6400" / "host-contract.json" def crc16_ccitt_false(data: bytes) -> int: value = 0xFFFF for octet in data: value ^= octet << 8 for _ in range(8): value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF return value def frame(frame_type: int, payload: bytes = b"") -> bytes: if len(payload) > 255: raise ValueError("payload exceeds one-byte wire length") body = bytes((frame_type, len(payload))) + payload checksum = crc16_ccitt_false(body) return b"\xA5\x5A" + body + checksum.to_bytes(2, "little") class Encoder: def __init__(self, contract_path: Path = DEFAULT_CONTRACT) -> None: self.contract_path = contract_path self.contract = json.loads(contract_path.read_text(encoding="utf-8")) self.profiles = self.contract["canonical_profiles"] self.commands = self.contract["wire"]["commands"] def _type(self, profile: str, command: str) -> int: if profile not in self.profiles: raise ValueError(f"unknown canonical profile: {profile}") if command not in self.profiles[profile]["allowed_commands"]: raise ValueError(f"{command} is not supported by {profile}") return int(self.commands[command]["type"]) def set_target(self, profile: str, target_celsius: int) -> bytes: if target_celsius != 0 and not 20 <= target_celsius <= 70: raise ValueError("target must be 0 or 20..70 C") return frame(self._type(profile, "SET_TARGET"), bytes((target_celsius,))) def get_snapshot(self, profile: str) -> bytes: return frame(self._type(profile, "GET_SNAPSHOT")) def set_stimulus( self, profile: str, duration_seconds: int, ptc: Iterable[int], front: Iterable[int], rear: Iterable[int], ) -> bytes: values = [duration_seconds, *ptc, *front, *rear] expected = self.commands["SET_STIMULUS"]["payload_fields"] counts = [int(field["count"]) for field in expected] if len(values) != sum(counts): raise ValueError("SET_STIMULUS requires duration + 24 PTC + 4 Front + 4 Rear values") offset = 0 for field in expected: count = int(field["count"]) minimum = int(field["minimum"]) maximum = int(field["maximum"]) for value in values[offset : offset + count]: if not minimum <= value <= maximum: raise ValueError(f"{field['name']} must be {minimum}..{maximum}") offset += count return frame(self._type(profile, "SET_STIMULUS"), bytes(values)) def percent_list(text: str, count: int, label: str) -> list[int]: values = [int(value.strip()) for value in text.split(",") if value.strip()] if len(values) != count: raise argparse.ArgumentTypeError(f"{label} requires exactly {count} comma-separated percentages") if any(value < 0 or value > 100 for value in values): raise argparse.ArgumentTypeError(f"{label} percentages must be 0..100") return values def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT) parser.add_argument("--profile", required=True) subparsers = parser.add_subparsers(dest="command", required=True) target_parser = subparsers.add_parser("set-target") target_parser.add_argument("celsius", type=int) subparsers.add_parser("get-snapshot") stimulus_parser = subparsers.add_parser("set-stimulus") stimulus_parser.add_argument("--duration", type=int, required=True) stimulus_parser.add_argument("--ptc", required=True) stimulus_parser.add_argument("--front", required=True) stimulus_parser.add_argument("--rear", required=True) args = parser.parse_args(argv) encoder = Encoder(args.contract) if args.command == "set-target": result = encoder.set_target(args.profile, args.celsius) elif args.command == "get-snapshot": result = encoder.get_snapshot(args.profile) else: result = encoder.set_stimulus( args.profile, args.duration, percent_list(args.ptc, 24, "PTC"), percent_list(args.front, 4, "Front"), percent_list(args.rear, 4, "Rear"), ) print(result.hex().upper()) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except (KeyError, ValueError, json.JSONDecodeError) as exc: print(f"ERROR: {exc}", file=sys.stderr) raise SystemExit(2)