encode_6400_hex.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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_all(self, profile: str, ptc: Iterable[int], front: Iterable[int], rear: Iterable[int]) -> bytes:
  37. values = [*ptc, *front, *rear]
  38. if len(values) != 32 or any(not 0 <= value <= 100 for value in values):
  39. raise ValueError("SET_ALL requires 24 PTC + 4 Front + 4 Rear values in 0..100")
  40. return frame(self._type(profile, "SET_ALL"), bytes(values))
  41. def set_pid_target(self, profile: str, target_celsius: int) -> bytes:
  42. if not 20 <= target_celsius <= 70:
  43. raise ValueError("PID target must be 20..70 C")
  44. return frame(self._type(profile, "SET_PID_TARGET"), bytes((target_celsius,)))
  45. def get_snapshot(self, profile: str) -> bytes:
  46. return frame(self._type(profile, "GET_SNAPSHOT"))
  47. def set_stimulus(
  48. self,
  49. profile: str,
  50. duration_seconds: int,
  51. ptc: Iterable[int],
  52. front: Iterable[int],
  53. rear: Iterable[int],
  54. ) -> bytes:
  55. values = [duration_seconds, *ptc, *front, *rear]
  56. expected = self.commands["SET_STIMULUS"]["payload_fields"]
  57. counts = [int(field["count"]) for field in expected]
  58. if len(values) != sum(counts):
  59. raise ValueError("SET_STIMULUS requires duration + 24 PTC + 4 Front + 4 Rear values")
  60. offset = 0
  61. for field in expected:
  62. count = int(field["count"])
  63. minimum = int(field["minimum"])
  64. maximum = int(field["maximum"])
  65. for value in values[offset : offset + count]:
  66. if not minimum <= value <= maximum:
  67. raise ValueError(f"{field['name']} must be {minimum}..{maximum}")
  68. offset += count
  69. return frame(self._type(profile, "SET_STIMULUS"), bytes(values))
  70. def percent_list(text: str, count: int, label: str) -> list[int]:
  71. values = [int(value.strip()) for value in text.split(",") if value.strip()]
  72. if len(values) != count:
  73. raise argparse.ArgumentTypeError(f"{label} requires exactly {count} comma-separated percentages")
  74. if any(value < 0 or value > 100 for value in values):
  75. raise argparse.ArgumentTypeError(f"{label} percentages must be 0..100")
  76. return values
  77. def main(argv: list[str] | None = None) -> int:
  78. parser = argparse.ArgumentParser(description=__doc__)
  79. parser.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT)
  80. parser.add_argument("--profile", required=True)
  81. subparsers = parser.add_subparsers(dest="command", required=True)
  82. target_parser = subparsers.add_parser("set-pid-target")
  83. target_parser.add_argument("celsius", type=int)
  84. set_all_parser = subparsers.add_parser("set-all")
  85. set_all_parser.add_argument("--ptc", required=True)
  86. set_all_parser.add_argument("--front", required=True)
  87. set_all_parser.add_argument("--rear", required=True)
  88. subparsers.add_parser("get-snapshot")
  89. stimulus_parser = subparsers.add_parser("set-stimulus")
  90. stimulus_parser.add_argument("--duration", type=int, required=True)
  91. stimulus_parser.add_argument("--ptc", required=True)
  92. stimulus_parser.add_argument("--front", required=True)
  93. stimulus_parser.add_argument("--rear", required=True)
  94. args = parser.parse_args(argv)
  95. encoder = Encoder(args.contract)
  96. if args.command == "set-pid-target":
  97. result = encoder.set_pid_target(args.profile, args.celsius)
  98. elif args.command == "set-all":
  99. result = encoder.set_all(
  100. args.profile,
  101. percent_list(args.ptc, 24, "PTC"),
  102. percent_list(args.front, 4, "Front"),
  103. percent_list(args.rear, 4, "Rear"),
  104. )
  105. elif args.command == "get-snapshot":
  106. result = encoder.get_snapshot(args.profile)
  107. else:
  108. result = encoder.set_stimulus(
  109. args.profile,
  110. args.duration,
  111. percent_list(args.ptc, 24, "PTC"),
  112. percent_list(args.front, 4, "Front"),
  113. percent_list(args.rear, 4, "Rear"),
  114. )
  115. print(result.hex().upper())
  116. return 0
  117. if __name__ == "__main__":
  118. try:
  119. raise SystemExit(main())
  120. except (KeyError, ValueError, json.JSONDecodeError) as exc:
  121. print(f"ERROR: {exc}", file=sys.stderr)
  122. raise SystemExit(2)