Explorar o código

feat: add project configuration and simple protocol model

Codex Resource Selftest hai 4 meses
pai
achega
11e3455cb1

+ 103 - 0
projects/prod2u-door-temp/project.json

@@ -0,0 +1,103 @@
+{
+  "project_id": "prod2u-door-temp",
+  "profile": "prod2u-normal-multiproject-115200-v1",
+  "display_name": "Prod2U door and temperature controller",
+  "device": {
+    "family": "EF2",
+    "part": "EF2L45BG256B",
+    "clock_hz": 25000000,
+    "clock_ball": "J1"
+  },
+  "uart": {
+    "baud": 115200,
+    "data_bits": 8,
+    "parity": "N",
+    "stop_bits": 1,
+    "flow_control": "none",
+    "clks_per_bit": 217,
+    "inter_byte_timeout_ms": 10
+  },
+  "outputs": {
+    "ptc_count": 24,
+    "fan_count": 4,
+    "pwm_bits": 8,
+    "ptc_polarity": "active_high",
+    "fan_polarity": "active_low",
+    "solenoid_policy": "constant_safe_zero",
+    "z_policy": "constant_zero"
+  },
+  "motors": {
+    "count": 2,
+    "fixed_steps": 450,
+    "execution": "serial",
+    "order": ["inlet", "outlet"],
+    "step_rate_hz": 1000,
+    "step_half_cycles": 12500,
+    "dir_setup_cycles": 25000,
+    "direction_values": [0, 1],
+    "direction_meaning": {"0": "open", "1": "close"},
+    "limits": "none",
+    "mapping": {
+      "inlet": {"axis": "x", "step_ball": "C11", "dir_ball": "B12"},
+      "outlet": {"axis": "y", "step_ball": "D15", "dir_ball": "H14"}
+    },
+    "enable_n": {"ball": "A10", "policy": "constant_low_enabled"}
+  },
+  "temperature": {
+    "value_count": 27,
+    "device_addresses": [73, 72, 75],
+    "registers": [0, 1, 2, 3, 4, 5, 6, 7, 8],
+    "scl_ball": "M8",
+    "sda_ball": "N9",
+    "invalid_value": 255,
+    "maximum_celsius": 150,
+    "conversion": {
+      "profile": "ct7428-msb-integer",
+      "raw_shift": 7,
+      "raw_width": 9,
+      "reject_sign_bit": true
+    }
+  },
+  "pins": {
+    "host_uart_rx": "N11",
+    "host_uart_tx": "M10",
+    "solenoid": "P5",
+    "z_step": "H12",
+    "z_dir": "F14",
+    "ls1": "B9",
+    "ls2": "A11",
+    "ptc_pwm": ["F16", "G16", "T4", "R5", "T6", "R7", "M1", "N1", "P1", "R1", "T2", "R3", "P16", "R16", "M16", "N16", "P8", "P7", "T9", "P9", "P10", "R10", "T13", "T12"],
+    "fan_pwm": ["C4", "B5", "B1", "A14"]
+  },
+  "resources": {
+    "target_ram_blocks": 1,
+    "request_ram_blocks": 1,
+    "temperature_ram_blocks": 1,
+    "dsp": 0,
+    "shared_pwm_comparators": 1,
+    "shared_motor_executors": 1,
+    "shared_i2c_readers": 1
+  },
+  "protocol": {
+    "header_hex": "A55A",
+    "crc": {
+      "name": "CRC-16/CCITT-FALSE",
+      "polynomial": 4129,
+      "initial": 65535,
+      "reflect_input": false,
+      "reflect_output": false,
+      "xor_output": 0,
+      "coverage": "type_length_payload",
+      "wire_order": "little"
+    },
+    "commands": {
+      "set_all": 1,
+      "get_temperature": 2,
+      "temperature_data": 130
+    }
+  },
+  "timeouts": {
+    "frame_inter_byte_ms": 10,
+    "host_get_response_ms": 5000
+  }
+}

+ 7 - 0
projects/prod2u-door-temp/requirements.zh-CN.md

