#!/usr/bin/env python3 """6400-only project validation and artifact generation.""" from __future__ import annotations import hashlib import json import re from pathlib import Path from typing import Any, Mapping from tools.crc16_ccitt_nibble_ref import GET_TEMPERATURE, SET_ALL_6400_ALL_ZERO, frame_hex from tools.fw_targets import assert_6400_closure_clean, load_source_closure, unresolved_pins ROOT = Path(__file__).resolve().parents[1] SCHEMA_PATH = ROOT / "schemas" / "project_thermal_24ptc_8fan_v1.schema.json" PROFILE = "thermal-24ptc-8fan-v1" PROJECT_ID = "prod2u-6400-front-back" EXPECTED_PTC_NETS = ( "HEAT6", "HEAT5", "HEAT4", "HEAT3", "HEAT2", "HEAT1", "HEAT12", "HEAT11", "HEAT10", "HEAT9", "HEAT8", "HEAT7", "HEAT18", "HEAT17", "HEAT16", "HEAT15", "HEAT14", "HEAT13", "HEAT24", "HEAT23", "HEAT22", "HEAT21", "HEAT20", "HEAT19", ) EXPECTED_PTC_BALLS = ( "R7", "T6", "R5", "T4", "G16", "F16", "R3", "T2", "R1", "P1", "N1", "M1", "P7", "P8", "N16", "M16", "R16", "P16", "T12", "T13", "R10", "P10", "P9", "T9", ) EXPECTED_FAN_IN = ( (0, "C1_FAN_IN", "FAN_PWM3", "B1"), (2, "C2_FAN_IN", "FAN_PWM1", "C4"), (4, "C3_FAN_IN", "FAN_PWM2", "B5"), (6, "C4_FAN_IN", "FAN_PWM4", "A14"), ) EXPECTED_FAN_OUT = ( (1, "C1_FAN_OUT", "FAN_GPIO44", "P15", "CON64", 4), (3, "C2_FAN_OUT", "FAN_GPIO46", "N15", "CON66", 4), (5, "C3_FAN_OUT", "FAN_GPIO42", "M14", "CON62", 4), (7, "C4_FAN_OUT", "FAN_GPIO40", "P5", "CON60", 4), ) FORBIDDEN_MOTOR = ( "motors", "limits", "doors", "startup_close_seek", "door_motor_engine", "get_motor_status", ) GOLDEN_SET_ALL_ZERO = SET_ALL_6400_ALL_ZERO GOLDEN_GET_TEMPERATURE = GET_TEMPERATURE PTC_CONTRACT = ( (0, "C1_PTC_L1", "HEAT6", "R7", "CON18", 11, (13,)), (1, "C1_PTC_L2", "HEAT5", "T6", "CON18", 9, ()), (2, "C1_PTC_L3", "HEAT4", "R5", "CON18", 7, ()), (3, "C1_PTC_L4", "HEAT3", "T4", "CON18", 5, ()), (4, "C1_PTC_L5", "HEAT2", "G16", "CON18", 3, ()), (5, "C1_PTC_L6", "HEAT1", "F16", "CON18", 1, ()), (6, "C2_PTC_L1", "HEAT12", "R3", "CON27", 11, (13,)), (7, "C2_PTC_L2", "HEAT11", "T2", "CON27", 9, ()), (8, "C2_PTC_L3", "HEAT10", "R1", "CON27", 7, ()), (9, "C2_PTC_L4", "HEAT9", "P1", "CON27", 5, ()), (10, "C2_PTC_L5", "HEAT8", "N1", "CON27", 3, ()), (11, "C2_PTC_L6", "HEAT7", "M1", "CON27", 1, ()), (12, "C3_PTC_L1", "HEAT18", "P7", "CON28", 11, (13,)), (13, "C3_PTC_L2", "HEAT17", "P8", "CON28", 9, ()), (14, "C3_PTC_L3", "HEAT16", "N16", "CON28", 7, ()), (15, "C3_PTC_L4", "HEAT15", "M16", "CON28", 5, ()), (16, "C3_PTC_L5", "HEAT14", "R16", "CON28", 3, ()), (17, "C3_PTC_L6", "HEAT13", "P16", "CON28", 1, ()), (18, "C4_PTC_L1", "HEAT24", "T12", "CON29", 11, (13,)), (19, "C4_PTC_L2", "HEAT23", "T13", "CON29", 9, ()), (20, "C4_PTC_L3", "HEAT22", "R10", "CON29", 7, ()), (21, "C4_PTC_L4", "HEAT21", "P10", "CON29", 5, ()), (22, "C4_PTC_L5", "HEAT20", "P9", "CON29", 3, ()), (23, "C4_PTC_L6", "HEAT19", "T9", "CON29", 1, ()), ) FAN_CONTRACT = ( (0, 24, "C1_FAN_IN", "FAN_PWM3", "B1", "CON25", 7, "intake", "confirmed"), (1, 25, "C1_FAN_OUT", "FAN_GPIO44", "P15", "CON64", 4, "exhaust", "confirmed"), (2, 26, "C2_FAN_IN", "FAN_PWM1", "C4", "CON8", 7, "intake", "confirmed"), (3, 27, "C2_FAN_OUT", "FAN_GPIO46", "N15", "CON66", 4, "exhaust", "confirmed"), (4, 28, "C3_FAN_IN", "FAN_PWM2", "B5", "CON24", 7, "intake", "confirmed"), (5, 29, "C3_FAN_OUT", "FAN_GPIO42", "M14", "CON62", 4, "exhaust", "confirmed"), (6, 30, "C4_FAN_IN", "FAN_PWM4", "A14", "CON26", 7, "intake", "confirmed"), (7, 31, "C4_FAN_OUT", "FAN_GPIO40", "P5", "CON60", 4, "exhaust", "confirmed"), ) def validate_6400_project(payload: Mapping[str, Any]) -> None: validate_6400(payload) def _require(condition: bool, message: str) -> None: if not condition: raise ValueError(message) def _object(value: Any, name: str) -> Mapping[str, Any]: _require(isinstance(value, dict), f"{name} must be an object") return value def validate_6400(payload: Mapping[str, Any]) -> None: _require(payload.get("project_id") == PROJECT_ID, "6400 project_id mismatch") _require(payload.get("profile") == PROFILE, "6400 profile mismatch") features = _object(payload.get("features"), "features") for key in ("motors", "limits", "startup_calibration", "get_motor_status", "runtime_project_select"): _require(features.get(key) is False, f"features.{key} must be false") for key in FORBIDDEN_MOTOR: _require(key not in payload or key == "features", f"6400 must not declare {key}") _require("motors" not in payload and "limits" not in payload and "doors" not in payload, "6400 must omit motors/limits/doors") device = _object(payload["device"], "device") _require(device["part"] == "EF2L45BG256B" and device["clock_hz"] == 25_000_000, "device mismatch") uart = _object(payload["uart"], "uart") _require(uart["baud"] == 115200 and uart["clks_per_bit"] == 217, "UART mismatch") _require(uart["parity"] == "N" and uart["flow_control"] == "none", "UART framing mismatch") outputs = _object(payload["outputs"], "outputs") _require(outputs["ptc_count"] == 24 and outputs["fan_count"] == 8, "PTC/FAN count mismatch") _require(outputs["output_count"] == 32, "output_count must be 32") _require(len(outputs["ptc_channels"]) == 24 and len(outputs["fan_channels"]) == 8, "channel list length mismatch") _require(outputs["pwm_frequency_hz"] == 500, "PWM frequency must be 500") _require(outputs["pwm_phase_count"] == 100, "PWM phase count must be 100") _require(outputs["pwm_phase_clks"] == 500, "PWM phase clocks must be 500") _require(outputs["pwm_period_clks"] == 50_000, "PWM period must be 50000") _require(outputs["pwm_actual_frequency_hz"] == 500, "PWM actual frequency must be 500") _require(outputs["ptc_polarity"] == "active_high" and outputs["fan_polarity"] == "active_low", "polarity mismatch") _require(outputs["boot_targets"] == {"ptc": 0, "fan": 10}, "boot targets mismatch") _require(outputs["fan_board_inverts"] is True, "FAN board invert required") for index, channel in enumerate(outputs["ptc_channels"]): item = _object(channel, f"ptc[{index}]") _require(item["index"] == index, f"PTC index mismatch at {index}") _require(item["board_signal"] == EXPECTED_PTC_NETS[index], f"PTC net mismatch at {index}") _require(item["ball"] == EXPECTED_PTC_BALLS[index], f"PTC ball mismatch at {index}") _require(item["pin_status"] == "confirmed", f"PTC pin_status at {index}") _require(item["polarity"] == "active_high", "PTC polarity") _require(re.fullmatch(r"C[1-4]_PTC_L[1-6]", str(item["name"])), f"PTC name at {index}") if index % 6 == 0: _require(item.get("connector_pin13_parallel") is True, f"Pin13 parallel required at {index}") for index, channel in enumerate(outputs["fan_channels"]): item = _object(channel, f"fan[{index}]") _require(item["index"] == index, f"FAN index mismatch at {index}") _require(item["polarity"] == "active_low", "FAN polarity") _require(item["pin_status"] == "confirmed", f"FAN {index} must be confirmed") exp = FAN_CONTRACT[index] _require(item["name"] == exp[2], f"FAN name {index}") _require(item["board_signal"] == exp[3], f"FAN net {index}") _require(item["ball"] == exp[4], f"FAN ball {index}") _require(item["connector"] == exp[5], f"FAN connector {index}") _require(item["connector_pin"] == exp[6], f"FAN connector pin {index}") _require(item.get("role") == exp[7], f"FAN role {index}") if index % 2 == 1: _require(item.get("fg_used") is False, f"{item['name']} FG must stay unused") _require(item.get("fg_pin") == 3, f"{item['name']} FG is pin 3") temperature = _object(payload["temperature"], "temperature") _require(temperature["value_count"] == 27, "temperature count") _require(temperature["device_addresses"] == [73, 72, 75], "CT7428 addresses") _require(temperature["registers"] == [0, 1, 2, 3, 4, 5, 6, 7, 8], "register order") protocol = _object(payload["protocol"], "protocol") _require(protocol["header_hex"] == "A55A", "header") commands = _object(protocol["commands"], "commands") _require(commands == {"set_all": 1, "get_temperature": 2, "temperature_data": 130}, "command set") _require("get_motor_status" not in commands, "GET_MOTOR_STATUS must be absent") set_all = _object(protocol["set_all"], "set_all") _require(set_all["payload_length"] == 32 and set_all["frame_length"] == 38, "SET length") _require(set_all["ptc_offset"] == 0 and set_all["fan_offset"] == 24, "SET offsets") _require(set_all["response"] == "none", "no ACK") _require(protocol["crc"]["name"] == "CRC-16/CCITT-FALSE", "CRC name") _require(protocol["crc"]["wire_order"] == "little", "CRC wire order") watchdog = _object(payload["watchdog"], "watchdog") _require(watchdog["timeout_seconds"] == 30, "watchdog seconds") _require(watchdog["timeout_ticks"] == 60_000, "watchdog ticks") _require(watchdog["tick_us"] == 500 and watchdog["tick_clks"] == 12_500, "watchdog tick") _require(watchdog.get("enable_after_startup_complete") is False, "watchdog must arm after POR") _require(watchdog["target"] == {"ptc": 0, "fan": 10}, "watchdog targets") def load_6400_project(path: Path) -> dict[str, Any]: payload = json.loads(Path(path).read_text(encoding="utf-8")) _require(isinstance(payload, dict), "project root must be an object") if SCHEMA_PATH.is_file(): from jsonschema import Draft202012Validator schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda error: list(error.absolute_path)) if errors: location = ".".join(str(part) for part in errors[0].absolute_path) or "project" raise ValueError(f"6400 schema violation at {location}: {errors[0].message}") validate_6400(payload) return payload def _crc16_ccitt_false(data: bytes) -> int: crc = 0xFFFF for value in data: crc ^= value << 8 for _ in range(8): crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF return crc def _frame_hex_local(frame_type: int, payload: bytes) -> str: body = bytes((frame_type, len(payload))) + payload crc = _crc16_ccitt_false(body) return (b"\xA5\x5A" + body + crc.to_bytes(2, "little")).hex().upper() def render_params(project: Mapping[str, Any]) -> str: outputs = project["outputs"] temperature = project["temperature"] uart = project["uart"] watchdog = project["watchdog"] protocol = project["protocol"] commands = protocol["commands"] frame_inter_byte_timeout_cycles = project["device"]["clock_hz"] * project["timeouts"]["frame_inter_byte_ms"] // 1000 lines = [ "// Generated from 6400 project.json. Do not edit.", f"`define FB_CLOCK_HZ {project['device']['clock_hz']}", f"`define P4_CLOCK_HZ {project['device']['clock_hz']}", f"`define P4_UART_BAUD {uart['baud']}", f"`define P4_UART_CLKS_PER_BIT {uart['clks_per_bit']}", f"`define P4_PTC_COUNT {outputs['ptc_count']}", f"`define P4_FAN_COUNT {outputs['fan_count']}", f"`define P4_OUTPUT_CHANNEL_COUNT {outputs['output_count']}", f"`define P4_PWM_PROTOCOL_WIDTH {outputs['pwm_bits']}", f"`define P4_PWM_INTERNAL_WIDTH {outputs['pwm_internal_width']}", f"`define P4_PWM_MAX_DUTY {outputs['pwm_max_duty']}", f"`define P4_PWM_PHASE_COUNT {outputs['pwm_phase_count']}", f"`define P4_PWM_FREQUENCY_HZ {outputs['pwm_frequency_hz']}", f"`define P4_PWM_PHASE_CLKS {outputs['pwm_phase_clks']}", f"`define P4_PWM_PERIOD_CLKS {outputs['pwm_period_clks']}", f"`define P4_CMD_SET_ALL 8'h{commands['set_all']:02X}", f"`define P4_CMD_GET_TEMPERATURE 8'h{commands['get_temperature']:02X}", f"`define P4_CMD_TEMPERATURE_DATA 8'h{commands['temperature_data']:02X}", f"`define P4_RSP_TEMPERATURE 8'h{commands['temperature_data']:02X}", f"`define P4_SET_ALL_PAYLOAD_LENGTH {protocol['set_all']['payload_length']}", f"`define P4_FRAME_INTER_BYTE_TIMEOUT_CYCLES {frame_inter_byte_timeout_cycles}", f"`define P4_TEMPERATURE_COUNT {temperature['value_count']}", f"`define P4_TEMP_MAX_CELSIUS {temperature['maximum_celsius']}", f"`define P4_PTC_DEFAULT_TARGET 8'h{outputs['ptc_default']:02X}", f"`define P4_FAN_DEFAULT_TARGET 8'h{outputs['fan_default']:02X}", f"`define P4_WATCHDOG_TIMEOUT_SECONDS {watchdog['timeout_seconds']}", f"`define P4_WATCHDOG_TICK_US {watchdog['tick_us']}", f"`define P4_WATCHDOG_TICK_CLKS {watchdog['tick_clks']}", f"`define P4_WATCHDOG_TIMEOUT_TICKS {watchdog['timeout_ticks']}", f"`define P4_WATCHDOG_PTC_TARGET 8'h{watchdog['target']['ptc']:02X}", f"`define P4_WATCHDOG_FAN_TARGET 8'h{watchdog['target']['fan']:02X}", ] lines.extend( f"`define P4_TEMP_DEVICE_ADDR_{index} 7'h{address:02X}" for index, address in enumerate(temperature["device_addresses"]) ) lines.extend( f"`define P4_TEMP_REGISTER_{index} 8'h{register:02X}" for index, register in enumerate(temperature["registers"]) ) lines.extend( line.replace("`define P4_", "`define FB_") for line in list(lines) if line.startswith("`define P4_") ) lines.append("") return "\n".join(lines) def render_adc_text(project: Mapping[str, Any]) -> str: lines = [ "# Generated from 6400 project.json. Confirmed pins only.", "# Exhaust FAN PWM is CON64/66/62/60 pin 4. Pin 3 FG is unused and absent.", ] pins = project["pins"] lines.append(f"set_pin_assignment {{ sys_clk }} {{ LOCATION = {project['device']['clock_ball']}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}") lines.append(f"set_pin_assignment {{ host_uart_rx }} {{ LOCATION = {pins['host_uart_rx']}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}") lines.append(f"set_pin_assignment {{ host_uart_tx }} {{ LOCATION = {pins['host_uart_tx']}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}") lines.append(f"set_pin_assignment {{ temp_scl }} {{ LOCATION = {pins['temp_scl']}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}") lines.append(f"set_pin_assignment {{ temp_sda }} {{ LOCATION = {pins['temp_sda']}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}") for channel in project["outputs"]["ptc_channels"]: lines.append( f"set_pin_assignment {{ {channel['signal']} }} {{ LOCATION = {channel['ball']}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}" ) for channel in project["outputs"]["fan_channels"]: if channel.get("pin_status") == "confirmed" and channel.get("ball"): lines.append( f"set_pin_assignment {{ {channel['signal']} }} {{ LOCATION = {channel['ball']}; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }}" ) return "\n".join(lines) + "\n" def generate_6400( project_path: Path | None = None, output_root: Path | None = None, *, generated_rel: str | None = None, source_closure_path: Path | None = None, target_alias: str = "6400", ) -> dict[str, Any]: if output_root is None: root = Path(project_path) if project_path is not None else ROOT if root.is_dir() and (root / "projects").is_dir(): project_path = root / "projects" / "prod2u-6400-front-back" / "project.json" output_root = root / "src" generated_rel = generated_rel or "generated/6400" else: raise TypeError("generate_6400 requires project_path and output_root") if generated_rel is None: generated_rel = "generated" project = load_6400_project(project_path) output = Path(output_root) / generated_rel output.mkdir(parents=True, exist_ok=True) closure_path = Path(source_closure_path) if source_closure_path else ROOT / "projects" / "prod2u-6400-front-back" / "source-closure.json" sources = load_source_closure(closure_path, PROJECT_ID) assert_6400_closure_clean(sources) config_hash = hashlib.sha256(Path(project_path).read_bytes()).hexdigest() params_name = "prod2u_6400_front_back_params.vh" (output / params_name).write_text(render_params(project), encoding="ascii", newline="\n") unresolved = unresolved_pins(project) summary = { "project_id": PROJECT_ID, "target_alias": target_alias, "profile": PROFILE, "top_module": "prod2u_6400_front_back_top", "set_all_payload_len": 32, "set_all_frame_len": 38, "temperature_payload_len": 27, "temperature_frame_len": 33, "pwm_frequency_hz": 500, "pwm_period_clks": 50000, "pwm_phase_clks": 500, "actual_frequency_hz": 500.0, "unresolved_pins": unresolved, "release_status": "release_blocked" if unresolved else "release-ready", "release_blocked": bool(unresolved), "project_config_sha256": config_hash, "watchdog_timeout_ticks": 60000, } field_order = [item["name"] for item in project["outputs"]["ptc_channels"]] field_order += [item["name"] for item in project["outputs"]["fan_channels"]] contract = { "schema": "prod2u-simple-host-contract-v1", "project_id": PROJECT_ID, "target_alias": target_alias, "profile": PROFILE, "uart": project["uart"], "protocol": project["protocol"], "commands": { "set_all": { "type": "0x01", "payload_length": 32, "frame_length": 38, "response": "none", "duty_range": [0, 100], "field_order": field_order, }, "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"}, "temperature_data": {"type": "0x82", "payload_length": 27, "frame_length": 33}, }, "outputs": project["outputs"], "temperature": project["temperature"], "watchdog": project["watchdog"], "features": project["features"], "unresolved_pins": unresolved, } local_zero = _frame_hex_local(0x01, bytes(32)) independent_zero = frame_hex(0x01, bytes(32)) _require(local_zero == SET_ALL_6400_ALL_ZERO, "local 6400 zero SET CRC mismatch") _require(independent_zero == SET_ALL_6400_ALL_ZERO, "independent 6400 zero SET CRC mismatch") _require(_frame_hex_local(0x02, b"") == GET_TEMPERATURE, "GET_TEMPERATURE golden mismatch") def _write_json(path: Path, payload: Mapping[str, Any]) -> None: path.write_text(json.dumps(dict(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n") _write_json(output / "host-contract.json", contract) _write_json(output / "project-summary.json", summary) _write_json( output / "golden-vectors.json", { "set_all_all_zero": SET_ALL_6400_ALL_ZERO, "set_all_all_100": _frame_hex_local(0x01, bytes([100] * 32)), "get_temperature": GET_TEMPERATURE, "all_invalid_temperature": _frame_hex_local(0x82, bytes([0xFF] * 27)), "notes": { "set_all_all_zero": "Independent nibble CRC and bit CRC both yield 0D8C.", "crc_wire_order": "little-endian CRC-16/CCITT-FALSE", }, }, ) channel_map = [ { "payload_offset": channel["index"], "logical_name": channel["name"], "kind": "ptc", "net": channel["board_signal"], "ball": channel["ball"], "connector": channel["connector"], "connector_pin": channel["connector_pin"], "pin13_parallel": channel.get("connector_pin13_parallel", False), "polarity": channel["polarity"], "pin_status": channel["pin_status"], "evidence": channel.get("evidence"), } for channel in project["outputs"]["ptc_channels"] ] + [ { "payload_offset": 24 + channel["index"], "logical_name": channel["name"], "kind": "fan", "role": channel.get("role"), "net": channel.get("board_signal"), "ball": channel.get("ball"), "connector": channel.get("connector"), "connector_pin": channel.get("connector_pin"), "polarity": channel["polarity"], "pin_status": channel["pin_status"], "evidence": channel.get("evidence"), } for channel in project["outputs"]["fan_channels"] ] _write_json(output / "channel-map.json", {"target_alias": "6400", "channels": channel_map}) _write_json( output / "unresolved-pins.json", { "target_alias": "6400", "unresolved": unresolved, "production_bitstream": "blocked_td_not_wired" if not unresolved else "blocked", "simulation_allowed": True, "non_production_synthesis_estimate_allowed": True, "required_electrical_fields": ["fpga_ball", "connector", "connector_pin", "net_name"], }, ) source_payload = { "schema": "prod2u-simple-source-manifest-template-v1", "lifecycle": "historical_only", "active_product": False, "superseded_by": "products/6400-front-rear/source-closure.json", "project_id": PROJECT_ID, "target_alias": target_alias, "top_module": "prod2u_6400_front_back_top", "project_config_sha256": config_hash, "sources": list(sources), "generated_from": "project.json", "contract": { "uart": project["uart"], "protocol": project["protocol"], "set_all_payload_length": 32, "temperature_frame_length": 33, "motors": False, "limits": False, }, "unresolved_pins": unresolved, "release_status": summary["release_status"], } _write_json(output / "td-source-manifest.json", source_payload) manifest_hash = hashlib.sha256((output / "td-source-manifest.json").read_bytes()).hexdigest() source_payload["source_manifest_sha256"] = manifest_hash _write_json(output / "td-source-manifest.json", source_payload) adc_text = ( "# HISTORICAL_ONLY: obsolete interleaved 6400 output map; " "current TD uses constraints/prod2u_6400_front_back.adc.\n" + render_adc_text(project) ) (output / "prod2u_6400_front_back.adc").write_text(adc_text, encoding="ascii", newline="\n") return summary