Преглед изворни кода

feat(sdk): expose 6400 CLI capture and Python client

root пре 3 месеци
родитељ
комит
eea478245d

+ 20 - 11
Makefile

@@ -1,7 +1,7 @@
 MODULE := hth
 GO ?= go
 PYTHON ?= python3
-PROTOC ?= protoc
+PROTOC ?= $(PYTHON) -m grpc_tools.protoc
 GOPROXY ?= https://goproxy.cn,direct
 export GOPROXY
 export CGO_ENABLED ?= 0
@@ -11,18 +11,25 @@ HOST_ROOT := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
 REPO_ROOT := $(abspath $(HOST_ROOT)/..)
 PROTO := $(HOST_ROOT)/api/proto/hth/api/v1/hth.proto
 GEN_DIR := $(HOST_ROOT)/internal/gen/hth/api/v1
-PROFILE := $(HOST_ROOT)/profiles/prod2u-door-temp/profile.json
+LEGACY_PROFILE := $(HOST_ROOT)/profiles/prod2u-door-temp/profile.json
 BIN_DIR := $(HOST_ROOT)/bin
 API_VERSION := hth.api.v1
+PYTHON_SDK_VENV ?= $(if $(XDG_STATE_HOME),$(XDG_STATE_HOME),/tmp)/hth-python-sdk-venv
 
-.PHONY: all generate profile proto tidy build build-amd64 build-arm64 test test-race vet fuzz python-sdk check-config doctor-bin gofmt-check clean
+.PHONY: all generate contract6400 contract6400-check profile proto tidy build build-amd64 build-arm64 test test-race vet fuzz python-sdk check-config doctor-bin gofmt-check clean
 
 all: generate build test
 
-generate: profile proto
+generate: contract6400 profile proto
+
+contract6400:
+	$(PYTHON) $(HOST_ROOT)/tools/import_6400_contract.py
+
+contract6400-check:
+	$(PYTHON) $(HOST_ROOT)/tools/import_6400_contract.py --check
 
 profile:
-	$(PYTHON) $(HOST_ROOT)/tools/gen_profile.py --repo-root $(REPO_ROOT) --out $(PROFILE)
+	$(PYTHON) $(HOST_ROOT)/tools/gen_profile.py --repo-root $(HOST_ROOT) --out $(LEGACY_PROFILE)
 
 proto:
 	@mkdir -p $(GEN_DIR)
@@ -40,25 +47,25 @@ proto:
 tidy:
 	cd $(HOST_ROOT) && $(GO) mod tidy
 
-build: generate
+build: contract6400-check
 	mkdir -p $(BIN_DIR)
 	cd $(HOST_ROOT) && $(GO) build -trimpath -ldflags '-s -w -X hth/internal/app.APIVersion=$(API_VERSION)' -o $(BIN_DIR)/hthd ./cmd/hthd
 	cd $(HOST_ROOT) && $(GO) build -trimpath -ldflags '-s -w -X hth/internal/app.APIVersion=$(API_VERSION)' -o $(BIN_DIR)/hthctl ./cmd/hthctl
 	cd $(HOST_ROOT) && $(GO) build -trimpath -ldflags '-s -w -X hth/internal/app.APIVersion=$(API_VERSION)' -o $(BIN_DIR)/hth-capture ./cmd/hth-capture
 
-build-amd64: generate
+build-amd64: contract6400-check
 	mkdir -p $(BIN_DIR)
 	cd $(HOST_ROOT) && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthd-linux-amd64 ./cmd/hthd
 	cd $(HOST_ROOT) && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthctl-linux-amd64 ./cmd/hthctl
 	cd $(HOST_ROOT) && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hth-capture-linux-amd64 ./cmd/hth-capture
 
-build-arm64: generate
+build-arm64: contract6400-check
 	mkdir -p $(BIN_DIR)
 	cd $(HOST_ROOT) && GOOS=linux GOARCH=arm64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthd-linux-arm64 ./cmd/hthd
 	cd $(HOST_ROOT) && GOOS=linux GOARCH=arm64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthctl-linux-arm64 ./cmd/hthctl
 	cd $(HOST_ROOT) && GOOS=linux GOARCH=arm64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hth-capture-linux-arm64 ./cmd/hth-capture
 
-test: generate
+test: contract6400-check
 	cd $(HOST_ROOT) && $(GO) test ./...
 
 test-race:
@@ -74,8 +81,10 @@ fuzz:
 	cd $(HOST_ROOT) && $(GO) test ./internal/protocol -fuzz=FuzzParser -fuzztime=8s
 
 python-sdk:
