فهرست منبع

feat(host): add 6400 target ACK snapshot transport

root 3 ماه پیش
والد
کامیت
47287e428d

+ 1 - 0
contracts/6400/SHA256SUMS

@@ -0,0 +1 @@
+f1277d466369134b33e970899d6883d5fc5e0d63c8d975824a439c1b0d08b65d  host-contract.json

+ 893 - 0
contracts/6400/host-contract.json

@@ -0,0 +1,893 @@
+{
+  "channel_map": {
+    "channels": [
+      {
+        "air_lane": 0,
+        "bmc_temperature_index": 0,
+        "cpu": 0,
+        "cpu_slot": 0,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 0,
+        "logical_dimm": 0,
+        "physical_label": "CPU0_DIMM0",
+        "primary_cohort": true,
+        "ptc_channel": 0,
+        "rear_fan_channel": 0,
+        "thermal_zone": 0
+      },
+      {
+        "air_lane": 0,
+        "bmc_temperature_index": 1,
+        "cpu": 0,
+        "cpu_slot": 1,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 0,
+        "logical_dimm": 1,
+        "physical_label": "CPU0_DIMM1",
+        "primary_cohort": true,
+        "ptc_channel": 1,
+        "rear_fan_channel": 0,
+        "thermal_zone": 0
+      },
+      {
+        "air_lane": 0,
+        "bmc_temperature_index": 2,
+        "cpu": 0,
+        "cpu_slot": 2,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 0,
+        "logical_dimm": 2,
+        "physical_label": "CPU0_DIMM2",
+        "primary_cohort": true,
+        "ptc_channel": 2,
+        "rear_fan_channel": 0,
+        "thermal_zone": 0
+      },
+      {
+        "air_lane": 0,
+        "bmc_temperature_index": 3,
+        "cpu": 0,
+        "cpu_slot": 3,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 0,
+        "logical_dimm": 3,
+        "physical_label": "CPU0_DIMM3",
+        "primary_cohort": true,
+        "ptc_channel": 3,
+        "rear_fan_channel": 0,
+        "thermal_zone": 0
+      },
+      {
+        "air_lane": 0,
+        "bmc_temperature_index": 4,
+        "cpu": 0,
+        "cpu_slot": 4,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 0,
+        "logical_dimm": 4,
+        "physical_label": "CPU0_DIMM4",
+        "primary_cohort": true,
+        "ptc_channel": 4,
+        "rear_fan_channel": 0,
+        "thermal_zone": 0
+      },
+      {
+        "air_lane": 0,
+        "bmc_temperature_index": 5,
+        "cpu": 0,
+        "cpu_slot": 5,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 0,
+        "logical_dimm": 5,
+        "physical_label": "CPU0_DIMM5",
+        "primary_cohort": true,
+        "ptc_channel": 5,
+        "rear_fan_channel": 0,
+        "thermal_zone": 0
+      },
+      {
+        "air_lane": 1,
+        "bmc_temperature_index": 6,
+        "cpu": 0,
+        "cpu_slot": 6,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 1,
+        "logical_dimm": 6,
+        "physical_label": "CPU0_DIMM6",
+        "primary_cohort": true,
+        "ptc_channel": 6,
+        "rear_fan_channel": 1,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 1,
+        "bmc_temperature_index": 7,
+        "cpu": 0,
+        "cpu_slot": 7,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 1,
+        "logical_dimm": 7,
+        "physical_label": "CPU0_DIMM7",
+        "primary_cohort": true,
+        "ptc_channel": 7,
+        "rear_fan_channel": 1,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 1,
+        "bmc_temperature_index": 8,
+        "cpu": 0,
+        "cpu_slot": 8,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 1,
+        "logical_dimm": 8,
+        "physical_label": "CPU0_DIMM8",
+        "primary_cohort": true,
+        "ptc_channel": 8,
+        "rear_fan_channel": 1,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 1,
+        "bmc_temperature_index": 9,
+        "cpu": 0,
+        "cpu_slot": 9,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 1,
+        "logical_dimm": 9,
+        "physical_label": "CPU0_DIMM9",
+        "primary_cohort": true,
+        "ptc_channel": 9,
+        "rear_fan_channel": 1,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 1,
+        "bmc_temperature_index": 10,
+        "cpu": 0,
+        "cpu_slot": 10,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 1,
+        "logical_dimm": 10,
+        "physical_label": "CPU0_DIMM10",
+        "primary_cohort": true,
+        "ptc_channel": 10,
+        "rear_fan_channel": 1,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 1,
+        "bmc_temperature_index": 11,
+        "cpu": 0,
+        "cpu_slot": 11,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 1,
+        "logical_dimm": 11,
+        "physical_label": "CPU0_DIMM11",
+        "primary_cohort": true,
+        "ptc_channel": 11,
+        "rear_fan_channel": 1,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 2,
+        "bmc_temperature_index": 12,
+        "cpu": 1,
+        "cpu_slot": 0,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 2,
+        "logical_dimm": 12,
+        "physical_label": "CPU1_DIMM0",
+        "primary_cohort": true,
+        "ptc_channel": 12,
+        "rear_fan_channel": 2,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 2,
+        "bmc_temperature_index": 13,
+        "cpu": 1,
+        "cpu_slot": 1,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 2,
+        "logical_dimm": 13,
+        "physical_label": "CPU1_DIMM1",
+        "primary_cohort": true,
+        "ptc_channel": 13,
+        "rear_fan_channel": 2,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 2,
+        "bmc_temperature_index": 14,
+        "cpu": 1,
+        "cpu_slot": 2,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 2,
+        "logical_dimm": 14,
+        "physical_label": "CPU1_DIMM2",
+        "primary_cohort": true,
+        "ptc_channel": 14,
+        "rear_fan_channel": 2,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 2,
+        "bmc_temperature_index": 15,
+        "cpu": 1,
+        "cpu_slot": 3,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 2,
+        "logical_dimm": 15,
+        "physical_label": "CPU1_DIMM3",
+        "primary_cohort": true,
+        "ptc_channel": 15,
+        "rear_fan_channel": 2,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 2,
+        "bmc_temperature_index": 16,
+        "cpu": 1,
+        "cpu_slot": 4,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 2,
+        "logical_dimm": 16,
+        "physical_label": "CPU1_DIMM4",
+        "primary_cohort": true,
+        "ptc_channel": 16,
+        "rear_fan_channel": 2,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 2,
+        "bmc_temperature_index": 17,
+        "cpu": 1,
+        "cpu_slot": 5,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 2,
+        "logical_dimm": 17,
+        "physical_label": "CPU1_DIMM5",
+        "primary_cohort": true,
+        "ptc_channel": 17,
+        "rear_fan_channel": 2,
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 3,
+        "bmc_temperature_index": 18,
+        "cpu": 1,
+        "cpu_slot": 6,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 3,
+        "logical_dimm": 18,
+        "physical_label": "CPU1_DIMM6",
+        "primary_cohort": false,
+        "ptc_channel": 18,
+        "rear_fan_channel": 3,
+        "thermal_zone": 2
+      },
+      {
+        "air_lane": 3,
+        "bmc_temperature_index": 19,
+        "cpu": 1,
+        "cpu_slot": 7,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 3,
+        "logical_dimm": 19,
+        "physical_label": "CPU1_DIMM7",
+        "primary_cohort": false,
+        "ptc_channel": 19,
+        "rear_fan_channel": 3,
+        "thermal_zone": 2
+      },
+      {
+        "air_lane": 3,
+        "bmc_temperature_index": 20,
+        "cpu": 1,
+        "cpu_slot": 8,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 3,
+        "logical_dimm": 20,
+        "physical_label": "CPU1_DIMM8",
+        "primary_cohort": false,
+        "ptc_channel": 20,
+        "rear_fan_channel": 3,
+        "thermal_zone": 2
+      },
+      {
+        "air_lane": 3,
+        "bmc_temperature_index": 21,
+        "cpu": 1,
+        "cpu_slot": 9,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 3,
+        "logical_dimm": 21,
+        "physical_label": "CPU1_DIMM9",
+        "primary_cohort": false,
+        "ptc_channel": 21,
+        "rear_fan_channel": 3,
+        "thermal_zone": 2
+      },
+      {
+        "air_lane": 3,
+        "bmc_temperature_index": 22,
+        "cpu": 1,
+        "cpu_slot": 10,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 3,
+        "logical_dimm": 22,
+        "physical_label": "CPU1_DIMM10",
+        "primary_cohort": false,
+        "ptc_channel": 22,
+        "rear_fan_channel": 3,
+        "thermal_zone": 2
+      },
+      {
+        "air_lane": 3,
+        "bmc_temperature_index": 23,
+        "cpu": 1,
+        "cpu_slot": 11,
+        "ct7428_channel": "unknown",
+        "enabled": true,
+        "evidence": {
+          "confidence": "confirmed",
+          "location": "topology",
+          "source": "active-task-contract"
+        },
+        "front_fan_channel": 3,
+        "logical_dimm": 23,
+        "physical_label": "CPU1_DIMM11",
+        "primary_cohort": false,
+        "ptc_channel": 23,
+        "rear_fan_channel": 3,
+        "thermal_zone": 2
+      }
+    ],
+    "lanes": [
+      {
+        "air_lane": 0,
+        "cohort": "primary",
+        "cpu": 0,
+        "cpu_slots": [
+          0,
+          5
+        ],
+        "thermal_zone": 0
+      },
+      {
+        "air_lane": 1,
+        "cohort": "primary",
+        "cpu": 0,
+        "cpu_slots": [
+          6,
+          11
+        ],
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 2,
+        "cohort": "primary",
+        "cpu": 1,
+        "cpu_slots": [
+          0,
+          5
+        ],
+        "thermal_zone": 1
+      },
+      {
+        "air_lane": 3,
+        "cohort": "holdout",
+        "cpu": 1,
+        "cpu_slots": [
+          6,
+          11
+        ],
+        "thermal_zone": 2
+      }
+    ],
+    "product": "6400-front-rear-v1",
+    "schema": "prod2u-6400-channel-map-v1"
+  },
+  "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+  "controller_coefficients": {
+    "classes": {
+      "CENTER": {
+        "ki_q4_12": 3,
+        "kp_q4_12": 24,
+        "lanes": [
+          1,
+          2
+        ]
+      },
+      "EDGE": {
+        "ki_q4_12": 4,
+        "kp_q4_12": 32,
+        "lanes": [
+          0,
+          3
+        ]
+      }
+    },
+    "limits_centi_degC": {
+      "hard": 7700,
+      "pretrip": 7600,
+      "recovery_above_target": 200,
+      "soft": 7400
+    },
+    "recovery_epochs": 3,
+    "schema": "prod2u-6400-controller-coefficients-v1",
+    "targets_centi_degC": {
+      "default": 7000,
+      "ideal_band": 100,
+      "preheat_offset": -500,
+      "qualification_band": 700
+    },
+    "truth_label": "SIMULATION_DEFAULT_NOT_HARDWARE_TUNED"
+  },
+  "fan_control": {
+    "duty": {
+      "hard": 100,
+      "nominal": 30,
+      "protection": 80,
+      "reset": 10,
+      "stopped": 30,
+      "warm": 50
+    },
+    "front_rear_independent": true,
+    "invalid_lane_threshold": 2,
+    "schema": "prod2u-6400-fan-control-v1",
+    "temperature_centi_degC": {
+      "hard": 7700,
+      "protection": 7400,
+      "warm_delta_from_target": -300
+    },
+    "truth_label": "SIMULATION_DEFAULT_NOT_HARDWARE_TUNED"
+  },
+  "fixed_point": {
+    "algorithm": "incremental_pi",
+    "coefficient": {
+      "format": "Q4.12",
+      "fractional_bits": 12,
+      "integer_bits": 4,
+      "signed_bits": 16
+    },
+    "error": {
+      "signed_bits": 16,
+      "unit": "centi_degC"
+    },
+    "kd": 0,
+    "output": {
+      "format": "Q8.8",
+      "fractional_bits": 8,
+      "integer_bits": 8,
+      "max": 25600,
+      "min": 0,
+      "signed_bits": 16
+    },
+    "product": {
+      "delta_to_output_shift": 4,
+      "rounding": "half_away_from_zero",
+      "signed_bits": 32
+    },
+    "schema": "prod2u-6400-fixed-point-v1",
+    "slew_limit_q8_8_per_epoch": 1280,
+    "temperature": {
+      "scale": 100,
+      "signed_bits": 16,
+      "unit": "centi_degC"
+    }
+  },
+  "golden_vectors": {
+    "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+    "frames": {
+      "get_snapshot": "A55A02006D7B",
+      "set_target_20": "A55A010114289A",
+      "set_target_70": "A55A0101469FE0",
+      "set_target_ack": "A55A8100A635",
+      "set_target_stop": "A55A0101009DC8",
+      "stimulus_ack": "A55A8300C453",
+      "stimulus_all_zero_one_second": "A55A03210100000000000000000000000000000000000000000000000000000000000000009782"
+    },
+    "schema": "prod2u-6400-golden-vectors-v1"
+  },
+  "schema": "prod2u-6400-host-contract-v1",
+  "snapshot": {
+    "byte_order": "little",
+    "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+    "fields": [
+      {
+        "name": "control_state",
+        "offset": 0,
+        "size": 1,
+        "type": "u8"
+      },
+      {
+        "name": "fault_flags",
+        "offset": 1,
+        "size": 2,
+        "type": "u16"
+      },
+      {
+        "name": "current_target",
+        "offset": 3,
+        "size": 1,
+        "type": "u8",
+        "unit": "degC"
+      },
+      {
+        "name": "host_target_seen",
+        "offset": 4,
+        "size": 1,
+        "type": "u8"
+      },
+      {
+        "name": "bmc_epoch",
+        "offset": 5,
+        "size": 2,
+        "type": "u16"
+      },
+      {
+        "name": "ct_epoch",
+        "offset": 7,
+        "size": 2,
+        "type": "u16"
+      },
+      {
+        "name": "control_epoch",
+        "offset": 9,
+        "size": 2,
+        "type": "u16"
+      },
+      {
+        "name": "bmc_age",
+        "offset": 11,
+        "size": 2,
+        "type": "u16",
+        "unit": "control_ticks"
+      },
+      {
+        "name": "ct_age",
+        "offset": 13,
+        "size": 2,
+        "type": "u16",
+        "unit": "control_ticks"
+      },
+      {
+        "count": 24,
+        "name": "bmc_raw",
+        "offset": 15,
+        "size": 48,
+        "type": "u16"
+      },
+      {
+        "count": 3,
+        "name": "bmc_valid_mask",
+        "offset": 63,
+        "size": 3,
+        "type": "bytes"
+      },
+      {
+        "count": 27,
+        "name": "ct_raw",
+        "offset": 66,
+        "size": 54,
+        "type": "u16"
+      },
+      {
+        "count": 4,
+        "name": "ct_valid_mask",
+        "offset": 120,
+        "size": 4,
+        "type": "bytes"
+      },
+      {
+        "count": 24,
+        "name": "ptc_requested",
+        "offset": 124,
+        "size": 24,
+        "type": "u8"
+      },
+      {
+        "count": 24,
+        "name": "ptc_applied",
+        "offset": 148,
+        "size": 24,
+        "type": "u8"
+      },
+      {
+        "count": 4,
+        "name": "front_requested",
+        "offset": 172,
+        "size": 4,
+        "type": "u8"
+      },
+      {
+        "count": 4,
+        "name": "front_applied",
+        "offset": 176,
+        "size": 4,
+        "type": "u8"
+      },
+      {
+        "count": 4,
+        "name": "rear_requested",
+        "offset": 180,
+        "size": 4,
+        "type": "u8"
+      },
+      {
+        "count": 4,
+        "name": "rear_applied",
+        "offset": 184,
+        "size": 4,
+        "type": "u8"
+      },
+      {
+        "count": 3,
+        "name": "safety_override_mask",
+        "offset": 188,
+        "size": 3,
+        "type": "bytes"
+      },
+      {
+        "name": "lane_fault_mask",
+        "offset": 191,
+        "size": 1,
+        "type": "u8"
+      },
+      {
+        "name": "global_fault",
+        "offset": 192,
+        "size": 1,
+        "type": "u8"
+      }
+    ],
+    "payload_length": 193,
+    "schema": "prod2u-6400-snapshot-v1"
+  },
+  "wire": {
+    "bmc_uart": {
+      "baud": 115200,
+      "clks_per_bit": 217,
+      "format": "8N1",
+      "poll_ascii": "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03\n",
+      "response_data_bytes": 48,
+      "rs232": {
+        "connector": "CON77",
+        "rx_ball": "M9",
+        "status": "confirmed",
+        "tx_ball": "L10"
+      }
+    },
+    "clock_hz": 25000000,
+    "commands": {
+      "GET_SNAPSHOT": {
+        "payload_length": 0,
+        "response": "SNAPSHOT_DATA",
+        "type": 2
+      },
+      "SET_STIMULUS": {
+        "payload_length": 33,
+        "profiles": [
+          "identification",
+          "sim-debug"
+        ],
+        "response": "SET_STIMULUS_ACK",
+        "type": 3
+      },
+      "SET_TARGET": {
+        "payload_length": 1,
+        "response": "SET_TARGET_ACK",
+        "type": 1,
+        "valid": [
+          0,
+          "20-70"
+        ]
+      }
+    },
+    "crc": {
+      "coverage": "type_length_payload",
+      "initial": 65535,
+      "name": "CRC-16/CCITT-FALSE",
+      "polynomial": 4129,
+      "reflect_input": false,
+      "reflect_output": false,
+      "wire_order": "little",
+      "xor_output": 0
+    },
+    "device": "EF2L45BG256B",
+    "forbidden_fields": [
+      "protocol_version",
+      "project_id",
+      "profile_id",
+      "capability",
+      "sequence",
+      "transaction_id",
+      "timestamp",
+      "tlv",
+      "nack"
+    ],
+    "header": [
+      165,
+      90
+    ],
+    "host_uart": {
+      "baud": 921600,
+      "fixed_candidate_clks_per_bit": 27,
+      "format": "8N1",
+      "rs232": {
+        "connector": "CON78",
+        "rx_ball": "N11",
+        "status": "confirmed",
+        "tx_ball": "M10"
+      },
+      "ttl": {
+        "connector": "unknown",
+        "level": "LVCMOS33",
+        "rx_ball": "unknown",
+        "status": "unbound",
+        "tx_ball": "unknown"
+      }
+    },
+    "invalid_behavior": "silent_drop",
+    "outstanding_transactions": 1,
+    "responses": {
+      "SET_STIMULUS_ACK": {
+        "payload_length": 0,
+        "profiles": [
+          "identification",
+          "sim-debug"
+        ],
+        "type": 131
+      },
+      "SET_TARGET_ACK": {
+        "payload_length": 0,
+        "type": 129
+      },
+      "SNAPSHOT_DATA": {
+        "payload_contract": "6400-snapshot.yaml",
+        "type": 130
+      }
+    },
+    "schema": "prod2u-6400-wire-v1"
+  }
+}

