protocol_oracle.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #!/usr/bin/env python3
  2. """Independent Prod2U UART protocol oracle.
  3. Re-implements Header/Length/Type/Payload/CRC-16/CCITT-FALSE from the published
  4. contract. Must NOT import host Go protocol packages.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import json
  9. import sys
  10. from pathlib import Path
  11. POLY = 0x1021
  12. INIT = 0xFFFF
  13. HEADER0 = 0xA5
  14. HEADER1 = 0x5A
  15. TYPE_SET_ALL = 0x01
  16. TYPE_GET_TEMP = 0x02
  17. TYPE_GET_MOTOR = 0x03
  18. TYPE_TEMP_DATA = 0x82
  19. TYPE_MOTOR_DATA = 0x83
  20. SET_ALL_LEN = 11
  21. KNOWN_POSITIVE = {
  22. "set_all_all_zero_full_open",
  23. "set_all_doors_0_percent",
  24. "set_all_doors_50_percent",
  25. "set_all_doors_100_percent",
  26. "get_motor_status",
  27. "get_temperature",
  28. "motor_status_data_example",
  29. "all_invalid_temperature",
  30. }
  31. KNOWN_NEGATIVE = {
  32. "set_all_door_0x65_rejected",
  33. "set_all_legacy_14_rejected",
  34. }
  35. FRAME_KEYS_MIN = 6
  36. def crc16_ccitt_false(data: bytes) -> int:
  37. crc = INIT
  38. for b in data:
  39. crc ^= b << 8
  40. for _ in range(8):
  41. if crc & 0x8000:
  42. crc = ((crc << 1) ^ POLY) & 0xFFFF
  43. else:
  44. crc = (crc << 1) & 0xFFFF
  45. return crc
  46. def encode_set_all(fans: list[int], ptcs: list[int], door_z: int, door_x: int, door_y: int) -> bytes:
  47. payload = bytes([*fans, *ptcs, door_z, door_x, door_y])
  48. body = bytes([TYPE_SET_ALL, SET_ALL_LEN]) + payload
  49. crc = crc16_ccitt_false(body)
  50. return bytes([HEADER0, HEADER1]) + body + bytes([crc & 0xFF, (crc >> 8) & 0xFF])
  51. def encode_get(typ: int) -> bytes:
  52. body = bytes([typ, 0])
  53. crc = crc16_ccitt_false(body)
  54. return bytes([HEADER0, HEADER1]) + body + bytes([crc & 0xFF, (crc >> 8) & 0xFF])
  55. def frame_from_hex(hexstr: str) -> bytes:
  56. return bytes.fromhex(hexstr.replace(" ", "").strip())
  57. def is_frame_hex(s: str) -> bool:
  58. h = s.replace(" ", "").strip()
  59. if len(h) < 12 or len(h) % 2:
  60. return False
  61. try:
  62. raw = bytes.fromhex(h)
  63. except ValueError:
  64. return False
  65. return len(raw) >= 6 and raw[0] == HEADER0 and raw[1] == HEADER1
  66. def check_frame(name: str, hx: str) -> list[str]:
  67. fails = []
  68. raw = frame_from_hex(hx)
  69. if raw[0] != HEADER0 or raw[1] != HEADER1:
  70. fails.append(f"{name}: bad header")
  71. return fails
  72. body = raw[2:-2]
  73. got = crc16_ccitt_false(body)
  74. want = raw[-2] | (raw[-1] << 8)
  75. if got != want:
  76. fails.append(f"{name}: crc oracle={got:04x} frame={want:04x}")
  77. return fails
  78. def decode_set_all(raw: bytes) -> tuple[list[int], list[int], int, int, int] | None:
  79. if len(raw) < 17:
  80. return None
  81. if raw[0] != HEADER0 or raw[1] != HEADER1 or raw[2] != TYPE_SET_ALL or raw[3] != SET_ALL_LEN:
  82. return None
  83. payload = raw[4:15]
  84. return list(payload[0:4]), list(payload[4:8]), payload[8], payload[9], payload[10]
  85. def check_golden(golden: dict, min_positive: int, min_negative: int, min_frames: int) -> int:
  86. if not isinstance(golden, dict):
  87. print("FAIL: golden is not an object", file=sys.stderr)
  88. return 1
  89. pos = neg = frames = 0
  90. fails: list[str] = []
  91. seen_pos: set[str] = set()
  92. seen_neg: set[str] = set()
  93. for key, val in golden.items():
  94. if key in {"notes", "comment", "schema"}:
  95. continue
  96. if isinstance(val, dict):
  97. fails.append(f"unrecognized nested object field {key!r}")
  98. continue
  99. if not isinstance(val, str):
  100. fails.append(f"unrecognized field {key!r} type {type(val).__name__}")
  101. continue
  102. if key in KNOWN_NEGATIVE:
  103. neg += 1
  104. seen_neg.add(key)
  105. if is_frame_hex(val):
  106. fails.append(f"{key}: negative vector looks like a complete frame")
  107. continue
  108. if is_frame_hex(val):
  109. frames += 1
  110. if key in KNOWN_POSITIVE:
  111. pos += 1
  112. seen_pos.add(key)
  113. else:
  114. fails.append(f"unrecognized golden field {key!r} (frame not in known positive set)")
  115. continue
  116. fails.extend(check_frame(key, val))
  117. raw = frame_from_hex(val)
  118. if key == "get_motor_status" and raw != encode_get(TYPE_GET_MOTOR):
  119. fails.append(f"{key}: does not match independent GET_MOTOR encoding")
  120. if key == "get_temperature" and raw != encode_get(TYPE_GET_TEMP):
  121. fails.append(f"{key}: does not match independent GET_TEMP encoding")
  122. if key.startswith("set_all_") and key not in KNOWN_NEGATIVE:
  123. decoded = decode_set_all(raw)
  124. if decoded is None:
  125. fails.append(f"{key}: not an independent SET_ALL frame")
  126. elif encode_set_all(*decoded) != raw:
  127. fails.append(f"{key}: independent SET_ALL re-encode mismatch")
  128. continue
  129. fails.append(f"unrecognized golden field {key!r} (not a frame, not a known negative)")
  130. missing_pos = KNOWN_POSITIVE - seen_pos
  131. missing_neg = KNOWN_NEGATIVE - seen_neg
  132. if missing_pos:
  133. fails.append(f"missing positive vectors: {sorted(missing_pos)}")
  134. if missing_neg:
  135. fails.append(f"missing negative vectors: {sorted(missing_neg)}")
  136. print(f"positive_vectors_checked={pos}")
  137. print(f"negative_vectors_checked={neg}")
  138. print(f"frames_checked={frames}")
  139. if fails:
  140. for f in fails:
  141. print(f"FAIL {f}", file=sys.stderr)
  142. print("oracle_status=FAIL")
  143. return 1
  144. if pos + neg == 0 or frames == 0:
  145. print("oracle_status=FAIL", file=sys.stderr)
  146. print("FAIL: zero checks", file=sys.stderr)
  147. return 1
  148. if pos < min_positive or neg < min_negative or frames < min_frames:
  149. print(
  150. f"FAIL: counts below minimum pos={pos}<{min_positive} neg={neg}<{min_negative} frames={frames}<{min_frames}",
  151. file=sys.stderr,
  152. )
  153. print("oracle_status=FAIL")
  154. return 1
  155. print("oracle_status=PASS")
  156. return 0
  157. def main() -> int:
  158. ap = argparse.ArgumentParser()
  159. ap.add_argument("--golden", type=Path)
  160. ap.add_argument("--encode-demo", action="store_true")
  161. ap.add_argument("--repo-root", type=Path, default=None)
  162. ap.add_argument("--min-positive", type=int, default=len(KNOWN_POSITIVE))
  163. ap.add_argument("--min-negative", type=int, default=len(KNOWN_NEGATIVE))
  164. ap.add_argument("--min-frames", type=int, default=FRAME_KEYS_MIN)
  165. args = ap.parse_args()
  166. if args.encode_demo:
  167. print(encode_set_all([10, 10, 10, 10], [0, 0, 0, 0], 0, 0, 0).hex())
  168. return 0
  169. golden_path = args.golden
  170. if golden_path is None and args.repo_root is not None:
  171. golden_path = args.repo_root / "src" / "generated" / "golden-vectors.json"
  172. if golden_path is None:
  173. print("usage: protocol_oracle.py --golden FILE | --repo-root DIR | --encode-demo", file=sys.stderr)
  174. return 2
  175. data = json.loads(golden_path.read_text(encoding="utf-8"))
  176. return check_golden(data, args.min_positive, args.min_negative, args.min_frames)
  177. if __name__ == "__main__":
  178. raise SystemExit(main())