@@ -0,0 +1,7 @@
+# Prod2U 门控与温度项目需求
+
+本项目使用 25 MHz 主时钟和 115200 8N1 UART。统一帧为 `A5 5A type length payload CRC16_LE`,CRC-16/CCITT-FALSE 覆盖类型、长度和 payload。
+
+正式帧只有 `0x01 SET_ALL`、`0x02 GET_TEMPERATURE` 和 `0x82 TEMPERATURE_DATA`。项目包含 24 路 PTC、4 路 FAN、两台无限位门控马达和 27 项 CT7428 温度读取。
+
+SET_ALL 每次更新 24 个 PTC、4 个 FAN 和两个方向字节,并按进风门、出风门顺序各执行 450 步;SET_ALL 不回复。GET_TEMPERATURE 完成 27 项顺序读取后只回复一个 33 字节温度帧。单项温度失败写 `FF` 并继续。

+ 73 - 0
schemas/project.schema.json

@@ -0,0 +1,73 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "type": "object",
+  "required": ["project_id", "profile", "device", "uart", "outputs", "motors", "temperature", "pins", "resources", "protocol", "timeouts"],
+  "properties": {
+    "project_id": {"type": "string", "pattern": "^[a-z0-9-]+$"},
+    "profile": {"type": "string", "const": "prod2u-normal-multiproject-115200-v1"},
+    "device": {
+      "type": "object",
+      "required": ["family", "part", "clock_hz", "clock_ball"],
+      "properties": {
+        "family": {"type": "string", "const": "EF2"},
+        "part": {"type": "string", "const": "EF2L45BG256B"},
+        "clock_hz": {"type": "integer", "const": 25000000},
+        "clock_ball": {"type": "string", "const": "J1"}
+      },
+      "additionalProperties": false
+    },
+    "uart": {
+      "type": "object",
+      "required": ["baud", "data_bits", "parity", "stop_bits", "flow_control", "clks_per_bit", "inter_byte_timeout_ms"],
+      "properties": {
+        "baud": {"type": "integer", "const": 115200},
+        "data_bits": {"type": "integer", "const": 8},
+        "parity": {"type": "string", "const": "N"},
+        "stop_bits": {"type": "integer", "const": 1},
+        "flow_control": {"type": "string", "const": "none"},
+        "clks_per_bit": {"type": "integer", "const": 217},
+        "inter_byte_timeout_ms": {"type": "integer", "const": 10}
+      },
+      "additionalProperties": false
+    },
+    "outputs": {
+      "type": "object",
+      "required": ["ptc_count", "fan_count", "pwm_bits", "ptc_polarity", "fan_polarity", "solenoid_policy", "z_policy"],
+      "properties": {
+        "ptc_count": {"type": "integer", "const": 24},
+        "fan_count": {"type": "integer", "const": 4},
+        "pwm_bits": {"type": "integer", "const": 8},
+        "ptc_polarity": {"type": "string", "enum": ["active_high", "active_low"]},
+        "fan_polarity": {"type": "string", "enum": ["active_high", "active_low"]},
+        "solenoid_policy": {"type": "string", "const": "constant_safe_zero"},
+        "z_policy": {"type": "string", "const": "constant_zero"}
+      },
+      "additionalProperties": false
+    },
+    "motors": {
+      "type": "object",
+      "required": ["count", "fixed_steps", "execution", "order", "step_rate_hz", "step_half_cycles", "dir_setup_cycles", "direction_values", "direction_meaning", "limits", "mapping", "enable_n"],
+      "properties": {
+        "count": {"type": "integer", "const": 2},
+        "fixed_steps": {"type": "integer", "const": 450},
+        "execution": {"type": "string", "const": "serial"},
+        "order": {"type": "array", "const": ["inlet", "outlet"]},
+        "step_rate_hz": {"type": "integer", "const": 1000},
+        "step_half_cycles": {"type": "integer", "const": 12500},
+        "dir_setup_cycles": {"type": "integer", "const": 25000},
+        "direction_values": {"type": "array", "const": [0, 1]},
+        "direction_meaning": {"type": "object"},
+        "limits": {"type": "string", "const": "none"},
+        "mapping": {"type": "object"},
+        "enable_n": {"type": "object"}
+      },
+      "additionalProperties": false
+    },
+    "temperature": {"type": "object"},
+    "pins": {"type": "object"},
+    "resources": {"type": "object"},
+    "protocol": {"type": "object"},
+    "timeouts": {"type": "object"}
+  },
+  "additionalProperties": false
+}