+ 146 - 0
internal/protocol6400/frame.go

@@ -0,0 +1,146 @@
+package protocol6400
+
+import (
+	"encoding/binary"
+	"errors"
+	"fmt"
+)
+
+const (
+	Header0 byte   = 0xA5
+	Header1 byte   = 0x5A
+	CRCPoly uint16 = 0x1021
+	CRCInit uint16 = 0xFFFF
+)
+
+var (
+	ErrHeader       = errors.New("invalid frame header")
+	ErrLength       = errors.New("invalid frame length")
+	ErrCRC          = errors.New("CRC mismatch")
+	ErrType         = errors.New("unknown frame type")
+	ErrTargetRange  = errors.New("target must be 0 or 20..70 C")
+	ErrDutyRange    = errors.New("duty must be 0..100")
+	ErrDuration     = errors.New("stimulus duration must be 1..255 seconds")
+	ErrNotSupported = errors.New("operation not supported by firmware profile")
+)
+
+type Frame struct {
+	Type    byte
+	Payload []byte
+}
+
+type Stimulus struct {
+	DurationSeconds byte
+	PTC             [24]byte
+	Front           [4]byte
+	Rear            [4]byte
+}
+
+func CRC16(data []byte) uint16 {
+	crc := CRCInit
+	for _, value := range data {
+		crc ^= uint16(value) << 8
+		for bit := 0; bit < 8; bit++ {
+			if crc&0x8000 != 0 {
+				crc = (crc << 1) ^ CRCPoly
+			} else {
+				crc <<= 1
+			}
+		}
+	}
+	return crc
+}
+
+func expectedLength(frameType byte) (int, error) {
+	switch frameType {
+	case CmdSetTarget:
+		return 1, nil
+	case CmdGetSnapshot, RspSetTargetAck, RspStimulusAck:
+		return 0, nil
+	case CmdSetStimulus:
+		return 33, nil
+	case RspSnapshot:
+		return SnapshotPayloadLen, nil
+	default:
+		return 0, fmt.Errorf("%w: 0x%02X", ErrType, frameType)
+	}
+}
+
+func Encode(frameType byte, payload []byte) ([]byte, error) {
+	want, err := expectedLength(frameType)
+	if err != nil {
+		return nil, err
+	}
+	if len(payload) != want {
+		return nil, fmt.Errorf("%w: type 0x%02X want %d got %d", ErrLength, frameType, want, len(payload))
+	}
+	body := make([]byte, 0, 2+len(payload))
+	body = append(body, frameType, byte(len(payload)))
+	body = append(body, payload...)
+	crc := CRC16(body)
+	out := []byte{Header0, Header1}
+	out = append(out, body...)
+	out = append(out, byte(crc), byte(crc>>8))
+	return out, nil
+}
+
+func Decode(raw []byte) (Frame, error) {
+	if len(raw) < 6 {
+		return Frame{}, ErrLength
+	}
+	if raw[0] != Header0 || raw[1] != Header1 {
+		return Frame{}, ErrHeader
+	}
+	n := int(raw[3])
+	if len(raw) != n+6 {
+		return Frame{}, ErrLength
+	}
+	want, err := expectedLength(raw[2])
+	if err != nil || want != n {
+		if err != nil {
+			return Frame{}, err
+		}
+		return Frame{}, ErrLength
+	}
+	got := binary.LittleEndian.Uint16(raw[len(raw)-2:])
+	if got != CRC16(raw[2:len(raw)-2]) {
+		return Frame{}, ErrCRC
+	}
+	payload := append([]byte(nil), raw[4:len(raw)-2]...)
+	return Frame{Type: raw[2], Payload: payload}, nil
+}
+
+func SetTargetRequest(target byte) ([]byte, error) {
+	if target != 0 && (target < 20 || target > 70) {
+		return nil, ErrTargetRange
+	}
+	return Encode(CmdSetTarget, []byte{target})
+}
+
+func GetSnapshotRequest() []byte {
+	value, err := Encode(CmdGetSnapshot, nil)
+	if err != nil {
+		panic(err)
+	}
+	return value
+}
+
+func StimulusRequest(profile string, value Stimulus) ([]byte, error) {
+	if profile == "production" || profile == "6400-control" {
+		return nil, ErrNotSupported
+	}
+	if value.DurationSeconds == 0 {
+		return nil, ErrDuration
+	}
+	payload := make([]byte, 0, 33)
+	payload = append(payload, value.DurationSeconds)
+	for _, group := range [][]byte{value.PTC[:], value.Front[:], value.Rear[:]} {
+		for _, duty := range group {
+			if duty > 100 {
+				return nil, ErrDutyRange
+			}
+			payload = append(payload, duty)
+		}
+	}
+	return Encode(CmdSetStimulus, payload)
+}