-	$(PYTHON) -m pip install -e $(HOST_ROOT)/sdk/python -q
-	$(PYTHON) -m pytest -q $(HOST_ROOT)/sdk/python/tests
+	$(PYTHON) -m venv --system-site-packages $(PYTHON_SDK_VENV)
+	$(PYTHON_SDK_VENV)/bin/python -m pip install -q --no-index --no-deps --no-build-isolation -e $(HOST_ROOT)/sdk/python
+	$(PYTHON_SDK_VENV)/bin/python -m pip check
+	$(PYTHON_SDK_VENV)/bin/python -m pytest -q $(HOST_ROOT)/sdk/python/tests
 
 check-config: build
 	$(BIN_DIR)/hthd --check-config --config $(HOST_ROOT)/deploy/examples/hthd.mock.yaml

+ 128 - 0
cmd/hth-capture/main.go

@@ -1,18 +1,24 @@
 package main
 
 import (
+	"bufio"
 	"context"
 	"crypto/rand"
+	"encoding/binary"
 	"encoding/hex"
+	"encoding/json"
 	"flag"
 	"fmt"
 	"os"
 	"os/signal"
+	"path/filepath"
 	"syscall"
 	"time"
 
+	"google.golang.org/grpc"
 	"google.golang.org/grpc/codes"
 	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/encoding/protojson"
 	"hth/internal/app"
 	"hth/internal/capture"
 	hthv1 "hth/internal/gen/hth/api/v1"
@@ -33,6 +39,8 @@ func main() {
 	deviceID := fs.String("device", "prod2u-0", "device id")
 	out := fs.String("out", "", "output directory")
 	dur := fs.Duration("duration", 3*time.Second, "capture duration")
+	thermal := fs.Bool("thermal", false, "capture 6400 snapshots instead of Legacy event stream")
+	period := fs.Duration("period", 200*time.Millisecond, "6400 snapshot period")
 	_ = fs.Parse(os.Args[1:])
 	if *out == "" {
 		fmt.Fprintln(os.Stderr, "hth-capture: --out required")
@@ -51,6 +59,13 @@ func main() {
 	cli := hthv1.NewObserveServiceClient(conn)
 	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
 	defer stop()
+	if *thermal {
+		if err := runThermalCapture(ctx, conn, *deviceID, *out, *dur, *period); err != nil {
+			fmt.Fprintln(os.Stderr, err)
+			os.Exit(1)
+		}
+		return
+	}
 	capCtx, capCancel := context.WithTimeout(ctx, 5*time.Second)
 	caps, err := cli.GetCapabilities(capCtx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
 	capCancel()
@@ -196,3 +211,116 @@ func main() {
 	}
 	fmt.Printf("wrote %d records to %s status=%s\n", n, *out, man.Status)
 }
+
+func runThermalCapture(parent context.Context, conn *grpc.ClientConn, deviceID, out string, duration, period time.Duration) error {
+	if duration <= 0 || period <= 0 {
+		return fmt.Errorf("thermal capture duration and period must be positive")
+	}
+	client := hthv1.NewThermalObserveServiceClient(conn)
+	ctx, cancel := context.WithTimeout(parent, duration)
+	defer cancel()
+	rawPath := filepath.Join(out, "raw-frames.bin")
+	jsonlPath := filepath.Join(out, "thermal-snapshots.jsonl")
+	rawFile, err := os.Create(rawPath)
+	if err != nil {
+		return err
+	}
+	jsonFile, err := os.Create(jsonlPath)
+	if err != nil {
+		rawFile.Close()
+		return err
+	}
+	rawWriter := bufio.NewWriter(rawFile)
+	jsonWriter := bufio.NewWriter(jsonFile)
+	started := time.Now().UTC()
+	count := 0
+	contractHash := ""
+	profile := ""
+	ticker := time.NewTicker(period)
+	defer ticker.Stop()
+	for {
+		resp, err := client.CaptureSnapshot(ctx, &hthv1.GetThermalSnapshotRequest{DeviceId: deviceID})
+		if err != nil {
+			if ctx.Err() != nil && count > 0 {
+				break
+			}
+			return err
+		}
+		snapshot := resp.GetSnapshot()
+		if snapshot == nil || len(snapshot.GetRawPayload()) == 0 {
+			return fmt.Errorf("thermal snapshot has no raw payload")
+		}
+		contractHash = snapshot.GetContractSha256()
+		profile = snapshot.GetFirmwareProfile()
+		if err := binary.Write(rawWriter, binary.LittleEndian, uint32(len(snapshot.GetRawPayload()))); err != nil {
+			return err
+		}
+		if _, err := rawWriter.Write(snapshot.GetRawPayload()); err != nil {
+			return err
+		}
+		message, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(snapshot)
+		if err != nil {
+			return err
+		}
+		record, _ := json.Marshal(struct {
+			SampleIndex int             `json:"sample_index"`
+			Snapshot    json.RawMessage `json:"snapshot"`
+		}{SampleIndex: count, Snapshot: message})
+		if _, err := jsonWriter.Write(append(record, '\n')); err != nil {
+			return err
+		}
+		count++
+		select {
+		case <-ctx.Done():
+			if count > 0 {
+				break
+			}
+			return ctx.Err()
+		case <-ticker.C:
+			continue
+		}
+		break
+	}
+	if err := rawWriter.Flush(); err != nil {
+		return err
+	}
+	if err := jsonWriter.Flush(); err != nil {
+		return err
+	}
+	if err := rawFile.Close(); err != nil {
+		return err
+	}
+	if err := jsonFile.Close(); err != nil {
+		return err
+	}
+	rawSHA, err := capture.HashFile(rawPath)
+	if err != nil {
+		return err
+	}
+	jsonSHA, err := capture.HashFile(jsonlPath)
+	if err != nil {
+		return err
+	}
+	meta := map[string]any{
+		"schema": "hth-6400-capture-v1", "device_id": deviceID,
+		"firmware_profile": profile, "contract_sha256": contractHash,
+		"started_at": started, "ended_at": time.Now().UTC(), "record_count": count,
+		"hardware_validation": "NOT RUN", "com_validation": "NOT RUN",
+		"real_thermal_performance": "NOT RUN",
+	}
+	metaBytes, _ := json.MarshalIndent(meta, "", "  ")
+	runPath := filepath.Join(out, "run.json")
+	if err := os.WriteFile(runPath, append(metaBytes, '\n'), 0o644); err != nil {
+		return err
+	}
+	runSHA, err := capture.HashFile(runPath)
+	if err != nil {
+		return err
+	}
+	checksums := fmt.Sprintf("%s  raw-frames.bin\n%s  thermal-snapshots.jsonl\n%s  run.json\n", rawSHA, jsonSHA, runSHA)
+	if err := os.WriteFile(filepath.Join(out, "checksums.sha256"), []byte(checksums), 0o644); err != nil {
+		return err
+	}
+	fmt.Printf("wrote %d thermal snapshots to %s\n", count, out)
+	return nil
+}

+ 80 - 11
cmd/hthctl/main.go

@@ -2,8 +2,10 @@ package main
 
 import (
 	"context"
+	"encoding/json"
 	"flag"
 	"fmt"
+	"io"
 	"os"
 	"strings"
 	"time"
@@ -34,9 +36,10 @@ func main() {
 	ttl := fs.Duration("ttl", 10*time.Second, "lease ttl")
 	file := fs.String("file", "", "JSON ActionBatch for validate-action")
 	allowClamp := fs.Bool("allow-clamp", false, "allow clamp on validate/apply")
+	target := fs.Int("target", -1, "6400 target temperature: 0 or 20..70 C")
 	cmd := parseHthctlArgs(fs, os.Args[1:])
 	if cmd == "" {
-		fmt.Fprintln(os.Stderr, "usage: hthctl [flags] doctor|devices|capabilities|snapshot|watch|events|faults|health|validate-action|apply-action|enter-safe-mode|resume-from-safe|step-replay")
+		fmt.Fprintln(os.Stderr, "usage: hthctl [flags] doctor|devices|capabilities|snapshot|thermal-snapshot|capture-snapshot|set-target|stop|run-stimulus|watch|events|faults|health|validate-action|apply-action|enter-safe-mode|resume-from-safe|step-replay")
 		os.Exit(2)
 	}
 	if err := requireActionFile(cmd, *file); err != nil {
@@ -82,6 +85,44 @@ func main() {
 		resp, err := c.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
 		fatal(err)
 		printMsg(resp)
+	case "thermal-snapshot", "capture-snapshot":
+		conn := mustDial(*observe, rpcTimeout)
+		defer conn.Close()
+		client := hthv1.NewThermalObserveServiceClient(conn)
+		req := &hthv1.GetThermalSnapshotRequest{DeviceId: *deviceID}
+		var resp *hthv1.GetThermalSnapshotResponse
+		var err error
+		if cmd == "capture-snapshot" {
+			resp, err = client.CaptureSnapshot(ctx, req)
+		} else {
+			resp, err = client.GetSnapshot(ctx, req)
+		}
+		fatal(err)
+		printMsg(resp)
+	case "set-target":
+		if *target < 0 {
+			fatal(fmt.Errorf("set-target requires --target 0 or 20..70"))
+		}
+		conn := mustDial(*control, rpcTimeout)
+		defer conn.Close()
+		resp, err := hthv1.NewThermalControlServiceClient(conn).SetTarget(ctx, &hthv1.SetThermalTargetRequest{
+			DeviceId: *deviceID, TemperatureC: uint32(*target),
+		})
+		fatal(err)
+		printMsg(resp)
+	case "stop":
+		conn := mustDial(*control, rpcTimeout)
+		defer conn.Close()
+		resp, err := hthv1.NewThermalControlServiceClient(conn).Stop(ctx, &hthv1.StopThermalRequest{DeviceId: *deviceID})
+		fatal(err)
+		printMsg(resp)
+	case "run-stimulus":
+		stim := loadStimulus(*file, *deviceID)
+		conn := mustDial(*control, rpcTimeout)
+		defer conn.Close()
+		resp, err := hthv1.NewThermalControlServiceClient(conn).RunStimulus(ctx, stim)
+		fatal(err)
+		printMsg(resp)
 	case "watch":
 		c := observeClient(*observe, rpcTimeout)
 		st, err := c.SubscribeTelemetry(context.Background(), &hthv1.SubscribeTelemetryRequest{DeviceId: *deviceID})
@@ -225,7 +266,7 @@ func parseHthctlArgs(fs *flag.FlagSet, argv []string) string {
 
 func commandMutatesDevice(cmd string) bool {
 	switch cmd {
-	case "apply-action", "enter-safe-mode", "resume-from-safe", "step-replay":
+	case "apply-action", "enter-safe-mode", "resume-from-safe", "step-replay", "set-target", "stop", "run-stimulus":
 		return true
 	default:
 		return false
@@ -254,9 +295,9 @@ func timingDeadlineMS(observe, deviceID string) (uint32, error) {
 
 func requireActionFile(cmd, file string) error {
 	switch cmd {
-	case "validate-action", "apply-action", "resume-from-safe":
+	case "validate-action", "apply-action", "resume-from-safe", "run-stimulus":
 		if strings.TrimSpace(file) == "" {
-			return fmt.Errorf("%s requires --file with a complete ActionBatch JSON; refusing implicit fan1=10", cmd)
+			return fmt.Errorf("%s requires --file with complete JSON input; refusing implicit values", cmd)
 		}
 	}
 	return nil
@@ -315,14 +356,21 @@ func runDoctor(ctx context.Context, cfgPath, observe string) error {
 		if err != nil {
 			return err
 		}
-		p, err := profile.LoadStrict(cfg.Profile)
-		if err != nil {
-			return err
-		}
-		if err := cfg.Validate(p); err != nil {
-			return err
+		if cfg.IsThermal6400() {
+			if err := cfg.Validate(nil); err != nil {
+				return err
+			}
+			fmt.Print(app.DoctorText(cfg, nil))
+		} else {
+			p, err := profile.LoadStrict(cfg.Profile)
+			if err != nil {
+				return err
+			}
+			if err := cfg.Validate(p); err != nil {
+				return err
+			}
+			fmt.Print(app.DoctorText(cfg, p))
 		}
-		fmt.Print(app.DoctorText(cfg, p))
 	}
 	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
 	if err != nil {
@@ -397,6 +445,27 @@ func loadBatch(path, deviceID string, clamp bool) *hthv1.ActionBatch {
 	return b
 }
 
+func loadStimulus(path, deviceID string) *hthv1.RunThermalStimulusRequest {
+	raw, err := os.ReadFile(path)
+	fatal(err)
+	var input struct {
+		DurationSeconds uint32   `json:"duration_seconds"`
+		PTCDuty         []uint32 `json:"ptc_duty"`
+		FrontFanDuty    []uint32 `json:"front_fan_duty"`
+		RearFanDuty     []uint32 `json:"rear_fan_duty"`
+	}
+	dec := json.NewDecoder(strings.NewReader(string(raw)))
+	dec.DisallowUnknownFields()
+	fatal(dec.Decode(&input))
+	if err := dec.Decode(&struct{}{}); err != io.EOF {
+		fatal(fmt.Errorf("stimulus JSON has trailing data"))
+	}
+	return &hthv1.RunThermalStimulusRequest{
+		DeviceId: deviceID, DurationSeconds: input.DurationSeconds,
+		PtcDuty: input.PTCDuty, FrontFanDuty: input.FrontFanDuty, RearFanDuty: input.RearFanDuty,
+	}
+}
+
 func fatal(err error) {
 	if err != nil {
 		fmt.Fprintln(os.Stderr, err)

+ 68 - 0
docs/6400/migration.md

@@ -5,3 +5,71 @@ This repository was created with `git subtree split --prefix=host` from the Host
 The existing door-percent API remains migration/Legacy code. The 6400 path imports the generated target/ACK/snapshot contract and exposes `set_target`, `stop`, `get_snapshot`, `capture_snapshot`, and Identification-only `run_stimulus` through the existing gRPC-over-UDS service boundary.
 
 Only `hthd` opens a serial path. Lab and notebooks must use the Python SDK. Hardware, COM, and real UART validation are NOT RUN.
+
+## Runtime boundary
+
+Use one of the strict example configurations:
+
+- `deploy/examples/hthd.6400-mock.yaml`
+- `deploy/examples/hthd.6400-replay.yaml`
+- `deploy/examples/hthd.6400-serial.yaml`
+
+`product: 6400-front-rear-v1` selects the autonomous thermal path without enabling the Legacy poller, lease, SET_ALL heartbeat, or Host watchdog. `thermal.firmware_profile` is `production`/`6400-control` or `identification`/`6400-identification`. Production firmware and the production mock reject stimulus.
+
+The daemon holds one global transaction lock. SET_TARGET waits for wire ACK `0x81`, GET_SNAPSHOT waits for response `0x82`, and Identification stimulus waits for ACK `0x83`. A successful command result means the CPLD committed the command; it never means that the requested temperature was reached.
+
+The observe and control services remain on different UDS endpoints:
+
+```text
+observe socket: ThermalObserveService.GetSnapshot / CaptureSnapshot
+control socket: ThermalControlService.SetTarget / Stop / RunStimulus
+```
+
+The snapshot response preserves the exact generated 193-byte wire payload in `raw_payload` and also exposes decoded fields. Offsets and command values come from `contracts/6400`; do not duplicate them in clients.
+
+## CLI examples with the mock backend
+
+Start `hthd` with the mock example, then run:
+
+```bash
+hthctl --observe-sock /tmp/hth-6400-mock/observe.sock --device prod2u-6400-0 thermal-snapshot
+hthctl --observe-sock /tmp/hth-6400-mock/observe.sock --control-sock /tmp/hth-6400-mock/control.sock --device prod2u-6400-0 --target 65 set-target
+hthctl --observe-sock /tmp/hth-6400-mock/observe.sock --control-sock /tmp/hth-6400-mock/control.sock --device prod2u-6400-0 stop
+hth-capture --thermal --observe-sock /tmp/hth-6400-mock/observe.sock --device prod2u-6400-0 --out /tmp/hth-6400-capture --duration 10s --period 200ms
+```
+
+Thermal capture writes length-prefixed `raw-frames.bin`, `thermal-snapshots.jsonl`, `run.json`, and `checksums.sha256` without opening serial itself.
+
+`run-stimulus` requires an explicit JSON file containing `duration_seconds`, exactly 24 `ptc_duty` values, four `front_fan_duty` values, and four `rear_fan_duty` values. It is valid only with Identification firmware. The CLI still requires `--i-understand-this-is-real-hardware` for any mutating command when `ListDevices` reports a serial backend; this flag does not authorize this repository's tests to touch hardware.
+
+## Python SDK
+
+The Legacy five-symbol top-level facade remains unchanged. Import the 6400 client explicitly:
+
+```python
+from hth_sdk.thermal import connect_thermal
+
+with connect_thermal(
+    device_id="prod2u-6400-0",
+    observe_socket="/tmp/hth-6400-mock/observe.sock",
+    control_socket="/tmp/hth-6400-mock/control.sock",
+) as hth:
+    hth.set_target(65)
+    snapshot = hth.capture_snapshot()
+    assert len(snapshot.payload) == 193
+    hth.stop()
+```
+
+The SDK uses synchronous gRPC over UDS and contains no serial open path.
+
+## Replay format
+
+Replay is strict JSONL. Each nonblank line contains exactly one JSON object and exactly one of:
+
+```json
+{"payload_hex":"<exact 193-byte snapshot encoded as hex>"}
+{"error":"crc"}
+{"error":"timeout"}
+```
+
+Unknown fields, trailing JSON values, unknown error names, malformed hex, and wrong payload lengths are rejected when the backend opens. Replay is observe-only; target, stop, and stimulus return failed-precondition through gRPC.

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

@@ -7,7 +7,6 @@ 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", "ThermalHTH", "ThermalSnapshot"]
+__all__ = ["HTH", "State", "Control", "Result", "HTHError"]
 __version__ = "0.3.0"

+ 115 - 1
sdk/python/hth_sdk/thermal.py

@@ -7,6 +7,7 @@ import struct
 import time
 from typing import Protocol, Sequence
 
+from hth_sdk.constants import DEFAULT_CONTROL_SOCKET, DEFAULT_OBSERVE_SOCKET
 from hth_sdk.generated.thermal.contract import SNAPSHOT_FIELDS, SNAPSHOT_PAYLOAD_LENGTH
 
 
@@ -16,6 +17,84 @@ class ThermalBackend(Protocol):
     def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None: ...
 
 
+def _unix_target(path: str) -> str:
+    if path.startswith("unix:"):
+        return path
+    if not path.startswith("/"):
+        raise ValueError(f"Unix socket path must be absolute, got {path!r}")
+    return f"unix://{path}"
+
+
+class GrpcThermalBackend:
+    """Synchronous gRPC/UDS backend. It never opens a serial device."""
+
+    def __init__(
+        self,
+        *,
+        device_id: str,
+        observe_socket: str,
+        control_socket: str,
+        timeout: float,
+    ) -> None:
+        try:
+            import grpc
+            from hth_sdk.generated.hth.api.v1 import hth_pb2, hth_pb2_grpc
+        except ImportError as exc:
+            raise RuntimeError("install hth-sdk[live] for gRPC thermal access") from exc
+        self._grpc = grpc
+        self._pb2 = hth_pb2
+        self._device_id = device_id
+        self._timeout = timeout
+        self._observe_channel = grpc.insecure_channel(_unix_target(observe_socket))
+        self._control_channel = grpc.insecure_channel(_unix_target(control_socket))
+        self._observe = hth_pb2_grpc.ThermalObserveServiceStub(self._observe_channel)
+        self._control = hth_pb2_grpc.ThermalControlServiceStub(self._control_channel)
+
+    def close(self) -> None:
+        self._observe_channel.close()
+        self._control_channel.close()
+
+    def set_target(self, temperature_c: int) -> None:
+        self._control.SetTarget(
+            self._pb2.SetThermalTargetRequest(
+                device_id=self._device_id, temperature_c=temperature_c
+            ),
+            timeout=self._timeout,
+        )
+
+    def get_snapshot_payload(self) -> bytes:
+        response = self._observe.GetSnapshot(
+            self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
+            timeout=self._timeout,
+        )
+        return bytes(response.snapshot.raw_payload)
+
+    def capture_snapshot_payload(self) -> bytes:
+        response = self._observe.CaptureSnapshot(
+            self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
+            timeout=self._timeout,
+        )
+        return bytes(response.snapshot.raw_payload)
+
+    def run_stimulus(
+        self,
+        duration_seconds: int,
+        ptc: Sequence[int],
+        front: Sequence[int],
+        rear: Sequence[int],
+    ) -> None:
+        self._control.RunStimulus(
+            self._pb2.RunThermalStimulusRequest(
+                device_id=self._device_id,
+                duration_seconds=duration_seconds,
+                ptc_duty=ptc,
+                front_fan_duty=front,
+                rear_fan_duty=rear,
+            ),
+            timeout=self._timeout,
+        )
+
+
 def _field(payload: bytes, name: str):
     field = SNAPSHOT_FIELDS[name]
     offset = field["offset"]
@@ -71,6 +150,17 @@ class ThermalHTH:
     def stop(self) -> None:
         self.set_target(0)
 
+    def close(self) -> None:
+        close = getattr(self._backend, "close", None)
+        if close is not None:
+            close()
+
+    def __enter__(self) -> "ThermalHTH":
+        return self
+
+    def __exit__(self, *_exc: object) -> None:
+        self.close()
+
     def get_snapshot(self) -> Snapshot:
         start = time.monotonic_ns()
         payload = self._backend.get_snapshot_payload()
@@ -78,7 +168,11 @@ class ThermalHTH:
         return Snapshot(payload, decode_snapshot(payload), start, end)
 
     def capture_snapshot(self) -> Snapshot:
-        return self.get_snapshot()
+        start = time.monotonic_ns()
+        capture = getattr(self._backend, "capture_snapshot_payload", None)
+        payload = capture() if capture is not None else self._backend.get_snapshot_payload()
+        end = time.monotonic_ns()
+        return Snapshot(payload, decode_snapshot(payload), start, end)
 
     def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None:
         if not self._identification:
@@ -90,3 +184,23 @@ class ThermalHTH:
         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)
+
+
+def connect_thermal(
+    *,
+    device_id: str = "prod2u-6400-0",
+    observe_socket: str = DEFAULT_OBSERVE_SOCKET,
+    control_socket: str = DEFAULT_CONTROL_SOCKET,
+    firmware_profile: str = "production",
+    timeout: float = 3.0,
+) -> ThermalHTH:
+    backend = GrpcThermalBackend(
+        device_id=device_id,
+        observe_socket=observe_socket,
+        control_socket=control_socket,
+        timeout=timeout,
+    )
+    return ThermalHTH(
+        backend,
+        identification=firmware_profile in {"identification", "6400-identification"},
+    )

+ 6 - 6
sdk/python/pyproject.toml

@@ -22,17 +22,17 @@ classifiers = [
 
 [project.optional-dependencies]
 live = [
-  "grpcio>=1.83.0,<2",
-  "protobuf>=7.35.1,<8",
+  "grpcio>=1.71.0,<2",
+  "protobuf>=5.29.6,<6",
 ]
 dev = [
-  "grpcio-tools>=1.83.0,<2",
-  "grpcio>=1.83.0,<2",
-  "protobuf>=7.35.1,<8",
+  "grpcio-tools>=1.71.0,<2",
+  "grpcio>=1.71.0,<2",
+  "protobuf>=5.29.6,<6",
   "pytest>=8",
 ]
 gen = [
-  "grpcio-tools>=1.83.0,<2",
+  "grpcio-tools>=1.71.0,<2",
 ]
 
 [project.urls]

+ 176 - 0
tests/thermal_6400_uds_test.go

@@ -0,0 +1,176 @@
+//go:build linux
+
+package tests
+
+import (
+	"context"
+	"encoding/binary"
+	"encoding/json"
+	"fmt"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/grpcserver"
+	"hth/internal/protocol6400"
+	"hth/internal/testutil"
+)
+
+func thermalConfig(t *testing.T, profile string) (string, string, string) {
+	t.Helper()
+	root := filepath.Join(t.TempDir(), "runtime")
+	observe := filepath.Join(root, "observe.sock")
+	control := filepath.Join(root, "control.sock")
+	path := filepath.Join(t.TempDir(), "hthd.yaml")
+	raw := fmt.Sprintf(`api_version: hth.api.v1
+product: 6400-front-rear-v1
+device_id: prod2u-6400-0
+display_name: 6400 test
+backend: mock
+runtime_root: %s
+sockets:
+  observe: %s
+  control: %s
+  observe_perm: "0660"
+  control_perm: "0660"
+thermal:
+  firmware_profile: %s
+  transaction_timeout_ms: 100
+  retries: 1
+  mock_scenario: normal
+grpc:
+  reflection: false
+`, root, observe, control, profile)
+	if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	return path, observe, control
+}
+
+func startThermalMock(t *testing.T, profile string) (string, string) {
+	t.Helper()
+	config, observe, control := thermalConfig(t, profile)
+	startAppFromConfig(t, config)
+	waitUnix(t, observe, 2*time.Second)
+	waitUnix(t, control, 2*time.Second)
+	return observe, control
+}
+
+func TestThermal6400UDSProductionAPI(t *testing.T) {
+	observe, control := startThermalMock(t, "production")
+	obsConn, err := grpcserver.DialUnix(observe, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer obsConn.Close()
+	ctlConn, err := grpcserver.DialUnix(control, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer ctlConn.Close()
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	ctl := hthv1.NewThermalControlServiceClient(ctlConn)
+	obs := hthv1.NewThermalObserveServiceClient(obsConn)
+	set, err := ctl.SetTarget(ctx, &hthv1.SetThermalTargetRequest{DeviceId: "prod2u-6400-0", TemperatureC: 65})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !set.GetCommitted() || set.GetContractSha256() != protocol6400.ContractSHA256 {
+		t.Fatalf("set result %+v", set)
+	}
+	snapshot, err := obs.CaptureSnapshot(ctx, &hthv1.GetThermalSnapshotRequest{DeviceId: "prod2u-6400-0"})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if snapshot.GetSnapshot().GetCurrentTarget() != 65 || len(snapshot.GetSnapshot().GetRawPayload()) != protocol6400.SnapshotPayloadLen {
+		t.Fatalf("snapshot %+v", snapshot.GetSnapshot())
+	}
+	_, err = ctl.RunStimulus(ctx, &hthv1.RunThermalStimulusRequest{
+		DeviceId: "prod2u-6400-0", DurationSeconds: 1,
+		PtcDuty: make([]uint32, 24), FrontFanDuty: make([]uint32, 4), RearFanDuty: make([]uint32, 4),
+	})
+	if status.Code(err) != codes.Unimplemented {
+		t.Fatalf("production stimulus code=%s err=%v", status.Code(err), err)
+	}
+	if _, err := ctl.Stop(ctx, &hthv1.StopThermalRequest{DeviceId: "prod2u-6400-0"}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestThermal6400CLIAndCapture(t *testing.T) {
+	observe, control := startThermalMock(t, "production")
+	hthctl := buildHostCmd(t, "hthctl", "./cmd/hthctl")
+	for _, args := range [][]string{
+		{"--observe-sock", observe, "--control-sock", control, "--device", "prod2u-6400-0", "--timeout", "2s", "--target", "65", "set-target"},
+		{"--observe-sock", observe, "--device", "prod2u-6400-0", "--timeout", "2s", "thermal-snapshot"},
+		{"--observe-sock", observe, "--control-sock", control, "--device", "prod2u-6400-0", "--timeout", "2s", "stop"},
+	} {
+		cmd := exec.Command(hthctl, args...)
+		if out, err := cmd.CombinedOutput(); err != nil {
+			t.Fatalf("hthctl %v: %v\n%s", args, err, out)
+		}
+	}
+	captureBin := buildHostCmd(t, "hth-capture", "./cmd/hth-capture")
+	outDir := filepath.Join(t.TempDir(), "capture")
+	cmd := exec.Command(captureBin, "--thermal", "--observe-sock", observe, "--device", "prod2u-6400-0", "--out", outDir, "--duration", "1s", "--period", "100ms")
+	if out, err := cmd.CombinedOutput(); err != nil {
+		t.Fatalf("hth-capture: %v\n%s", err, out)
+	}
+	raw, err := os.ReadFile(filepath.Join(outDir, "raw-frames.bin"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(raw) < 4+protocol6400.SnapshotPayloadLen || binary.LittleEndian.Uint32(raw[:4]) != protocol6400.SnapshotPayloadLen {
+		t.Fatalf("raw capture len=%d prefix=%d", len(raw), binary.LittleEndian.Uint32(raw[:4]))
+	}
+	for _, name := range []string{"thermal-snapshots.jsonl", "run.json", "checksums.sha256"} {
+		if _, err := os.Stat(filepath.Join(outDir, name)); err != nil {
+			t.Fatalf("missing %s: %v", name, err)
+		}
+	}
+	runRaw, err := os.ReadFile(filepath.Join(outDir, "run.json"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	var runMeta map[string]any
+	if err := json.Unmarshal(runRaw, &runMeta); err != nil {
+		t.Fatal(err)
+	}
+	if runMeta["hardware_validation"] != "NOT RUN" || runMeta["com_validation"] != "NOT RUN" || runMeta["real_thermal_performance"] != "NOT RUN" {
+		t.Fatalf("capture truth labels %+v", runMeta)
+	}
+	checksums, err := os.ReadFile(filepath.Join(outDir, "checksums.sha256"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !strings.Contains(string(checksums), "  run.json\n") {
+		t.Fatalf("run.json checksum missing: %s", checksums)
+	}
+}
+
+func TestThermal6400PythonSDKLiveUDS(t *testing.T) {
+	observe, control := startThermalMock(t, "identification")
+	code := strings.Join([]string{
+		"from hth_sdk.thermal import connect_thermal",
+		fmt.Sprintf("with connect_thermal(device_id='prod2u-6400-0', observe_socket=%q, control_socket=%q, firmware_profile='identification', timeout=2.0) as h:", observe, control),
+		"    h.set_target(60)",
+		"    s = h.get_snapshot()",
+		"    assert s.decoded['current_target'] == 60",
+		"    h.run_stimulus(1, [20] * 24, [30] * 4, [40] * 4)",
+		"    s = h.capture_snapshot()",
+		"    assert s.decoded['ptc_applied'][0] == 20",
+		"    h.stop()",
+	}, "\n")
+	cmd := exec.Command("python3", "-c", code)
+	cmd.Env = append(os.Environ(), "PYTHONPATH="+filepath.Join(testutil.HostRoot(t), "sdk", "python"))
+	if out, err := cmd.CombinedOutput(); err != nil {
+		t.Fatalf("Python thermal SDK: %v\n%s", err, out)
+	}
+}

+ 2 - 0
tools/sdk_wheel_matrix.sh

@@ -119,9 +119,11 @@ from datetime import timedelta
 import hth_sdk
 from hth_sdk.generated.hth.api.v1 import hth_pb2, hth_pb2_grpc
 from hth_sdk.client import connect
+from hth_sdk.thermal import ThermalHTH, connect_thermal
 from hth_sdk.types import ActionBatch
 from hth_sdk.profiles import prod2u
 assert hth_pb2 is not None and hth_pb2_grpc is not None
+assert ThermalHTH is not None and connect_thermal is not None
 async def main():
     async with await connect(observe=os.environ["HTH_OBSERVE_SOCK"], control=os.environ["HTH_CONTROL_SOCK"], role="control") as client:
         caps = await client.get_capabilities("prod2u-0")