+ 50 - 0
tests/unit/test_project_config.py

@@ -0,0 +1,50 @@
+import json
+import unittest
+from pathlib import Path
+
+from tools.generate_project import load_project, project_summary
+
+
+ROOT = Path(__file__).resolve().parents[2]
+PROJECT = ROOT / "projects" / "prod2u-door-temp" / "project.json"
+
+
+class ProjectConfigTests(unittest.TestCase):
+    def test_project_config_freezes_counts_hardware_and_uart(self):
+        project = load_project(PROJECT)
+        self.assertEqual(project["project_id"], "prod2u-door-temp")
+        self.assertEqual(project["device"]["part"], "EF2L45BG256B")
+        self.assertEqual(project["device"]["clock_hz"], 25_000_000)
+        self.assertEqual(project["uart"]["baud"], 115200)
+        self.assertEqual(project["uart"]["clks_per_bit"], 217)
+        self.assertEqual(project["outputs"]["ptc_count"], 24)
+        self.assertEqual(project["outputs"]["fan_count"], 4)
+        self.assertEqual(project["motors"]["fixed_steps"], 450)
+        self.assertEqual(project["temperature"]["value_count"], 27)
+
+    def test_project_config_uses_only_new_protocol_types(self):
+        project = load_project(PROJECT)
+        self.assertEqual(project["protocol"]["commands"], {
+            "set_all": 0x01,
+            "get_temperature": 0x02,
+            "temperature_data": 0x82,
+        })
+        self.assertEqual(project["protocol"]["crc"]["polynomial"], 0x1021)
+
+    def test_summary_is_deterministic_and_contains_generated_lengths(self):
+        summary = project_summary(PROJECT)
+        self.assertEqual(summary["set_all_payload_len"], 30)
+        self.assertEqual(summary["set_all_frame_len"], 36)
+        self.assertEqual(summary["temperature_frame_len"], 33)
+        self.assertEqual(summary["uart_clks_per_bit"], 217)
+        self.assertEqual(summary, project_summary(PROJECT))
+
+    def test_schema_contains_frozen_contract_constants(self):
+        schema = json.loads((ROOT / "schemas" / "project.schema.json").read_text(encoding="utf-8"))
+        self.assertEqual(schema["properties"]["uart"]["properties"]["baud"]["const"], 115200)
+        self.assertEqual(schema["properties"]["outputs"]["properties"]["ptc_count"]["const"], 24)
+        self.assertEqual(schema["properties"]["motors"]["properties"]["fixed_steps"]["const"], 450)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 37 - 0
tests/unit/test_project_generation.py