+ 59 - 0
internal/protocol6400/frame_test.go

@@ -0,0 +1,59 @@
+package protocol6400
+
+import (
+	"encoding/hex"
+	"errors"
+	"testing"
+)
+
+func mustHex(t *testing.T, value string) []byte {
+	t.Helper()
+	out, err := hex.DecodeString(value)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return out
+}
+
+func TestGeneratedGoldenFrames(t *testing.T) {
+	cases := map[byte]string{0: GoldenSetTargetStop, 20: GoldenSetTarget20, 70: GoldenSetTarget70}
+	for target, want := range cases {
+		got, err := SetTargetRequest(target)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if hex.EncodeToString(got) != want {
+			t.Fatalf("target %d got %x want %s", target, got, want)
+		}
+	}
+	if got := GetSnapshotRequest(); hex.EncodeToString(got) != GoldenGetSnapshot {
+		t.Fatalf("GET got %x", got)
+	}
+}
+
+func TestTargetRangeAndCRC(t *testing.T) {
+	for _, value := range []byte{1, 19, 71, 255} {
+		if _, err := SetTargetRequest(value); !errors.Is(err, ErrTargetRange) {
+			t.Fatalf("target %d error %v", value, err)
+		}
+	}
+	raw := mustHex(t, GoldenSetTarget70)
+	raw[len(raw)-1] ^= 1
+	if _, err := Decode(raw); !errors.Is(err, ErrCRC) {
+		t.Fatalf("CRC error %v", err)
+	}
+}
+
+func TestProductionRejectsStimulus(t *testing.T) {
+	if _, err := StimulusRequest("production", Stimulus{DurationSeconds: 1}); !errors.Is(err, ErrNotSupported) {
+		t.Fatalf("production stimulus error %v", err)
+	}
+	value := Stimulus{DurationSeconds: 1}
+	raw, err := StimulusRequest("identification", value)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if hex.EncodeToString(raw) != GoldenStimulusAllZeroOneSecond {
+		t.Fatalf("stimulus got %x", raw)
+	}
+}

