| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- """Synchronize FPGA/MCU logical pin mappings and electrical peripheral wiring across all board bundles."""
- from __future__ import annotations
- import hashlib
- import importlib.util
- import json
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any
- from collections.abc import Mapping
- from jsonschema import Draft202012Validator
- from .annotations import expand_annotation_templates
- from .data import (
- _attach_related_resistors,
- _attach_structured_resistor_links,
- _merge_annotation,
- _merge_programming_annotation,
- _programming_guidance,
- _refresh_recommendation,
- _unique_strings,
- )
- ROOT = Path(__file__).resolve().parents[3]
- VIEWER_ROOT = ROOT / "tools" / "board-viewer"
- ANNOTATIONS_V12_PATH = ROOT / "config" / "board_viewer_annotations.fcb_fpga_mcu_v1_2.json"
- EXPECTATION_PATH = ROOT / "tests" / "board_viewer" / "fixtures" / "candidate_count_expectation.json"
- DATA_SCHEMA_PATH = ROOT / "schemas" / "board_viewer_data.schema.json"
- def _sha256_file(path: Path) -> str:
- h = hashlib.sha256()
- with path.open("rb") as stream:
- while chunk := stream.read(1024 * 1024):
- h.update(chunk)
- return h.hexdigest()
- def sync_v12_board_data_from_annotations(
- annotations_path: Path = ANNOTATIONS_V12_PATH,
- generated_dir: Path = VIEWER_ROOT / "generated",
- ) -> dict[str, Any]:
- """Apply updated V1.2 annotations directly to generated/board-data.json and refresh build-info hashes."""
- raw_annotations = json.loads(annotations_path.read_text(encoding="utf-8"))
- annotations = expand_annotation_templates(raw_annotations)
- board_data_path = generated_dir / "board-data.json"
- board_data = json.loads(board_data_path.read_text(encoding="utf-8"))
- tp_annotations: dict[str, Any] = annotations.get("touchpoints", {})
- updated_touchpoints = 0
- updated_pins = 0
- for tp in board_data.get("touchpoints", []):
- ref = str(tp.get("reference") or "")
- if ref not in tp_annotations:
- continue
- ann_tp = tp_annotations[ref]
- if isinstance(ann_tp, Mapping) and ann_tp.get("summary"):
- tp["summary"] = str(ann_tp["summary"])
- updated_touchpoints += 1
- ann_pins: dict[str, Any] = ann_tp.get("pins", {}) if isinstance(ann_tp, Mapping) else {}
- for pin in tp.get("pins", []):
- pnum = str(pin.get("number") or "")
- if pnum not in ann_pins:
- continue
- ann_pin = ann_pins[pnum]
- if isinstance(ann_pin, Mapping):
- _merge_annotation(pin, ann_pin)
- pin["evidence_sources"] = _unique_strings(list(pin.get("evidence_sources", [])))
- pin["programming"] = _programming_guidance(ref, pin)
- prog_ann = ann_pin.get("programming", {})
- if isinstance(prog_ann, Mapping):
- _merge_programming_annotation(pin["programming"], prog_ann)
- _refresh_recommendation(pin)
- updated_pins += 1
- if isinstance(board_data.get("resistors"), list):
- _attach_related_resistors(board_data["touchpoints"], board_data["resistors"])
- board_data["resistor_links"] = _attach_structured_resistor_links(
- annotations, board_data["resistors"], board_data["touchpoints"]
- )
- if "interfaces" in annotations:
- board_data["interfaces"] = annotations["interfaces"]
- if DATA_SCHEMA_PATH.is_file():
- schema = json.loads(DATA_SCHEMA_PATH.read_text(encoding="utf-8"))
- Draft202012Validator(schema).validate(board_data)
- board_data_path.write_text(
- json.dumps(board_data, indent=2, ensure_ascii=False) + "\n",
- encoding="utf-8",
- )
- build_info_path = generated_dir / "build-info.json"
- if build_info_path.is_file():
- build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
- for _src_name, src_meta in build_info.get("sources", {}).items():
- # Only annotations were consumed by this partial update.
- if _src_name != "annotations":
- continue
- if not isinstance(src_meta, dict) or not src_meta.get("path"):
- continue
- src_path = Path(src_meta["path"])
- if not src_path.is_absolute():
- src_path = ROOT / src_path
- if src_path.is_file():
- src_meta["sha256"] = _sha256_file(src_path)
- for asset_name, meta in build_info.get("assets", {}).items():
- # Geometry/import assets were not regenerated; retain their recorded hashes.
- if asset_name != "board-data.json":
- continue
- asset_file = generated_dir / asset_name
- if asset_file.is_file():
- meta["sha256"] = _sha256_file(asset_file)
- meta["bytes"] = asset_file.stat().st_size
- build_info["generated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
- build_info_path.write_text(
- json.dumps(build_info, indent=2, ensure_ascii=False) + "\n",
- encoding="utf-8",
- )
- if EXPECTATION_PATH.is_file() and build_info_path.is_file():
- exp = json.loads(EXPECTATION_PATH.read_text(encoding="utf-8"))
- if "bound_to" in exp:
- bd_sha = _sha256_file(board_data_path)
- exp["bound_to"]["board_data_sha256"] = bd_sha
- exp["bound_to"]["board_data_asset_sha256"] = bd_sha
- exp["bound_to"]["build_info_sha256"] = _sha256_file(build_info_path)
- EXPECTATION_PATH.write_text(
- json.dumps(exp, indent=2, ensure_ascii=False) + "\n",
- encoding="utf-8",
- )
- return {
- "board": "v1_2",
- "updated_touchpoints": updated_touchpoints,
- "updated_pins": updated_pins,
- "host_ttl": {
- "connector": "CON146",
- "tx_pin": "CON146.1",
- "tx_ball": "H6",
- "tx_logical": "host_ttl_tx (SW_KEYLED3)",
- "rx_pin": "CON146.3",
- "rx_ball": "N7",
- "rx_logical": "host_ttl_rx (KEY_3)",
- "gnd_pins": ["CON146.2", "CON146.4"],
- },
- }
- def sync_all_boards_wiring(repository_root: Path = ROOT) -> dict[str, Any]:
- """Update V1.2 annotations and regenerate V2 bundles; leave V1.1 unchanged."""
- repo = Path(repository_root).resolve()
- viewer_dir = repo / "tools" / "board-viewer"
- v12_summary = sync_v12_board_data_from_annotations(
- annotations_path=repo / "config" / "board_viewer_annotations.fcb_fpga_mcu_v1_2.json",
- generated_dir=viewer_dir / "generated",
- )
- # Run V2.0 and V2.0_FAN generator
- v2_script = viewer_dir / "generate_v2_0_assets.py"
- spec = importlib.util.spec_from_file_location("generate_v2_0_assets", v2_script)
- if spec is None or spec.loader is None:
- raise RuntimeError(f"Unable to load {v2_script}")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- module.generate_v2_0_mainboard()
- module.generate_v2_0_fan_board()
- # V1.1 is not regenerated by this command; keep its provenance unchanged.
- return {
- "status": "pass",
- "synchronized_boards": ["v1_2", "v2_0", "v2_0_fan"],
- "retained_boards": ["v1_1"],
- "v1_2": v12_summary,
- "v2_0": {
- "board": "v2_0",
- "host_ttl": {
- "connector": "CON12",
- "tx_pin": "CON12.3",
- "tx_ball": "K2",
- "tx_logical": "host_ttl_tx (EX_GPIO1) <-> STM32H7 P1.26 (PB11)",
- "rx_pin": "CON12.4",
- "rx_ball": "J4",
- "rx_logical": "host_ttl_rx (EX_GPIO2) <-> STM32H7 P1.25 (PB10)",
- },
- },
- "v1_1": {
- "board": "v1_1",
- "host_ttl": {
- "connector": "CON30",
- "tx_pin": "CON30.4",
- "tx_ball": "A10",
- "tx_logical": "host_ttl_tx (FAN_GPIO4)",
- "rx_pin": "CON30.3",
- "rx_ball": "B9",
- "rx_logical": "host_ttl_rx (FAN_GPIO3)",
- },
- },
- }
|