@@ -0,0 +1,37 @@
+import hashlib
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+from tools.generate_project import generate_project
+
+
+ROOT = Path(__file__).resolve().parents[2]
+PROJECT = ROOT / "projects" / "prod2u-door-temp" / "project.json"
+
+
+class ProjectGenerationTests(unittest.TestCase):
+    def test_generation_is_deterministic_and_emits_compile_time_parameters(self):
+        with tempfile.TemporaryDirectory() as directory:
+            first = Path(directory) / "first"
+            second = Path(directory) / "second"
+            generate_project(PROJECT, first)
+            generate_project(PROJECT, second)
+            first_files = sorted(path.relative_to(first) for path in first.rglob("*" ) if path.is_file())
+            second_files = sorted(path.relative_to(second) for path in second.rglob("*" ) if path.is_file())
+            self.assertEqual(first_files, second_files)
+            for relative in first_files:
+                self.assertEqual(
+                    hashlib.sha256((first / relative).read_bytes()).digest(),
+                    hashlib.sha256((second / relative).read_bytes()).digest(),
+                )
+            params = (first / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
+            self.assertIn("P4_PTC_COUNT 24", params)
+            self.assertIn("P4_UART_CLKS_PER_BIT 217", params)
+            contract = json.loads((first / "generated" / "host-contract.json").read_text(encoding="utf-8"))
+            self.assertEqual(contract["commands"]["set_all"]["payload_length"], 30)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 50 - 0
tests/unit/test_protocol.py

@@ -0,0 +1,50 @@
+import unittest
+
+from tools.prod2u_simple_protocol import (
+    FrameType,
+    ProtocolError,
+    build_get_temperature,
+    build_set_all,
+    build_temperature_data,
+    decode_frame,
+    decode_temperature_data,
+    encode_frame,
+)
+
+
+class ProtocolTests(unittest.TestCase):
+    def test_get_temperature_matches_frozen_hex_vector(self):
+        self.assertEqual(build_get_temperature().hex(" ").upper(), "A5 5A 02 00 6D 7B")
+
+    def test_set_all_has_24_ptc_4_fan_and_two_direction_bytes(self):
+        raw = build_set_all(range(24), (10, 20, 30, 40), 0, 1)
+        frame = decode_frame(raw)
+        self.assertEqual(frame.frame_type, FrameType.SET_ALL)
+        self.assertEqual(len(frame.payload), 30)
+        self.assertEqual(frame.payload[:24], bytes(range(24)))
+        self.assertEqual(frame.payload[-2:], b"\x00\x01")
+
+    def test_temperature_response_is_exactly_33_bytes(self):
+        raw = build_temperature_data([0xFF] * 27)
+        self.assertEqual(len(raw), 33)
+        self.assertEqual(raw.hex(" ").upper(),
+                         "A5 5A 82 1B " + "FF " * 26 + "FF A7 45")
+        self.assertEqual(decode_temperature_data(decode_frame(raw)), (0xFF,) * 27)
+
+    def test_crc_and_length_errors_are_rejected(self):
+        raw = bytearray(encode_frame(FrameType.GET_TEMPERATURE, b""))
+        raw[-1] ^= 1
+        with self.assertRaises(ProtocolError):
+            decode_frame(bytes(raw))
+        with self.assertRaises(ProtocolError):
+            decode_frame(bytes(raw[:-1]))
+
+    def test_unknown_type_and_invalid_direction_are_rejected(self):
+        with self.assertRaises(ProtocolError):
+            decode_frame(encode_frame(0x7F, b""))
+        with self.assertRaises(ValueError):
+            build_set_all([0] * 24, [0] * 4, 2, 0)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 124 - 0
tools/generate_project.py

@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+"""Validate a project.json and emit deterministic compile-time artifacts."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+from pathlib import Path
+from typing import Any, Mapping
+
+
+PROFILE = "prod2u-normal-multiproject-115200-v1"
+
+
+def _require(condition: bool, message: str) -> None:
+    if not condition:
+        raise ValueError(message)
+
+
+def load_project(path: Path) -> dict[str, Any]:
+    project_path = Path(path)
+    payload = json.loads(project_path.read_text(encoding="utf-8"))
+    _require(isinstance(payload, dict), "project root must be an object")
+    _require(re.fullmatch(r"[a-z0-9-]+", str(payload.get("project_id", ""))) is not None, "invalid project_id")
+    _require(payload.get("profile") == PROFILE, "unsupported project profile")
+    device = payload.get("device")
+    uart = payload.get("uart")
+    outputs = payload.get("outputs")
+    motors = payload.get("motors")
+    temperature = payload.get("temperature")
+    protocol = payload.get("protocol")
+    for name, value in (("device", device), ("uart", uart), ("outputs", outputs), ("motors", motors), ("temperature", temperature), ("protocol", protocol)):
+        _require(isinstance(value, dict), f"{name} must be an object")
+    _require(device["part"] == "EF2L45BG256B" and device["clock_hz"] == 25_000_000, "device constants mismatch")
+    _require(uart == {**uart, "baud": 115200, "data_bits": 8, "parity": "N", "stop_bits": 1, "flow_control": "none", "clks_per_bit": 217}, "UART constants mismatch")
+    _require(outputs["ptc_count"] == 24 and outputs["fan_count"] == 4 and outputs["pwm_bits"] == 8, "output counts mismatch")
+    _require(motors["count"] == 2 and motors["fixed_steps"] == 450 and motors["execution"] == "serial", "motor constants mismatch")
+    _require(motors["order"] == ["inlet", "outlet"] and motors["direction_values"] == [0, 1], "motor order mismatch")
+    _require(temperature["value_count"] == 27 and temperature["device_addresses"] == [73, 72, 75], "temperature constants mismatch")
+    _require(temperature["registers"] == list(range(9)), "temperature register order mismatch")
+    _require(protocol["commands"] == {"set_all": 1, "get_temperature": 2, "temperature_data": 130}, "protocol type mismatch")
+    _require(protocol["crc"]["polynomial"] == 0x1021 and protocol["crc"]["initial"] == 0xFFFF, "CRC constants mismatch")
+    _require(len(payload["pins"]["ptc_pwm"]) == 24 and len(payload["pins"]["fan_pwm"]) == 4, "pin count mismatch")
+    return payload
+
+
+def project_summary(path: Path) -> dict[str, Any]:
+    project = load_project(path)
+    ptc_count = project["outputs"]["ptc_count"]
+    fan_count = project["outputs"]["fan_count"]
+    temperature_count = project["temperature"]["value_count"]
+    return {
+        "project_id": project["project_id"],
+        "profile": project["profile"],
+        "uart_clks_per_bit": project["uart"]["clks_per_bit"],
+        "set_all_payload_len": ptc_count + fan_count + 2,
+        "set_all_frame_len": ptc_count + fan_count + 8,
+        "temperature_payload_len": temperature_count,
+        "temperature_frame_len": temperature_count + 6,
+        "temperature_addresses": tuple(project["temperature"]["device_addresses"]),
+    }
+
+
+def _write_json(path: Path, payload: Mapping[str, Any]) -> None:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_text(json.dumps(dict(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
+
+
+def _render_params(project: Mapping[str, Any]) -> str:
+    outputs = project["outputs"]
+    motors = project["motors"]
+    temperature = project["temperature"]
+    uart = project["uart"]
+    return "\n".join([
+        "// Generated from project.json. Do not edit.",
+        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_FIXED_MOTOR_STEPS {motors['fixed_steps']}",
+        f"`define P4_MOTOR_STEP_HALF_CYCLES {motors['step_half_cycles']}",
+        f"`define P4_MOTOR_DIR_SETUP_CYCLES {motors['dir_setup_cycles']}",
+        f"`define P4_TEMPERATURE_COUNT {temperature['value_count']}",
+        "",
+    ])
+
+
+def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
+    project = load_project(project_path)
+    output = Path(output_root) / "generated"
+    output.mkdir(parents=True, exist_ok=True)
+    (output / f"{project['project_id'].replace('-', '_')}_params.vh").write_text(_render_params(project), encoding="ascii", newline="\n")
+    summary = project_summary(project_path)
+    contract = {
+        "schema": "prod2u-simple-host-contract-v1",
+        "project_id": project["project_id"],
+        "uart": project["uart"],
+        "commands": {
+            "set_all": {"type": "0x01", "payload_length": summary["set_all_payload_len"], "response": "none"},
+            "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"},
+            "temperature_data": {"type": "0x82", "payload_length": summary["temperature_payload_len"], "frame_length": summary["temperature_frame_len"]},
+        },
+        "crc": project["protocol"]["crc"],
+        "motors": project["motors"],
+        "temperature": project["temperature"],
+    }
+    _write_json(output / "host-contract.json", contract)
+    _write_json(output / "project-summary.json", summary)
+    return summary
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("project", type=Path)
+    parser.add_argument("output", type=Path)
+    args = parser.parse_args()
+    generate_project(args.project, args.output)
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 116 - 0
tools/prod2u_simple_protocol.py

@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+"""Reference model for the frozen 115200 Prod2U frame contract."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import IntEnum
+from typing import Iterable, Sequence
+
+
+FRAME_HEADER = b"\xA5\x5A"
+PTC_COUNT = 24
+FAN_COUNT = 4
+TEMPERATURE_COUNT = 27
+SET_ALL_PAYLOAD_LENGTH = PTC_COUNT + FAN_COUNT + 2
+
+
+class FrameType(IntEnum):
+    SET_ALL = 0x01
+    GET_TEMPERATURE = 0x02
+    TEMPERATURE_DATA = 0x82
+
+
+class ProtocolError(ValueError):
+    """Raised when a frame violates the frozen protocol contract."""
+
+
+@dataclass(frozen=True)
+class Frame:
+    frame_type: FrameType
+    payload: bytes
+
+
+def crc16_ccitt_false(data: bytes | bytearray | Iterable[int]) -> int:
+    crc = 0xFFFF
+    for value in data:
+        crc ^= (int(value) & 0xFF) << 8
+        for _ in range(8):
+            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
+    return crc
+
+
+def _coerce_type(value: int | FrameType) -> FrameType:
+    try:
+        return FrameType(int(value))
+    except (TypeError, ValueError) as exc:
+        raise ProtocolError(f"unsupported frame type: {value!r}") from exc
+
+
+def _expected_length(frame_type: FrameType) -> int:
+    return {
+        FrameType.SET_ALL: SET_ALL_PAYLOAD_LENGTH,
+        FrameType.GET_TEMPERATURE: 0,
+        FrameType.TEMPERATURE_DATA: TEMPERATURE_COUNT,
+    }[frame_type]
+
+
+def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray | Sequence[int]) -> bytes:
+    kind = _coerce_type(frame_type)
+    body = bytes(payload)
+    expected = _expected_length(kind)
+    if len(body) != expected:
+        raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
+    crc = crc16_ccitt_false(bytes((int(kind), len(body))) + body)
+    return FRAME_HEADER + bytes((int(kind), len(body))) + body + crc.to_bytes(2, "little")
+
+
+def decode_frame(raw: bytes | bytearray) -> Frame:
+    packet = bytes(raw)
+    if len(packet) < 6 or packet[:2] != FRAME_HEADER:
+        raise ProtocolError("invalid frame header or length")
+    try:
+        kind = FrameType(packet[2])
+    except ValueError as exc:
+        raise ProtocolError(f"unsupported frame type: 0x{packet[2]:02X}") from exc
+    payload_length = packet[3]
+    if len(packet) != payload_length + 6:
+        raise ProtocolError("frame length mismatch")
+    payload = packet[4 : 4 + payload_length]
+    expected = _expected_length(kind)
+    if payload_length != expected:
+        raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
+    actual_crc = int.from_bytes(packet[-2:], "little")
+    expected_crc = crc16_ccitt_false(packet[2:-2])
+    if actual_crc != expected_crc:
+        raise ProtocolError("CRC mismatch")
+    return Frame(kind, payload)
+
+
+def _checked_bytes(values: Iterable[int], count: int, name: str) -> bytes:
+    body = bytes(values)
+    if len(body) != count:
+        raise ValueError(f"{name} must contain {count} bytes")
+    return body
+
+
+def build_set_all(ptc: Iterable[int], fan: Iterable[int], inlet_dir: int, outlet_dir: int) -> bytes:
+    if inlet_dir not in (0, 1) or outlet_dir not in (0, 1):
+        raise ValueError("motor directions must be 0 or 1")
+    payload = _checked_bytes(ptc, PTC_COUNT, "ptc")
+    payload += _checked_bytes(fan, FAN_COUNT, "fan")
+    return encode_frame(FrameType.SET_ALL, payload + bytes((inlet_dir, outlet_dir)))
+
+
+def build_get_temperature() -> bytes:
+    return encode_frame(FrameType.GET_TEMPERATURE, b"")
+
+
+def build_temperature_data(values: Iterable[int]) -> bytes:
+    return encode_frame(FrameType.TEMPERATURE_DATA, _checked_bytes(values, TEMPERATURE_COUNT, "temperature"))
+
+
+def decode_temperature_data(frame: Frame) -> tuple[int, ...]:
+    if frame.frame_type is not FrameType.TEMPERATURE_DATA:
+        raise ProtocolError("frame is not TEMPERATURE_DATA")
+    return tuple(frame.payload)