encode_6400_hex.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #!/usr/bin/env python3
  2. """Offline 6400 Host HEX encoder; never opens a serial or hardware device."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. from pathlib import Path
  7. import sys
  8. from typing import Iterable
  9. ROOT = Path(__file__).resolve().parents[1]
  10. DEFAULT_CONTRACT = ROOT / "generated" / "6400" / "host-contract.json"
  11. def crc16_ccitt_false(data: bytes) -> int:
  12. value = 0xFFFF
  13. for octet in data:
  14. value ^= octet << 8
  15. for _ in range(8):
  16. value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
  17. return value
  18. def frame(frame_type: int, payload: bytes = b"") -> bytes:
  19. if len(payload) > 255:
  20. raise ValueError("payload exceeds one-byte wire length")
  21. body = bytes((frame_type, len(payload))) + payload
  22. checksum = crc16_ccitt_false(body)
  23. return b"\xA5\x5A" + body + checksum.to_bytes(2, "little")
  24. class Encoder:
  25. def __init__(self, contract_path: Path = DEFAULT_CONTRACT) -> None:
  26. self.contract_path = contract_path
  27. self.contract = json.loads(contract_path.read_text(encoding="utf-8"))
  28. self.profiles = self.contract["canonical_profiles"]
  29. self.commands = self.contract["wire"]["commands"]
  30. def _type(self, profile: str, command: str) -> int:
  31. if profile not in self.profiles:
  32. raise ValueError(f"unknown canonical profile: {profile}")
  33. if command not in self.profiles[profile]["allowed_commands"]:
  34. raise ValueError(f"{command} is not supported by {profile}")
  35. return int(self.commands[command]["type"])
  36. def set_target(self, profile: str, target_celsius: int) -> bytes:
  37. if target_celsius != 0 and not 20 <= target_celsius <= 70:
  38. raise ValueError("target must be 0 or 20..70 C")
  39. return frame(self._type(profile, "SET_TARGET"), bytes((target_celsius,)))
  40. def get_snapshot(self, profile: str) -> bytes:
  41. return frame(self._type(profile, "GET_SNAPSHOT"))
  42. def set_stimulus(
  43. self,
  44. profile: str,
  45. duration_seconds: int,
  46. ptc: Iterable[int],
  47. front: Iterable[int],
  48. rear: Iterable[int],
  49. ) -> bytes:
  50. values = [duration_seconds, *ptc, *front, *rear]
  51. expected = self.commands["SET_STIMULUS"]["payload_fields"]
  52. counts = [int(field["count"]) for field in expected]
  53. if len(values) != sum(counts):
  54. raise ValueError("SET_STIMULUS requires duration + 24 PTC + 4 Front + 4 Rear values")
  55. offset = 0
  56. for field in expected:
  57. count = int(field["count"])
  58. minimum = int(field["minimum"])
  59. maximum = int(field["maximum"])
  60. for value in values[offset : offset + count]:
  61. if not minimum <= value <= maximum:
  62. raise ValueError(f"{field['name']} must be {minimum}..{maximum}")
  63. offset += count
  64. return frame(self._type(profile, "SET_STIMULUS"), bytes(values))
  65. def percent_list(text: str, count: int, label: str) -> list[int]:
  66. values = [int(value.strip()) for value in text.split(",") if value.strip()]
  67. if len(values) != count:
  68. raise argparse.ArgumentTypeError(f"{label} requires exactly {count} comma-separated percentages")
  69. if any(value < 0 or value > 100 for value in values):
  70. raise argparse.ArgumentTypeError(f"{label} percentages must be 0..100")
  71. return values
  72. def main(argv: list[str] | None = None) -> int:
  73. parser = argparse.ArgumentParser(description=__doc__)
  74. parser.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT)
  75. parser.add_argument("--profile", required=True)
  76. subparsers = parser.add_subparsers(dest="command", required=True)
  77. target_parser = subparsers.add_parser("set-target")
  78. target_parser.add_argument("celsius", type=int)
  79. subparsers.add_parser("get-snapshot")
  80. stimulus_parser = subparsers.add_parser("set-stimulus")
  81. stimulus_parser.add_argument("--duration", type=int, required=True)
  82. stimulus_parser.add_argument("--ptc", required=True)
  83. stimulus_parser.add_argument("--front", required=True)
  84. stimulus_parser.add_argument("--rear", required=True)
  85. args = parser.parse_args(argv)
  86. encoder = Encoder(args.contract)
  87. if args.command == "set-target":
  88. result = encoder.set_target(args.profile, args.celsius)
  89. elif args.command == "get-snapshot":
  90. result = encoder.get_snapshot(args.profile)
  91. else:
  92. result = encoder.set_stimulus(
  93. args.profile,
  94. args.duration,
  95. percent_list(args.ptc, 24, "PTC"),
  96. percent_list(args.front, 4, "Front"),
  97. percent_list(args.rear, 4, "Rear"),
  98. )
  99. print(result.hex().upper())
  100. return 0
  101. if __name__ == "__main__":
  102. try:
  103. raise SystemExit(main())
  104. except (KeyError, ValueError, json.JSONDecodeError) as exc:
  105. print(f"ERROR: {exc}", file=sys.stderr)
  106. raise SystemExit(2)