+ 41 - 0
internal/protocol6400/generated_contract.go

@@ -0,0 +1,41 @@
+// Code generated by tools/import_6400_contract.py; DO NOT EDIT.
+package protocol6400
+
+const ContractSHA256 = "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1"
+const SnapshotPayloadLen = 193
+const CmdSetTarget byte = 0x01
+const CmdGetSnapshot byte = 0x02
+const CmdSetStimulus byte = 0x03
+const RspSetTargetAck byte = 0x81
+const RspSnapshot byte = 0x82
+const RspStimulusAck byte = 0x83
+const HostBaud = 921600
+
+const SnapshotControlStateOffset = 0
+const SnapshotFaultFlagsOffset = 1
+const SnapshotCurrentTargetOffset = 3
+const SnapshotHostTargetSeenOffset = 4
+const SnapshotBMCEpochOffset = 5
+const SnapshotCTEpochOffset = 7
+const SnapshotControlEpochOffset = 9
+const SnapshotBMCAgeOffset = 11
+const SnapshotCTAgeOffset = 13
+const SnapshotBMCRawOffset = 15
+const SnapshotBMCValidMaskOffset = 63
+const SnapshotCTRawOffset = 66
+const SnapshotCTValidMaskOffset = 120
+const SnapshotPTCRequestedOffset = 124
+const SnapshotPTCAppliedOffset = 148
+const SnapshotFrontRequestedOffset = 172
+const SnapshotFrontAppliedOffset = 176
+const SnapshotRearRequestedOffset = 180
+const SnapshotRearAppliedOffset = 184
+const SnapshotSafetyOverrideMaskOffset = 188
+const SnapshotLaneFaultMaskOffset = 191
+const SnapshotGlobalFaultOffset = 192
+
+const GoldenSetTargetStop = "a55a0101009dc8"
+const GoldenSetTarget20 = "a55a010114289a"
+const GoldenSetTarget70 = "a55a0101469fe0"
+const GoldenGetSnapshot = "a55a02006d7b"
+const GoldenStimulusAllZeroOneSecond = "a55a03210100000000000000000000000000000000000000000000000000000000000000009782"

