wiring_sync.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. """Synchronize FPGA/MCU logical pin mappings and electrical peripheral wiring across all board bundles."""
  2. from __future__ import annotations
  3. import hashlib
  4. import importlib.util
  5. import json
  6. from datetime import datetime, timezone
  7. from pathlib import Path
  8. from typing import Any
  9. from collections.abc import Mapping
  10. from jsonschema import Draft202012Validator
  11. from .annotations import expand_annotation_templates
  12. from .data import (
  13. _attach_related_resistors,
  14. _attach_structured_resistor_links,
  15. _merge_annotation,
  16. _merge_programming_annotation,
  17. _programming_guidance,
  18. _refresh_recommendation,
  19. _unique_strings,
  20. )
  21. ROOT = Path(__file__).resolve().parents[3]
  22. VIEWER_ROOT = ROOT / "tools" / "board-viewer"
  23. ANNOTATIONS_V12_PATH = ROOT / "config" / "board_viewer_annotations.fcb_fpga_mcu_v1_2.json"
  24. EXPECTATION_PATH = ROOT / "tests" / "board_viewer" / "fixtures" / "candidate_count_expectation.json"
  25. DATA_SCHEMA_PATH = ROOT / "schemas" / "board_viewer_data.schema.json"
  26. def _sha256_file(path: Path) -> str:
  27. h = hashlib.sha256()
  28. with path.open("rb") as stream:
  29. while chunk := stream.read(1024 * 1024):
  30. h.update(chunk)
  31. return h.hexdigest()
  32. def sync_v12_board_data_from_annotations(
  33. annotations_path: Path = ANNOTATIONS_V12_PATH,
  34. generated_dir: Path = VIEWER_ROOT / "generated",
  35. ) -> dict[str, Any]:
  36. """Apply updated V1.2 annotations directly to generated/board-data.json and refresh build-info hashes."""
  37. raw_annotations = json.loads(annotations_path.read_text(encoding="utf-8"))
  38. annotations = expand_annotation_templates(raw_annotations)
  39. board_data_path = generated_dir / "board-data.json"
  40. board_data = json.loads(board_data_path.read_text(encoding="utf-8"))
  41. tp_annotations: dict[str, Any] = annotations.get("touchpoints", {})
  42. updated_touchpoints = 0
  43. updated_pins = 0
  44. for tp in board_data.get("touchpoints", []):
  45. ref = str(tp.get("reference") or "")
  46. if ref not in tp_annotations:
  47. continue
  48. ann_tp = tp_annotations[ref]
  49. if isinstance(ann_tp, Mapping) and ann_tp.get("summary"):
  50. tp["summary"] = str(ann_tp["summary"])
  51. updated_touchpoints += 1
  52. ann_pins: dict[str, Any] = ann_tp.get("pins", {}) if isinstance(ann_tp, Mapping) else {}
  53. for pin in tp.get("pins", []):
  54. pnum = str(pin.get("number") or "")
  55. if pnum not in ann_pins:
  56. continue
  57. ann_pin = ann_pins[pnum]
  58. if isinstance(ann_pin, Mapping):
  59. _merge_annotation(pin, ann_pin)
  60. pin["evidence_sources"] = _unique_strings(list(pin.get("evidence_sources", [])))
  61. pin["programming"] = _programming_guidance(ref, pin)
  62. prog_ann = ann_pin.get("programming", {})
  63. if isinstance(prog_ann, Mapping):
  64. _merge_programming_annotation(pin["programming"], prog_ann)
  65. _refresh_recommendation(pin)
  66. updated_pins += 1
  67. if isinstance(board_data.get("resistors"), list):
  68. _attach_related_resistors(board_data["touchpoints"], board_data["resistors"])
  69. board_data["resistor_links"] = _attach_structured_resistor_links(
  70. annotations, board_data["resistors"], board_data["touchpoints"]
  71. )
  72. if "interfaces" in annotations:
  73. board_data["interfaces"] = annotations["interfaces"]
  74. if DATA_SCHEMA_PATH.is_file():
  75. schema = json.loads(DATA_SCHEMA_PATH.read_text(encoding="utf-8"))
  76. Draft202012Validator(schema).validate(board_data)
  77. board_data_path.write_text(
  78. json.dumps(board_data, indent=2, ensure_ascii=False) + "\n",
  79. encoding="utf-8",
  80. )
  81. build_info_path = generated_dir / "build-info.json"
  82. if build_info_path.is_file():
  83. build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
  84. for _src_name, src_meta in build_info.get("sources", {}).items():
  85. # Only annotations were consumed by this partial update.
  86. if _src_name != "annotations":
  87. continue
  88. if not isinstance(src_meta, dict) or not src_meta.get("path"):
  89. continue
  90. src_path = Path(src_meta["path"])
  91. if not src_path.is_absolute():
  92. src_path = ROOT / src_path
  93. if src_path.is_file():
  94. src_meta["sha256"] = _sha256_file(src_path)
  95. for asset_name, meta in build_info.get("assets", {}).items():
  96. # Geometry/import assets were not regenerated; retain their recorded hashes.
  97. if asset_name != "board-data.json":
  98. continue
  99. asset_file = generated_dir / asset_name
  100. if asset_file.is_file():
  101. meta["sha256"] = _sha256_file(asset_file)
  102. meta["bytes"] = asset_file.stat().st_size
  103. build_info["generated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  104. build_info_path.write_text(
  105. json.dumps(build_info, indent=2, ensure_ascii=False) + "\n",
  106. encoding="utf-8",
  107. )
  108. if EXPECTATION_PATH.is_file() and build_info_path.is_file():
  109. exp = json.loads(EXPECTATION_PATH.read_text(encoding="utf-8"))
  110. if "bound_to" in exp:
  111. bd_sha = _sha256_file(board_data_path)
  112. exp["bound_to"]["board_data_sha256"] = bd_sha
  113. exp["bound_to"]["board_data_asset_sha256"] = bd_sha
  114. exp["bound_to"]["build_info_sha256"] = _sha256_file(build_info_path)
  115. EXPECTATION_PATH.write_text(
  116. json.dumps(exp, indent=2, ensure_ascii=False) + "\n",
  117. encoding="utf-8",
  118. )
  119. return {
  120. "board": "v1_2",
  121. "updated_touchpoints": updated_touchpoints,
  122. "updated_pins": updated_pins,
  123. "host_ttl": {
  124. "connector": "CON146",
  125. "tx_pin": "CON146.1",
  126. "tx_ball": "H6",
  127. "tx_logical": "host_ttl_tx (SW_KEYLED3)",
  128. "rx_pin": "CON146.3",
  129. "rx_ball": "N7",
  130. "rx_logical": "host_ttl_rx (KEY_3)",
  131. "gnd_pins": ["CON146.2", "CON146.4"],
  132. },
  133. }
  134. def sync_all_boards_wiring(repository_root: Path = ROOT) -> dict[str, Any]:
  135. """Update V1.2 annotations and regenerate V2 bundles; leave V1.1 unchanged."""
  136. repo = Path(repository_root).resolve()
  137. viewer_dir = repo / "tools" / "board-viewer"
  138. v12_summary = sync_v12_board_data_from_annotations(
  139. annotations_path=repo / "config" / "board_viewer_annotations.fcb_fpga_mcu_v1_2.json",
  140. generated_dir=viewer_dir / "generated",
  141. )
  142. # Run V2.0 and V2.0_FAN generator
  143. v2_script = viewer_dir / "generate_v2_0_assets.py"
  144. spec = importlib.util.spec_from_file_location("generate_v2_0_assets", v2_script)
  145. if spec is None or spec.loader is None:
  146. raise RuntimeError(f"Unable to load {v2_script}")
  147. module = importlib.util.module_from_spec(spec)
  148. spec.loader.exec_module(module)
  149. module.generate_v2_0_mainboard()
  150. module.generate_v2_0_fan_board()
  151. # V1.1 is not regenerated by this command; keep its provenance unchanged.
  152. return {
  153. "status": "pass",
  154. "synchronized_boards": ["v1_2", "v2_0", "v2_0_fan"],
  155. "retained_boards": ["v1_1"],
  156. "v1_2": v12_summary,
  157. "v2_0": {
  158. "board": "v2_0",
  159. "host_ttl": {
  160. "connector": "CON12",
  161. "tx_pin": "CON12.3",
  162. "tx_ball": "K2",
  163. "tx_logical": "host_ttl_tx (EX_GPIO1) <-> STM32H7 P1.26 (PB11)",
  164. "rx_pin": "CON12.4",
  165. "rx_ball": "J4",
  166. "rx_logical": "host_ttl_rx (EX_GPIO2) <-> STM32H7 P1.25 (PB10)",
  167. },
  168. },
  169. "v1_1": {
  170. "board": "v1_1",
  171. "host_ttl": {
  172. "connector": "CON30",
  173. "tx_pin": "CON30.4",
  174. "tx_ball": "A10",
  175. "tx_logical": "host_ttl_tx (FAN_GPIO4)",
  176. "rx_pin": "CON30.3",
  177. "rx_ball": "B9",
  178. "rx_logical": "host_ttl_rx (FAN_GPIO3)",
  179. },
  180. },
  181. }