+ 56 - 0
internal/protocol6400/parser.go

@@ -0,0 +1,56 @@
+package protocol6400
+
+import "time"
+
+type Parsed struct {
+	Frame Frame
+	Raw   []byte
+	Err   error
+}
+
+type StreamParser struct {
+	buffer    []byte
+	lastByte  time.Time
+	interByte time.Duration
+}
+
+func NewStreamParser(interByte time.Duration) *StreamParser {
+	return &StreamParser{interByte: interByte}
+}
+
+func (p *StreamParser) Reset() { p.buffer = p.buffer[:0] }
+
+func (p *StreamParser) Push(data []byte, now time.Time) []Parsed {
+	if len(p.buffer) > 0 && p.interByte > 0 && !p.lastByte.IsZero() && now.Sub(p.lastByte) > p.interByte {
+		p.Reset()
+	}
+	if len(data) > 0 {
+		p.lastByte = now
+	}
+	p.buffer = append(p.buffer, data...)
+	var out []Parsed
+	for {
+		for len(p.buffer) > 0 && p.buffer[0] != Header0 {
+			p.buffer = p.buffer[1:]
+		}
+		if len(p.buffer) < 2 {
+			break
+		}
+		if p.buffer[1] != Header1 {
+			p.buffer = p.buffer[1:]
+			continue
+		}
+		if len(p.buffer) < 4 {
+			break
+		}
+		total := int(p.buffer[3]) + 6
+		if len(p.buffer) < total {
+			break
+		}
+		raw := append([]byte(nil), p.buffer[:total]...)
+		p.buffer = p.buffer[total:]
+		frame, err := Decode(raw)
+		out = append(out, Parsed{Frame: frame, Raw: raw, Err: err})
+	}
+	return out
+}

+ 69 - 0
internal/protocol6400/snapshot.go

@@ -0,0 +1,69 @@
+package protocol6400
+
+import (
+	"encoding/binary"
+	"fmt"
+)
+
+type Snapshot struct {
+	ControlState   byte
+	FaultFlags     uint16
+	CurrentTarget  byte
+	HostTargetSeen bool
+	BMCEpoch       uint16
+	CTEpoch        uint16
+	ControlEpoch   uint16
+	BMCAge         uint16
+	CTAge          uint16
+	BMCRaw         [24]uint16
+	BMCValid       [24]bool
+	CTRaw          [27]uint16
+	CTValid        [27]bool
+	PTCRequested   [24]byte
+	PTCApplied     [24]byte
+	FrontRequested [4]byte
+	FrontApplied   [4]byte
+	RearRequested  [4]byte
+	RearApplied    [4]byte
+	SafetyOverride [24]bool
+	LaneFaultMask  byte
+	GlobalFault    bool
+}
+
+func maskBit(payload []byte, offset, index int) bool {
+	return payload[offset+index/8]&(1<<uint(index%8)) != 0
+}
+
+func DecodeSnapshot(payload []byte) (Snapshot, error) {
+	if len(payload) != SnapshotPayloadLen {
+		return Snapshot{}, fmt.Errorf("%w: snapshot want %d got %d", ErrLength, SnapshotPayloadLen, len(payload))
+	}
+	var out Snapshot
+	out.ControlState = payload[SnapshotControlStateOffset]
+	out.FaultFlags = binary.LittleEndian.Uint16(payload[SnapshotFaultFlagsOffset:])
+	out.CurrentTarget = payload[SnapshotCurrentTargetOffset]
+	out.HostTargetSeen = payload[SnapshotHostTargetSeenOffset] != 0
+	out.BMCEpoch = binary.LittleEndian.Uint16(payload[SnapshotBMCEpochOffset:])
+	out.CTEpoch = binary.LittleEndian.Uint16(payload[SnapshotCTEpochOffset:])
+	out.ControlEpoch = binary.LittleEndian.Uint16(payload[SnapshotControlEpochOffset:])
+	out.BMCAge = binary.LittleEndian.Uint16(payload[SnapshotBMCAgeOffset:])
+	out.CTAge = binary.LittleEndian.Uint16(payload[SnapshotCTAgeOffset:])
+	for i := range out.BMCRaw {
+		out.BMCRaw[i] = binary.LittleEndian.Uint16(payload[SnapshotBMCRawOffset+i*2:])
+		out.BMCValid[i] = maskBit(payload, SnapshotBMCValidMaskOffset, i)
+		out.PTCRequested[i] = payload[SnapshotPTCRequestedOffset+i]
+		out.PTCApplied[i] = payload[SnapshotPTCAppliedOffset+i]
+		out.SafetyOverride[i] = maskBit(payload, SnapshotSafetyOverrideMaskOffset, i)
+	}
+	for i := range out.CTRaw {
+		out.CTRaw[i] = binary.LittleEndian.Uint16(payload[SnapshotCTRawOffset+i*2:])
+		out.CTValid[i] = maskBit(payload, SnapshotCTValidMaskOffset, i)
+	}
+	copy(out.FrontRequested[:], payload[SnapshotFrontRequestedOffset:SnapshotFrontRequestedOffset+4])
+	copy(out.FrontApplied[:], payload[SnapshotFrontAppliedOffset:SnapshotFrontAppliedOffset+4])
+	copy(out.RearRequested[:], payload[SnapshotRearRequestedOffset:SnapshotRearRequestedOffset+4])
+	copy(out.RearApplied[:], payload[SnapshotRearAppliedOffset:SnapshotRearAppliedOffset+4])
+	out.LaneFaultMask = payload[SnapshotLaneFaultMaskOffset]
+	out.GlobalFault = payload[SnapshotGlobalFaultOffset] != 0
+	return out, nil
+}

+ 16 - 3
internal/serialtransport/termios_linux.go

@@ -13,6 +13,10 @@ import (
 )
 
 func Configure1152008N1(fd int) error {
+	return ConfigureBaud8N1(fd, 115200)
+}
+
+func ConfigureBaud8N1(fd int, baud int) error {
 	t, err := unix.IoctlGetTermios(fd, unix.TCGETS)
 	if err != nil {
 		return fmt.Errorf("tcgets: %w", err)
@@ -22,9 +26,18 @@ func Configure1152008N1(fd int) error {
 	t.Lflag = 0
 	t.Cflag = unix.CLOCAL | unix.CREAD | unix.CS8
 	t.Cflag &^= unix.CBAUD | unix.CBAUDEX | unix.PARENB | unix.CSTOPB | unix.CRTSCTS
-	t.Cflag |= unix.B115200
-	t.Ispeed = unix.B115200
-	t.Ospeed = unix.B115200
+	var speed uint32
+	switch baud {
+	case 115200:
+		speed = unix.B115200
+	case 921600:
+		speed = unix.B921600
+	default:
+		return fmt.Errorf("unsupported baud %d", baud)
+	}
+	t.Cflag |= speed
+	t.Ispeed = speed
+	t.Ospeed = speed
 	t.Cc[unix.VMIN] = 0
 	t.Cc[unix.VTIME] = 0
 	if err := unix.IoctlSetTermios(fd, unix.TCSETS, t); err != nil {

+ 152 - 0
internal/thermaltransport/client_linux.go

@@ -0,0 +1,152 @@
+//go:build linux
+
+package thermaltransport
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"strings"
+	"sync"
+	"time"
+
+	"golang.org/x/sys/unix"
+	"hth/internal/protocol6400"
+	"hth/internal/serialtransport"
+)
+
+type Client struct {
+	mu      sync.Mutex
+	file    *os.File
+	path    string
+	profile string
+	timeout time.Duration
+	retries int
+	parser  *protocol6400.StreamParser
+	locked  bool
+}
+
+func Open(path, profile string, timeout time.Duration, retries int) (*Client, error) {
+	file, err := os.OpenFile(path, os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
+	if err != nil {
+		return nil, err
+	}
+	locked := false
+	if !strings.HasPrefix(path, "/dev/pts/") {
+		if err := serialtransport.FlockExclusive(int(file.Fd())); err != nil {
+			file.Close()
+			return nil, fmt.Errorf("exclusive serial ownership: %w", err)
+		}
+		locked = true
+		if err := serialtransport.ConfigureBaud8N1(int(file.Fd()), protocol6400.HostBaud); err != nil {
+			serialtransport.Funlock(int(file.Fd()))
+			file.Close()
+			return nil, err
+		}
+	} else if err := serialtransport.ConfigurePTYRaw(int(file.Fd())); err != nil {
+		file.Close()
+		return nil, err
+	}
+	return &Client{file: file, path: path, profile: profile, timeout: timeout, retries: retries, parser: protocol6400.NewStreamParser(10 * time.Millisecond), locked: locked}, nil
+}
+
+func (c *Client) Close() error {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	if c.file == nil {
+		return nil
+	}
+	if c.locked {
+		_ = serialtransport.Funlock(int(c.file.Fd()))
+	}
+	err := c.file.Close()
+	c.file = nil
+	return err
+}
+
+func (c *Client) transact(ctx context.Context, request []byte, responseType byte) (protocol6400.Frame, error) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	if c.file == nil {
+		return protocol6400.Frame{}, os.ErrClosed
+	}
+	deadline := time.Now().Add(c.timeout)
+	if value, ok := ctx.Deadline(); ok && value.Before(deadline) {
+		deadline = value
+	}
+	_ = c.file.SetDeadline(deadline)
+	c.parser.Reset()
+	written, err := c.file.Write(request)
+	if err != nil {
+		return protocol6400.Frame{}, err
+	}
+	if written != len(request) {
+		return protocol6400.Frame{}, io.ErrShortWrite
+	}
+	buffer := make([]byte, 256)
+	for {
+		if err := ctx.Err(); err != nil {
+			return protocol6400.Frame{}, err
+		}
+		n, err := c.file.Read(buffer)
+		now := time.Now()
+		if n > 0 {
+			for _, item := range c.parser.Push(buffer[:n], now) {
+				if item.Err != nil {
+					return protocol6400.Frame{}, item.Err
+				}
+				if item.Frame.Type != responseType {
+					return protocol6400.Frame{}, fmt.Errorf("unexpected response 0x%02x", item.Frame.Type)
+				}
+				return item.Frame, nil
+			}
+		}
+		if err != nil {
+			if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
+				return protocol6400.Frame{}, context.DeadlineExceeded
+			}
+			if errors.Is(err, io.EOF) && strings.HasPrefix(c.path, "/dev/pts/") {
+				continue
+			}
+			return protocol6400.Frame{}, err
+		}
+	}
+}
+
+func (c *Client) SetTarget(ctx context.Context, target byte) error {
+	request, err := protocol6400.SetTargetRequest(target)
+	if err != nil {
+		return err
+	}
+	var last error
+	for attempt := 0; attempt <= c.retries; attempt++ {
+		if _, err := c.transact(ctx, request, protocol6400.RspSetTargetAck); err == nil {
+			return nil
+		} else {
+			last = err
+		}
+	}
+	return last
+}
+
+func (c *Client) Stop(ctx context.Context) error { return c.SetTarget(ctx, 0) }
+
+func (c *Client) GetSnapshot(ctx context.Context) (protocol6400.Snapshot, []byte, error) {
+	frame, err := c.transact(ctx, protocol6400.GetSnapshotRequest(), protocol6400.RspSnapshot)
+	if err != nil {
+		return protocol6400.Snapshot{}, nil, err
+	}
+	value, err := protocol6400.DecodeSnapshot(frame.Payload)
+	return value, frame.Payload, err
+}
+
+func (c *Client) RunStimulus(ctx context.Context, value protocol6400.Stimulus) error {
+	request, err := protocol6400.StimulusRequest(c.profile, value)
+	if err != nil {
+		return err
+	}
+	_, err = c.transact(ctx, request, protocol6400.RspStimulusAck)
+	return err
+}

+ 96 - 0
internal/thermaltransport/client_linux_test.go

@@ -0,0 +1,96 @@
+//go:build linux
+
+package thermaltransport
+
+import (
+	"context"
+	"os"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"golang.org/x/sys/unix"
+	"hth/internal/protocol6400"
+	"hth/internal/serialtransport"
+)
+
+func serveThermalPTY(t *testing.T, master *os.File, dropFirstACK bool, done chan<- struct{}) {
+	t.Helper()
+	parser := protocol6400.NewStreamParser(20 * time.Millisecond)
+	buffer := make([]byte, 256)
+	var sets atomic.Int32
+	for {
+		_ = master.SetReadDeadline(time.Now().Add(2 * time.Second))
+		n, err := master.Read(buffer)
+		if err != nil {
+			return
+		}
+		for _, item := range parser.Push(buffer[:n], time.Now()) {
+			if item.Err != nil {
+				t.Errorf("request parse: %v", item.Err)
+				return
+			}
+			var response []byte
+			switch item.Frame.Type {
+			case protocol6400.CmdSetTarget:
+				count := sets.Add(1)
+				if dropFirstACK && count == 1 {
+					continue
+				}
+				response, _ = protocol6400.Encode(protocol6400.RspSetTargetAck, nil)
+			case protocol6400.CmdGetSnapshot:
+				payload := make([]byte, protocol6400.SnapshotPayloadLen)
+				payload[0] = 4
+				payload[3] = 70
+				response, _ = protocol6400.Encode(protocol6400.RspSnapshot, payload)
+			default:
+				t.Errorf("unexpected request type %02x", item.Frame.Type)
+				return
+			}
+			if _, err := master.Write(response); err != nil {
+				t.Errorf("response write: %v", err)
+				return
+			}
+			if item.Frame.Type == protocol6400.CmdGetSnapshot {
+				close(done)
+				return
+			}
+		}
+	}
+}
+
+func TestPTYTargetRetrySnapshotAndProductionStimulus(t *testing.T) {
+	master, slaveHold, slave, err := serialtransport.OpenPTY()
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer master.Close()
+	defer unix.Close(slaveHold)
+	done := make(chan struct{})
+	go serveThermalPTY(t, master, true, done)
+	client, err := Open(slave, "production", 80*time.Millisecond, 1)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer client.Close()
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	if err := client.SetTarget(ctx, 70); err != nil {
+		t.Fatal(err)
+	}
+	snapshot, payload, err := client.GetSnapshot(ctx)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(payload) != protocol6400.SnapshotPayloadLen || snapshot.ControlState != 4 || snapshot.CurrentTarget != 70 {
+		t.Fatalf("snapshot mismatch: len=%d state=%d target=%d", len(payload), snapshot.ControlState, snapshot.CurrentTarget)
+	}
+	if err := client.RunStimulus(ctx, protocol6400.Stimulus{DurationSeconds: 1}); err != protocol6400.ErrNotSupported {
+		t.Fatalf("production stimulus error: %v", err)
+	}
+	select {
+	case <-done:
+	case <-time.After(time.Second):
+		t.Fatal("PTY server did not complete")
+	}
+}

+ 15 - 0
profiles/6400-control/profile.json

@@ -0,0 +1,15 @@
+{
+  "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+  "one_outstanding_transaction": true,
+  "profile_id": "6400-control",
+  "schema": "hth-6400-profile-v1",
+  "serial": {
+    "baud": 921600,
+    "data_bits": 8,
+    "parity": "N",
+    "stop_bits": 1
+  },
+  "single_serial_owner": true,
+  "snapshot_payload_length": 193,
+  "stimulus_supported": false
+}

+ 15 - 0
profiles/6400-identification/profile.json

@@ -0,0 +1,15 @@
+{
+  "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+  "one_outstanding_transaction": true,
+  "profile_id": "6400-identification",
+  "schema": "hth-6400-profile-v1",
+  "serial": {
+    "baud": 921600,
+    "data_bits": 8,
+    "parity": "N",
+    "stop_bits": 1
+  },
+  "single_serial_owner": true,
+  "snapshot_payload_length": 193,
+  "stimulus_supported": true
+}

+ 2 - 1
sdk/python/hth_sdk/__init__.py

@@ -7,6 +7,7 @@ Default public surface is the synchronous facade. Platform details live in
 from __future__ import annotations
 
 from hth_sdk.simple import Control, HTH, HTHError, Result, State
+from hth_sdk.thermal import Snapshot as ThermalSnapshot, ThermalHTH
 
-__all__ = ["HTH", "State", "Control", "Result", "HTHError"]
+__all__ = ["HTH", "State", "Control", "Result", "HTHError", "ThermalHTH", "ThermalSnapshot"]
 __version__ = "0.3.0"

+ 1 - 0
sdk/python/hth_sdk/generated/thermal/__init__.py

@@ -0,0 +1 @@
+from .contract import *  # noqa: F401,F403

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 8 - 0
sdk/python/hth_sdk/generated/thermal/contract.py


+ 92 - 0
sdk/python/hth_sdk/thermal.py

@@ -0,0 +1,92 @@
+"""6400 target/ACK/snapshot facade. No serial ownership exists in this module."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import struct
+import time
+from typing import Protocol, Sequence
+
+from hth_sdk.generated.thermal.contract import SNAPSHOT_FIELDS, SNAPSHOT_PAYLOAD_LENGTH
+
+
+class ThermalBackend(Protocol):
+    def set_target(self, temperature_c: int) -> None: ...
+    def get_snapshot_payload(self) -> bytes: ...
+    def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None: ...
+
+
+def _field(payload: bytes, name: str):
+    field = SNAPSHOT_FIELDS[name]
+    offset = field["offset"]
+    count = field.get("count", 1)
+    kind = field["type"]
+    if kind == "u8":
+        values = list(payload[offset : offset + count])
+    elif kind == "u16":
+        values = list(struct.unpack_from("<" + "H" * count, payload, offset))
+    elif kind == "bytes":
+        values = list(payload[offset : offset + count])
+    else:
+        raise ValueError(f"unsupported snapshot field type {kind}")
+    return values[0] if count == 1 else values
+
+
+def _mask(values: Sequence[int], count: int) -> list[bool]:
+    return [bool(values[index // 8] & (1 << (index % 8))) for index in range(count)]
+
+
+def decode_snapshot(payload: bytes) -> dict[str, object]:
+    if len(payload) != SNAPSHOT_PAYLOAD_LENGTH:
+        raise ValueError(f"snapshot length {len(payload)} != {SNAPSHOT_PAYLOAD_LENGTH}")
+    decoded = {name: _field(payload, name) for name in SNAPSHOT_FIELDS}
+    decoded["bmc_valid"] = _mask(decoded.pop("bmc_valid_mask"), 24)
+    decoded["ct_valid"] = _mask(decoded.pop("ct_valid_mask"), 27)
+    decoded["safety_override"] = _mask(decoded.pop("safety_override_mask"), 24)
+    lane_mask = int(decoded.pop("lane_fault_mask"))
+    decoded["lane_fault"] = [bool(lane_mask & (1 << lane)) for lane in range(4)]
+    decoded["host_target_seen"] = bool(decoded["host_target_seen"])
+    decoded["global_fault"] = bool(decoded["global_fault"])
+    return decoded
+
+
+@dataclass(frozen=True)
+class Snapshot:
+    payload: bytes
+    decoded: dict[str, object]
+    request_monotonic_ns: int
+    response_monotonic_ns: int
+
+
+class ThermalHTH:
+    def __init__(self, backend: ThermalBackend, *, identification: bool = False):
+        self._backend = backend
+        self._identification = identification
+
+    def set_target(self, temperature_c: int) -> None:
+        if temperature_c != 0 and not 20 <= temperature_c <= 70:
+            raise ValueError("temperature must be 0 or 20..70 C")
+        self._backend.set_target(temperature_c)
+
+    def stop(self) -> None:
+        self.set_target(0)
+
+    def get_snapshot(self) -> Snapshot:
+        start = time.monotonic_ns()
+        payload = self._backend.get_snapshot_payload()
+        end = time.monotonic_ns()
+        return Snapshot(payload, decode_snapshot(payload), start, end)
+
+    def capture_snapshot(self) -> Snapshot:
+        return self.get_snapshot()
+
+    def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None:
+        if not self._identification:
+            raise NotImplementedError("stimulus is not supported by production firmware")
+        if not 1 <= duration_seconds <= 255:
+            raise ValueError("duration must be 1..255 seconds")
+        if len(ptc) != 24 or len(front) != 4 or len(rear) != 4:
+            raise ValueError("stimulus requires 24 PTC, 4 front, and 4 rear duties")
+        if any(value < 0 or value > 100 for value in [*ptc, *front, *rear]):
+            raise ValueError("stimulus duties must be 0..100")
+        self._backend.run_stimulus(duration_seconds, ptc, front, rear)

+ 46 - 0
sdk/python/tests/test_thermal.py

@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+import pytest
+
+from hth_sdk.thermal import ThermalHTH, decode_snapshot
+
+
+class Backend:
+    def __init__(self):
+        self.targets = []
+        self.stimuli = []
+
+    def set_target(self, temperature_c):
+        self.targets.append(temperature_c)
+
+    def get_snapshot_payload(self):
+        return bytes(193)
+
+    def run_stimulus(self, duration_seconds, ptc, front, rear):
+        self.stimuli.append((duration_seconds, list(ptc), list(front), list(rear)))
+
+
+def test_target_stop_and_snapshot() -> None:
+    backend = Backend()
+    hth = ThermalHTH(backend)
+    hth.set_target(70)
+    hth.stop()
+    assert backend.targets == [70, 0]
+    assert hth.get_snapshot().decoded["bmc_raw"] == [0] * 24
+
+
+def test_production_rejects_stimulus() -> None:
+    with pytest.raises(NotImplementedError):
+        ThermalHTH(Backend()).run_stimulus(1, [0] * 24, [0] * 4, [0] * 4)
+
+
+def test_identification_validates_and_runs_stimulus() -> None:
+    backend = Backend()
+    hth = ThermalHTH(backend, identification=True)
+    hth.run_stimulus(2, [1] * 24, [20] * 4, [30] * 4)
+    assert backend.stimuli[0][0] == 2
+
+
+def test_snapshot_length_is_exact() -> None:
+    with pytest.raises(ValueError):
+        decode_snapshot(bytes(192))

+ 115 - 0
tools/import_6400_contract.py

@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+"""Import generated CPLD contracts and derive Go/Python constants."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import sys
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parents[1]
+DEFAULT_SOURCE = ROOT.parent / "cpld-temperature-control/generated/6400/host-contract.json"
+
+
+def json_bytes(value: Any) -> bytes:
+    return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode()
+
+
+def camel(name: str) -> str:
+    return "".join(item.upper() if item in {"bmc", "ct", "ptc"} else item.title() for item in name.split("_"))
+
+
+def outputs(source: Path) -> dict[Path, bytes]:
+    raw = source.read_bytes()
+    contract = json.loads(raw)
+    contract_sha = contract["contract_sha256"]
+    wire = contract["wire"]
+    snapshot = contract["snapshot"]
+    golden = contract["golden_vectors"]["frames"]
+    go_lines = [
+        "// Code generated by tools/import_6400_contract.py; DO NOT EDIT.",
+        "package protocol6400",
+        "",
+        f'const ContractSHA256 = "{contract_sha}"',
+        f"const SnapshotPayloadLen = {snapshot['payload_length']}",
+        f"const CmdSetTarget byte = 0x{wire['commands']['SET_TARGET']['type']:02X}",
+        f"const CmdGetSnapshot byte = 0x{wire['commands']['GET_SNAPSHOT']['type']:02X}",
+        f"const CmdSetStimulus byte = 0x{wire['commands']['SET_STIMULUS']['type']:02X}",
+        f"const RspSetTargetAck byte = 0x{wire['responses']['SET_TARGET_ACK']['type']:02X}",
+        f"const RspSnapshot byte = 0x{wire['responses']['SNAPSHOT_DATA']['type']:02X}",
+        f"const RspStimulusAck byte = 0x{wire['responses']['SET_STIMULUS_ACK']['type']:02X}",
+        f"const HostBaud = {wire['host_uart']['baud']}",
+        "",
+    ]
+    for field in snapshot["fields"]:
+        go_lines.append(f"const Snapshot{camel(field['name'])}Offset = {field['offset']}")
+    go_lines.extend([
+        "",
+        f'const GoldenSetTargetStop = "{golden["set_target_stop"].lower()}"',
+        f'const GoldenSetTarget20 = "{golden["set_target_20"].lower()}"',
+        f'const GoldenSetTarget70 = "{golden["set_target_70"].lower()}"',
+        f'const GoldenGetSnapshot = "{golden["get_snapshot"].lower()}"',
+        f'const GoldenStimulusAllZeroOneSecond = "{golden["stimulus_all_zero_one_second"].lower()}"',
+        "",
+    ])
+    py_lines = [
+        '"""Generated 6400 wire and snapshot constants."""',
+        f'CONTRACT_SHA256 = "{contract_sha}"',
+        f"SNAPSHOT_PAYLOAD_LENGTH = {snapshot['payload_length']}",
+        f"HOST_BAUD = {wire['host_uart']['baud']}",
+        "COMMANDS = " + repr({name: value["type"] for name, value in wire["commands"].items()}),
+        "RESPONSES = " + repr({name: value["type"] for name, value in wire["responses"].items()}),
+        "SNAPSHOT_FIELDS = " + repr({field["name"]: field for field in snapshot["fields"]}),
+        "CHANNEL_MAP = " + repr(contract["channel_map"]["channels"]),
+        "",
+    ]
+    profile_common = {
+        "schema": "hth-6400-profile-v1",
+        "contract_sha256": contract_sha,
+        "serial": {"baud": wire["host_uart"]["baud"], "data_bits": 8, "parity": "N", "stop_bits": 1},
+        "snapshot_payload_length": snapshot["payload_length"],
+        "single_serial_owner": True,
+        "one_outstanding_transaction": True,
+    }
+    production = {**profile_common, "profile_id": "6400-control", "stimulus_supported": False}
+    identification = {**profile_common, "profile_id": "6400-identification", "stimulus_supported": True}
+    imported_sha = hashlib.sha256(raw).hexdigest()
+    return {
+        ROOT / "contracts/6400/host-contract.json": raw,
+        ROOT / "contracts/6400/SHA256SUMS": f"{imported_sha}  host-contract.json\n".encode(),
+        ROOT / "internal/protocol6400/generated_contract.go": ("\n".join(go_lines)).encode(),
+        ROOT / "sdk/python/hth_sdk/generated/thermal/contract.py": ("\n".join(py_lines)).encode(),
+        ROOT / "sdk/python/hth_sdk/generated/thermal/__init__.py": b"from .contract import *  # noqa: F401,F403\n",
+        ROOT / "profiles/6400-control/profile.json": json_bytes(production),
+        ROOT / "profiles/6400-identification/profile.json": json_bytes(identification),
+    }
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)
+    parser.add_argument("--check", action="store_true")
+    args = parser.parse_args()
+    expected = outputs(args.source)
+    drift = []
+    for path, content in expected.items():
+        if args.check:
+            if not path.exists() or path.read_bytes() != content:
+                drift.append(str(path.relative_to(ROOT)))
+        else:
+            path.parent.mkdir(parents=True, exist_ok=True)
+            if not path.exists() or path.read_bytes() != content:
+                path.write_bytes(content)
+    if drift:
+        print("generated drift: " + ", ".join(drift), file=sys.stderr)
+        return 1
+    print(f"PASS: {len(expected)} imported files")
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())