Просмотр исходного кода

replace active HTH surface with 6400 manual transports

高宇轩 3 месяцев назад
Родитель
Сommit
a3d8a31039
100 измененных файлов с 982 добавлено и 599 удалено
  1. 5 126
      README.zh-CN.md
  2. 109 0
      cmd/6400-uart/main.go
  3. 30 457
      cmd/hthctl/main.go
  4. 1 16
      go.mod
  5. 1 0
      golden-vectors.json
  6. 1 0
      host-i2c-register-map.json
  7. 81 0
      internal/i2creg/i2creg.go
  8. 46 0
      internal/i2creg/i2creg_test.go
  9. 115 0
      internal/protocol/protocol.go
  10. 81 0
      internal/transport/transport.go
  11. 20 0
      internal/transport/transport_test.go
  12. 0 0
      legacy-hth/Makefile
  13. 0 0
      legacy-hth/RELEASE.zh-CN.md
  14. 0 0
      legacy-hth/REQUIREMENTS_TRACEABILITY.md
  15. 0 0
      legacy-hth/api/proto/google/protobuf/README.md
  16. 0 0
      legacy-hth/api/proto/google/protobuf/duration.proto
  17. 0 0
      legacy-hth/api/proto/google/protobuf/timestamp.proto
  18. 0 0
      legacy-hth/api/proto/hth.api.v1.desc.prev
  19. 0 0
      legacy-hth/api/proto/hth/api/v1/hth.desc
  20. 0 0
      legacy-hth/api/proto/hth/api/v1/hth.proto
  21. 0 0
      legacy-hth/buf.yaml
  22. 0 0
      legacy-hth/cmd/hth-capture/main.go
  23. 474 0
      legacy-hth/cmd/hthctl/main.go
  24. 0 0
      legacy-hth/cmd/hthctl/main_test.go
  25. 0 0
      legacy-hth/cmd/hthd/main.go
  26. 0 0
      legacy-hth/contracts/6400/SHA256SUMS
  27. 0 0
      legacy-hth/contracts/6400/host-contract.json
  28. 0 0
      legacy-hth/contracts/evidence/RTL_REF.txt
  29. 0 0
      legacy-hth/contracts/evidence/SHA256SUMS
  30. 0 0
      legacy-hth/contracts/evidence/golden-vectors.json
  31. 0 0
      legacy-hth/contracts/evidence/host-contract.json
  32. 0 0
      legacy-hth/deploy/amd64-release/README.md
  33. 0 0
      legacy-hth/deploy/amd64-release/README.zh-CN.md
  34. 0 0
      legacy-hth/deploy/amd64-release/config/hthd.6400-mock.yaml
  35. 0 0
      legacy-hth/deploy/amd64-release/config/hthd.6400-serial.yaml
  36. 0 0
      legacy-hth/deploy/amd64-release/install.sh
  37. 0 0
      legacy-hth/deploy/amd64-release/selftest.sh
  38. 0 0
      legacy-hth/deploy/amd64-release/uninstall.sh
  39. 0 0
      legacy-hth/deploy/amd64-release/verify-install.sh
  40. 0 0
      legacy-hth/deploy/examples/hthd.6400-mock.yaml
  41. 0 0
      legacy-hth/deploy/examples/hthd.6400-replay.yaml
  42. 0 0
      legacy-hth/deploy/examples/hthd.6400-serial.yaml
  43. 0 0
      legacy-hth/deploy/examples/hthd.mock.yaml
  44. 0 0
      legacy-hth/deploy/examples/hthd.serial.yaml
  45. 0 0
      legacy-hth/deploy/examples/podman-socket-only.sh
  46. 0 0
      legacy-hth/deploy/install.sh
  47. 0 0
      legacy-hth/deploy/systemd/hth.conf
  48. 0 0
      legacy-hth/deploy/systemd/hthd.service
  49. 0 0
      legacy-hth/deploy/systemd/hthd@.service
  50. 0 0
      legacy-hth/deploy/sysusers.d/hth.conf
  51. 0 0
      legacy-hth/deploy/tmpfiles/hth.conf
  52. 0 0
      legacy-hth/deploy/udev/99-hth-controller.rules.template
  53. 0 0
      legacy-hth/deploy/uninstall.sh
  54. 0 0
      legacy-hth/docs/6400/migration.md
  55. 0 0
      legacy-hth/docs/TEST_MATRIX.zh-CN.md
  56. 0 0
      legacy-hth/docs/advanced/README.md
  57. 0 0
      legacy-hth/docs/amd64-release.zh-CN.md
  58. 0 0
      legacy-hth/docs/api-contract.zh-CN.md
  59. 0 0
      legacy-hth/docs/architecture.zh-CN.md
  60. 0 0
      legacy-hth/docs/compatibility-policy.zh-CN.md
  61. 0 0
      legacy-hth/docs/deployment.zh-CN.md
  62. 0 0
      legacy-hth/docs/failure-semantics.zh-CN.md
  63. 0 0
      legacy-hth/docs/known-gaps.zh-CN.md
  64. 0 0
      legacy-hth/docs/model-data-integration.zh-CN.md
  65. 0 0
      legacy-hth/docs/operations.zh-CN.md
  66. 0 0
      legacy-hth/docs/protocol-source-audit.zh-CN.md
  67. 0 0
      legacy-hth/docs/python-sdk-guide.zh-CN.md
  68. 0 0
      legacy-hth/docs/safety-contract.zh-CN.md
  69. 0 0
      legacy-hth/docs/signal-dictionary.zh-CN.md
  70. 0 0
      legacy-hth/docs/simple/ALGORITHM_API.md
  71. 0 0
      legacy-hth/docs/simple/README_10_MINUTES.md
  72. 0 0
      legacy-hth/generated/6400/golden-vectors.json
  73. 0 0
      legacy-hth/generated/6400/host-contract.json
  74. 0 0
      legacy-hth/generated/6400/import-source.json
  75. 18 0
      legacy-hth/go.mod
  76. 0 0
      legacy-hth/go.sum
  77. 0 0
      legacy-hth/internal/app/app.go
  78. 0 0
      legacy-hth/internal/app/backend_linux.go
  79. 0 0
      legacy-hth/internal/backend/backend.go
  80. 0 0
      legacy-hth/internal/backend/backend_test.go
  81. 0 0
      legacy-hth/internal/backend/classify.go
  82. 0 0
      legacy-hth/internal/backend/mock.go
  83. 0 0
      legacy-hth/internal/backend/replay.go
  84. 0 0
      legacy-hth/internal/backend/replay_fuzz_test.go
  85. 0 0
      legacy-hth/internal/backend/replay_strict_test.go
  86. 0 0
      legacy-hth/internal/backend/serial_close_linux_test.go
  87. 0 0
      legacy-hth/internal/backend/serial_get_linux_test.go
  88. 0 0
      legacy-hth/internal/backend/serial_linux.go
  89. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0255ca613fd7c6a1
  90. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0938b7fa705ec552
  91. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0cbd8c395f234c73
  92. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0ce8924336b00a4a
  93. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/10668f0c64d180ee
  94. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/1e4976294bffeaa6
  95. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/247c677b3d2ee7d7
  96. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/2940cad0e1b165c5
  97. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/2eafed28f42a799b
  98. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/2fa28f4c3423d42d
  99. 0 0
      legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/406a65375d9339a3
  100. 0 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/446e2c92d43d091a

+ 5 - 126
README.zh-CN.md

@@ -1,128 +1,7 @@
-# HTH 6400 可用初版
+# Prod2U 6400 UART 抽象层(远端构建)
 
-## 5 分钟快速开始
+该小型工具实现 6400 手动 UART/I2C 的 `SetAll`、`GetSnapshot`、CRC、ACK 解码和寄存器事务编码。
+通道 4 默认向量为:PTC18..23=100,Front3=30,Rear3=10,其余风扇=20。
 
-当前审核软件版本是 `v1.0.0-rc2`。它默认安装 **6400 Production + Mock** 服务,不打开串口,也不操作硬件。请从审核交付目录下载:
-
-- `hth-linux-amd64-v1.0.0-rc2.tar.gz` 与同名 `.sha256`:Linux amd64 服务、CLI、Python SDK wheel。
-
-```bash
-sha256sum -c hth-linux-amd64-v1.0.0-rc2.tar.gz.sha256
-tar -xzf hth-linux-amd64-v1.0.0-rc2.tar.gz
-cd hth-linux-amd64-v1.0.0-rc2
-
-./selftest.sh
-sudo ./install.sh
-./verify-install.sh
-```
-
-成功标志分别是 `HTH_AMD64_SELFTEST_PASS`、`HTH_INSTALL_PASS` 和
-`HTH_VERIFY_INSTALL_PASS`。安装后服务是 `hthd.service`,配置是
-`/etc/hth/hthd.yaml`,观察/控制接口是 `/run/hth/{observe,control}/*.sock`。
-
-## 从上一正式 Release 升级
-
-上一正式 HTH Release 已由 Git tag 确认为 `v0.1.1`,提交
-`7128a205a5cf70256bf6bb3cc87068b1d03e7fd4`。它使用同一个
-`hthd.service` 和旧的 `/usr/local/bin`、`/etc/hth`、`/var/lib/hth`
-布局。旧配置不兼容 6400 Production,因此升级器自动停止旧服务、移除已知旧布局、
-安装新的 Production Mock 配置并做自检:
-
-```bash
-cd hth-linux-amd64-v1.0.0-rc2
-sudo ./install.sh --upgrade
-```
-
-不要手工复制二进制、编辑 systemd 或创建第二个串口进程。升级完成后只应有一套
-`/usr/local/bin/hth{d,ctl,-capture}` 和一个 `hthd.service`。
-
-## 日常状态和基础自检
-
-```bash
-systemctl status hthd.service --no-pager
-journalctl -u hthd.service -n 50 --no-pager
-./verify-install.sh
-```
-
-`verify-install.sh` 会显示版本、源码提交、服务状态、配置路径、Production profile、
-唯一进程、SDK wheel,并通过 Mock UDS 读取和解码一个 193 字节 Snapshot。它不把
-Mock、PTY 或 RTL 仿真描述成真机验证。
-
-CLI 示例:
-
-```bash
-sudo /usr/local/bin/hthctl \
-  --observe-sock /run/hth/observe/observe.sock \
-  --device prod2u-6400-0 --timeout 5s thermal-snapshot
-```
-
-## 最小 Python SDK 示例
-
-SDK wheel 安装在 `/usr/local/share/hth/sdk/`。不要修改全局 PATH;使用虚拟环境:
-
-```bash
-sudo usermod -aG hth-observe,hth-control "$USER"
-# 重新登录一次,使组权限生效
-python3 -m venv .venv-hth
-. .venv-hth/bin/activate
-python -m pip install '/usr/local/share/hth/sdk/hth_sdk-0.3.0-py3-none-any.whl[live]'
-```
-
-```python
-from hth_sdk.thermal import connect_thermal
-
-with connect_thermal() as hth:
-    hth.set_target(60)              # 0=停止;其他合法值为 20..70 C
-    snapshot = hth.get_snapshot()   # 已校验并解码 193 字节 payload
-    print(snapshot.decoded["current_target"])
-    hth.stop()
-```
-
-只有 `hthd` 可以打开串口;SDK、CLI、采集和 Replay 都只连接 Unix Socket。
-Production profile 会拒绝 Identification stimulus。
-
-## 真实串口
-
-本初版交付和安装矩阵只运行 Mock,未访问 COM/串口。未来获得硬件授权并确认稳定
-设备名后,才可显式安装 serial backend:
-
-```bash
-sudo ./install.sh --backend serial --serial-path /dev/hth/controller0
-```
-
-这条命令会打开真实串口,不属于本阶段已运行证据。不要直接使用不稳定的
-`/dev/ttyUSB0` 编号,也不要让第二个进程抢占设备。
-
-## 常见错误
-
-- `permission denied`:把用户加入 `hth-observe,hth-control` 后重新登录;
-  临时诊断可直接运行 `./verify-install.sh`,它会用 sudo 自检。
-- `hthd.service failed`:运行
-  `sudo hthd --check-config --config /etc/hth/hthd.yaml`,再查看
-  `sudo journalctl -u hthd -n 100 --no-pager`。
-- 检测到旧安装:使用 `sudo ./install.sh --upgrade`,不要手工删文件。
-- `serial device does not exist`:保持 Mock;本阶段没有获准操作硬件。
-- Snapshot 不是 193 字节:停止使用该服务并保留 `verify-install.sh` 输出和日志。
-
-## 彻底卸载和重装
-
-```bash
-sudo ./uninstall.sh --purge --yes
-sudo ./install.sh
-./verify-install.sh
-```
-
-purge 只处理安装清单列出的 HTH 文件、服务、配置和产品专用状态目录;删除前会解析
-并检查绝对路径,最后运行残留冲突扫描。它不会 reset/clean/stash Git,不删除共享
-依赖或清单外文件。
-
-## 固件状态:DO NOT PROGRAM
-
-当前审核软件包不包含可烧录固件。Host TTL RX/TX 仍没有冻结的 FPGA Ball 约束,已有
-TD 输出使用了自动分配的未知板网,因此现有 6400 BIT 全部为 **REJECTED / DO NOT
-PROGRAM**。不要继续使用旧 `rc1` 固件包、旧 BIT 名称或旧 SHA-256 作为烧录依据。
-
-只有在 Host TTL 引脚被准确确认,或硬件 Profile 经授权明确改为 RS-232-only,并重新
-完成 TD 与绑定打包后,才会在交付目录提供新的固件文件和 SHA-256。Hardware、COM、
-JTAG、烧录和真实温控性能均为 **NOT RUN**;Mock、PTY 和 RTL cosim 只证明软件与仿真
-行为,不代表真机验证。
+它不实现 PID、自动温控或 MCU HAL;I2C 仅提供寄存器事务编码,不访问 `/dev/i2c-*`。`--dry-run` 只打印 Golden Frame;指定 `--port`
+时才打开 UART。生产使用前必须确认设备、波特率和串口独占权。

+ 109 - 0
cmd/6400-uart/main.go

@@ -0,0 +1,109 @@
+package main
+
+import (
+	"encoding/hex"
+	"errors"
+	"flag"
+	"fmt"
+	"io"
+	"os"
+	"os/exec"
+	"strings"
+	"syscall"
+	"time"
+
+	"prod2u6400-uartkit/internal/protocol"
+)
+
+func main() {
+	port := flag.String("port", "", "UART device, e.g. /dev/ttyUSB2")
+	mode := flag.String("mode", "set-all", "set-all or get-snapshot")
+	preset := flag.String("preset", "channel4", "channel4 or safe")
+	dry := flag.Bool("dry-run", false, "print frame and do not open UART")
+	flag.Parse()
+
+	s := protocol.SetAll{}
+	for i := range s.Front {
+		s.Front[i] = 20
+	}
+	for i := range s.Rear {
+		s.Rear[i] = 20
+	}
+	if *preset == "channel4" {
+		for i := 18; i < 24; i++ {
+			s.PTC[i] = 100
+		}
+		s.Front[3], s.Rear[3] = 30, 10
+	} else if *preset != "safe" {
+		panic(fmt.Errorf("unknown preset %q", *preset))
+	}
+
+	var frame []byte
+	var err error
+	switch *mode {
+	case "set-all":
+		frame, err = protocol.EncodeSetAll(s)
+	case "get-snapshot":
+		frame = protocol.EncodeGetSnapshot()
+	default:
+		err = fmt.Errorf("unknown mode %q", *mode)
+	}
+	if err != nil {
+		panic(err)
+	}
+	fmt.Printf("TX %s\n", strings.ToUpper(hex.EncodeToString(frame)))
+	if *dry || *port == "" {
+		return
+	}
+	if err := exec.Command("stty", "-F", *port, "921600", "cs8", "-cstopb", "-parenb", "raw", "-echo", "-ixon", "-ixoff", "-crtscts").Run(); err != nil {
+		panic(err)
+	}
+	fd, err := syscall.Open(*port, syscall.O_RDWR|syscall.O_NONBLOCK, 0)
+	if err != nil {
+		panic(err)
+	}
+	f := os.NewFile(uintptr(fd), *port)
+	if f == nil {
+		_ = syscall.Close(fd)
+		panic("cannot wrap UART fd")
+	}
+	defer f.Close()
+	if _, err = f.Write(frame); err != nil {
+		panic(err)
+	}
+
+	deadline := time.Now().Add(5 * time.Second)
+	buf := make([]byte, 256)
+	rx := make([]byte, 0, 512)
+	for time.Now().Before(deadline) {
+		n, rerr := f.Read(buf)
+		if n > 0 {
+			rx = append(rx, buf[:n]...)
+			for len(rx) >= protocol.FrameOverhead {
+				if rx[0] != protocol.Header0 || rx[1] != protocol.Header1 {
+					rx = rx[1:]
+					continue
+				}
+				total := protocol.FrameOverhead + int(rx[3])
+				if len(rx) < total {
+					break
+				}
+				raw := append([]byte(nil), rx[:total]...)
+				if fr, derr := protocol.Decode(raw); derr == nil {
+					fmt.Printf("RX %s\n", strings.ToUpper(hex.EncodeToString(raw)))
+					if fr.Type == protocol.TypeAck {
+						a, _ := protocol.DecodeAck(fr)
+						fmt.Printf("ACK ok=%t request=0x%02X status=%d detail=%d\n", a.OK, a.Request, a.Status, a.Detail)
+					}
+					return
+				}
+				rx = rx[1:]
+			}
+		}
+		if rerr != nil && rerr != io.EOF && !errors.Is(rerr, syscall.EAGAIN) {
+			time.Sleep(10 * time.Millisecond)
+		}
+		time.Sleep(10 * time.Millisecond)
+	}
+	fmt.Println("RX timeout/no complete framed response")
+}

+ 30 - 457
cmd/hthctl/main.go

@@ -1,474 +1,47 @@
 package main
 
 import (
-	"context"
-	"encoding/json"
+	"encoding/hex"
 	"flag"
 	"fmt"
-	"io"
 	"os"
-	"strings"
-	"time"
-
-	"google.golang.org/grpc"
-	"google.golang.org/grpc/health/grpc_health_v1"
-	"google.golang.org/protobuf/encoding/protojson"
-	"google.golang.org/protobuf/proto"
-	"google.golang.org/protobuf/types/known/durationpb"
-	"google.golang.org/protobuf/types/known/timestamppb"
-	"hth/internal/app"
-	"hth/internal/config"
-	hthv1 "hth/internal/gen/hth/api/v1"
-	"hth/internal/grpcserver"
-	"hth/internal/profile"
+	"prod2u6400-uartkit/internal/protocol"
 )
 
 func main() {
-	fs := flag.NewFlagSet("hthctl", flag.ExitOnError)
-	observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
-	control := fs.String("control-sock", "/tmp/hth-mock/control.sock", "control unix socket")
-	deviceID := fs.String("device", "prod2u-0", "device id")
-	cfgPath := fs.String("config", "", "optional local config for doctor")
-	realHW := fs.Bool("i-understand-this-is-real-hardware", false, "required for commands that mutate device state on non-mock backends")
-	timeout := fs.Duration("timeout", 0, "rpc timeout; 0 uses TimingCapabilities for mutating commands, 5s for observe")
-	count := fs.Int("count", 0, "watch/events count (0=until interrupt)")
-	holder := fs.String("holder", "hthctl", "lease holder")
-	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|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 {
-		fmt.Fprintln(os.Stderr, err)
+	mode := flag.String("mode", "set-all", "set-all, get-snapshot, or i2c-set-all")
+	preset := flag.String("preset", "channel4", "channel4 or safe")
+	flag.Parse()
+	s := protocol.SetAll{}
+	for i := range s.Front {
+		s.Front[i] = 20
+	}
+	for i := range s.Rear {
+		s.Rear[i] = 20
+	}
+	if *preset == "channel4" {
+		for i := 18; i < 24; i++ {
+			s.PTC[i] = 100
+		}
+		s.Front[3], s.Rear[3] = 30, 10
+	} else if *preset != "safe" {
+		fmt.Fprintln(os.Stderr, "unknown preset")
 		os.Exit(2)
 	}
-	if commandMutatesDevice(cmd) && (cmd != "doctor" || *cfgPath == "") {
-		if err := requireRealAck(*observe, *realHW); err != nil {
-			fmt.Fprintln(os.Stderr, err)
-			os.Exit(2)
-		}
-	}
-	rpcTimeout := *timeout
-	if rpcTimeout <= 0 {
-		if commandMutatesDevice(cmd) {
-			ms, err := timingDeadlineMS(*observe, *deviceID)
-			if err != nil || ms <= 0 {
-				fmt.Fprintln(os.Stderr, "FAIL CLOSED: mutating command requires --timeout or GetCapabilities TimingCapabilities.recommended_rpc_deadline_ms:", err)
-				os.Exit(2)
-			}
-			rpcTimeout = time.Duration(ms) * time.Millisecond
-		} else {
-			rpcTimeout = 5 * time.Second
-		}
-	}
-	ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
-	defer cancel()
-	switch cmd {
-	case "doctor":
-		fatal(runDoctor(ctx, *cfgPath, *observe))
-	case "devices":
-		c := observeClient(*observe, rpcTimeout)
-		resp, err := c.ListDevices(ctx, &hthv1.ListDevicesRequest{})
-		fatal(err)
-		printMsg(resp)
-	case "capabilities":
-		c := observeClient(*observe, rpcTimeout)
-		resp, err := c.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
-		fatal(err)
-		printMsg(resp)
-	case "snapshot":
-		c := observeClient(*observe, rpcTimeout)
-		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})
-		fatal(err)
-		n := 0
-		for {
-			s, err := st.Recv()
-			fatal(err)
-			printMsg(s)
-			n++
-			if *count > 0 && n >= *count {
-				return
-			}
-		}
-	case "events":
-		c := observeClient(*observe, rpcTimeout)
-		st, err := c.SubscribeEvents(context.Background(), &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
-		fatal(err)
-		n := 0
-		for {
-			e, err := st.Recv()
-			fatal(err)
-			printMsg(e)
-			n++
-			if *count > 0 && n >= *count {
-				return
-			}
-		}
-	case "faults":
-		c := observeClient(*observe, rpcTimeout)
-		resp, err := c.GetFaults(ctx, &hthv1.GetFaultsRequest{DeviceId: *deviceID, IncludeInactive: true})
-		fatal(err)
-		printMsg(resp)
-	case "health":
-		conn := mustDial(*observe, rpcTimeout)
-		defer conn.Close()
-		hc := grpc_health_v1.NewHealthClient(conn)
-		resp, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
-		fatal(err)
-		fmt.Println(resp.Status.String())
-		oc := hthv1.NewObserveServiceClient(conn)
-		st, err := oc.WatchHealth(ctx, &hthv1.WatchHealthRequest{})
-		fatal(err)
-		msg, err := st.Recv()
-		fatal(err)
-		printMsg(msg)
-	case "validate-action":
-		batch := loadBatch(*file, *deviceID, *allowClamp)
-		c := controlClient(*control, rpcTimeout)
-		res, err := c.ValidateAction(ctx, &hthv1.ValidateActionRequest{Batch: batch})
-		fatal(err)
-		printAction(res)
-	case "apply-action":
-		cc := controlClient(*control, rpcTimeout)
-		oc := observeClient(*observe, rpcTimeout)
-		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
-			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
-		})
-		fatal(err)
-		snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
-		fatal(err)
-		batch := loadBatch(*file, *deviceID, *allowClamp)
-		batch.LeaseId = lease.Lease.LeaseId
-		batch.LeaseEpoch = lease.Lease.LeaseEpoch
-		batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
-		batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
-		if batch.ValidUntil == nil {
-			batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
-		}
-		if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
-			batch.CommandId = fmt.Sprintf("hthctl-%d", time.Now().UnixNano())
-		}
-		res, err := cc.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: batch})
-		fatal(err)
-		printAction(res)
-	case "enter-safe-mode":
-		cc := controlClient(*control, rpcTimeout)
-		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
-			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
-		})
-		fatal(err)
-		res, err := cc.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
-			DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "hthctl",
-		})
-		fatal(err)
-		printAction(res)
-	case "resume-from-safe":
-		cc := controlClient(*control, rpcTimeout)
-		oc := observeClient(*observe, rpcTimeout)
-		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
-			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
-		})
-		fatal(err)
-		snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
-		fatal(err)
-		batch := loadBatch(*file, *deviceID, false)
-		if len(batch.GetContinuousTargets()) == 0 {
-			fatal(fmt.Errorf("resume-from-safe FAIL CLOSED: --file must contain a complete ActionBatch; snapshot has no invented fan=10/ptc=0/doors=0 defaults"))
-		}
-		batch.LeaseId = lease.Lease.LeaseId
-		batch.LeaseEpoch = lease.Lease.LeaseEpoch
-		batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
-		batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
-		if batch.ValidUntil == nil {
-			batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
-		}
-		if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
-			batch.CommandId = fmt.Sprintf("hthctl-resume-%d", time.Now().UnixNano())
-		}
-		res, err := cc.ResumeFromSafe(ctx, &hthv1.ResumeFromSafeRequest{
-			DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Batch: batch,
-		})
-		fatal(err)
-		printAction(res)
-	case "step-replay":
-		cc := controlClient(*control, rpcTimeout)
-		res, err := cc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
-		fatal(err)
-		printMsg(res)
-	default:
-		fmt.Fprintln(os.Stderr, "unknown command", cmd)
-		os.Exit(2)
-	}
-}
-
-// parseHthctlArgs accepts both `hthctl --file x resume-from-safe` and
-// `hthctl resume-from-safe --file x`. Go's FlagSet stops at the first
-// non-flag, so flags after the subcommand must be parsed in a second pass.
-func parseHthctlArgs(fs *flag.FlagSet, argv []string) string {
-	_ = fs.Parse(argv)
-	args := fs.Args()
-	if len(args) == 0 {
-		return ""
-	}
-	cmd := args[0]
-	if len(args) > 1 {
-		_ = fs.Parse(args[1:])
-	}
-	return cmd
-}
-
-func commandMutatesDevice(cmd string) bool {
-	switch cmd {
-	case "apply-action", "enter-safe-mode", "resume-from-safe", "step-replay", "set-target", "stop", "run-stimulus":
-		return true
-	default:
-		return false
-	}
-}
-
-func timingDeadlineMS(observe, deviceID string) (uint32, error) {
-	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
-	if err != nil {
-		return 0, err
-	}
-	defer conn.Close()
-	cli := hthv1.NewObserveServiceClient(conn)
-	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
-	defer cancel()
-	resp, err := cli.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: deviceID})
-	if err != nil {
-		return 0, err
-	}
-	t := resp.GetCapabilities().GetTiming()
-	if t == nil || t.GetRecommendedRpcDeadlineMs() == 0 {
-		return 0, fmt.Errorf("capabilities.timing.recommended_rpc_deadline_ms missing")
-	}
-	return t.GetRecommendedRpcDeadlineMs(), nil
-}
-
-func requireActionFile(cmd, file string) error {
-	switch cmd {
-	case "validate-action", "apply-action", "resume-from-safe", "run-stimulus":
-		if strings.TrimSpace(file) == "" {
-			return fmt.Errorf("%s requires --file with complete JSON input; refusing implicit values", cmd)
-		}
-	}
-	return nil
-}
-
-func backendRequiresHardwareAck(kind string) bool {
-	switch strings.ToLower(strings.TrimSpace(kind)) {
-	case "mock", "replay":
-		return false
-	default:
-		return true
-	}
-}
-
-func refuseIfSerialNeedsAck(kind, observe string, ack bool) error {
-	if !backendRequiresHardwareAck(kind) {
-		return nil
-	}
-	if ack {
-		return nil
-	}
-	return fmt.Errorf("refusing serial backend kind %q at observe %s without --i-understand-this-is-real-hardware (path is not used to detect mock)", kind, observe)
-}
-
-func requireRealAck(observe string, ack bool) error {
-	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
-	if err != nil {
-		return fmt.Errorf("cannot read DeviceIdentity.backend_kind from observe socket %s: %w", observe, err)
-	}
-	defer conn.Close()
-	cli := hthv1.NewObserveServiceClient(conn)
-	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
-	defer cancel()
-	resp, err := cli.ListDevices(ctx, &hthv1.ListDevicesRequest{})
-	if err != nil {
-		return fmt.Errorf("ListDevices for backend_kind: %w", err)
-	}
-	if len(resp.GetDevices()) == 0 {
-		return refuseIfSerialNeedsAck("unknown", observe, ack)
-	}
-	for _, d := range resp.GetDevices() {
-		kind := ""
-		if d.GetIdentity() != nil {
-			kind = d.GetIdentity().GetBackendKind()
-		}
-		if err := refuseIfSerialNeedsAck(kind, observe, ack); err != nil {
-			return err
-		}
-	}
-	return nil
-}
-
-func runDoctor(ctx context.Context, cfgPath, observe string) error {
-	if cfgPath != "" {
-		cfg, err := config.Load(cfgPath)
-		if 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))
-		}
-	}
-	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
-	if err != nil {
-		if cfgPath != "" {
-			fmt.Println("live observe socket: not connected (", err, ")")
-			return nil
-		}
-		return err
-	}
-	defer conn.Close()
-	hc := grpc_health_v1.NewHealthClient(conn)
-	st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
-	if err != nil {
-		return err
-	}
-	fmt.Println("grpc_health", st.Status.String())
-	return nil
-}
-
-func observeClient(path string, d time.Duration) hthv1.ObserveServiceClient {
-	return hthv1.NewObserveServiceClient(mustDial(path, d))
-}
-
-func controlClient(path string, d time.Duration) hthv1.ControlServiceClient {
-	return hthv1.NewControlServiceClient(mustDial(path, d))
-}
-
-func mustDial(path string, d time.Duration) *grpc.ClientConn {
-	c, err := grpcserver.DialUnix(path, d)
-	fatal(err)
-	return c
-}
-
-func printMsg(m proto.Message) {
-	b, err := protojson.MarshalOptions{Multiline: true, UseProtoNames: true}.Marshal(m)
-	if err != nil {
-		fmt.Println(err)
+	if *mode == "set-all" {
+		b, _ := protocol.EncodeSetAll(s)
+		fmt.Println(hex.EncodeToString(b))
 		return
 	}
-	fmt.Println(string(b))
-}
-
-func printAction(res *hthv1.ActionResult) {
-	fmt.Println("accepted", res.Accepted, "confirmation", res.Confirmation.String(), "reject", res.RejectReason.String())
-	fmt.Println("message", res.Message)
-	fmt.Println("replayed_from_cache", res.ReplayedFromCache)
-	printNamed("requested", res.Requested)
-	printNamed("accepted", res.AcceptedAction)
-	printNamed("dispatched", res.Dispatched)
-}
-
-func printNamed(name string, rec *hthv1.ActionRecord) {
-	if rec == nil {
-		fmt.Println(name, "(none)")
+	if *mode == "get-snapshot" {
+		fmt.Println(hex.EncodeToString(protocol.EncodeGetSnapshot()))
 		return
 	}
-	b, _ := protojson.MarshalOptions{UseProtoNames: true}.Marshal(rec)
-	fmt.Println(name, string(b))
-}
-
-func loadBatch(path, deviceID string, clamp bool) *hthv1.ActionBatch {
-	b := &hthv1.ActionBatch{DeviceId: deviceID, CommandId: "hthctl-validate", AllowClamp: clamp, ClientId: "hthctl"}
-	if strings.TrimSpace(path) == "" {
-		fatal(fmt.Errorf("ActionBatch --file is required"))
-	}
-	raw, err := os.ReadFile(path)
-	fatal(err)
-	fatal(protojson.Unmarshal(raw, b))
-	if b.DeviceId == "" {
-		b.DeviceId = deviceID
-	}
-	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)
-		os.Exit(1)
+	if *mode == "i2c-set-all" {
+		p, _ := s.Payload()
+		fmt.Printf("addr=0x%02X staging=0100%s command=001001\n", 0x2A, hex.EncodeToString(p))
+		return
 	}
+	fmt.Fprintln(os.Stderr, "unknown mode")
+	os.Exit(2)
 }

+ 1 - 16
go.mod

@@ -1,18 +1,3 @@
-module hth
+module prod2u6400-uartkit
 
 go 1.25.0
-
-require (
-	go.uber.org/goleak v1.3.0
-	golang.org/x/sys v0.47.0
-	google.golang.org/grpc v1.82.1
-	google.golang.org/protobuf v1.36.12
-	gopkg.in/yaml.v3 v3.0.1
-)
-
-require (
-	github.com/kr/text v0.2.0 // indirect
-	golang.org/x/net v0.58.0 // indirect
-	golang.org/x/text v0.41.0 // indirect
-	google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
-)

+ 1 - 0
golden-vectors.json

@@ -0,0 +1 @@
+{"contract_sha256":"3d1db034f6b60bc3d747e882defe60b168d37eb356449d46933da824c1c0214a","frames":{"get_snapshot":"A55A02006D7B","get_snapshot_ack":"A55A0604010200002312","removed_04":"A55A0400CBD1","removed_04_ack":"A55A06040004010006E5","set_all_ack":"A55A060401010000734B","set_all_safe":"A55A01200000000000000000000000000000000000000000000000001414141414141414E70A"},"schema":"prod2u-6400-manual-golden-v1"}

Разница между файлами не показана из-за своего большого размера
+ 1 - 0
host-i2c-register-map.json


+ 81 - 0
internal/i2creg/i2creg.go

@@ -0,0 +1,81 @@
+package i2creg
+
+import (
+	"encoding/binary"
+	"fmt"
+	"prod2u6400-uartkit/internal/protocol"
+)
+
+const (
+	Address7           byte   = 0x2A
+	RegDeviceStatus    uint16 = 0x0000
+	RegResponseOK      uint16 = 0x0001
+	RegResponseCommand uint16 = 0x0002
+	RegResponseStatus  uint16 = 0x0003
+	RegResponseDetail  uint16 = 0x0004
+	RegWatchdogSeconds uint16 = 0x0005
+	RegWrittenMask     uint16 = 0x0006
+	RegSnapshotLengthL uint16 = 0x0007
+	RegSnapshotLengthH uint16 = 0x0008
+	RegCommand         uint16 = 0x0010
+	RegStagingBase     uint16 = 0x0100
+	RegSnapshotBase    uint16 = 0x0200
+)
+
+type Transaction struct {
+	Address7      byte
+	Write         []byte
+	ReadLength    int
+	RepeatedStart bool
+}
+
+func pointer(reg uint16) []byte {
+	var p [2]byte
+	binary.BigEndian.PutUint16(p[:], reg)
+	return p[:]
+}
+
+func SetAllTransactions(s protocol.SetAll) ([]Transaction, error) {
+	p, err := s.Payload()
+	if err != nil {
+		return nil, err
+	}
+	w := append(pointer(RegStagingBase), p...)
+	c := append(pointer(RegCommand), protocol.TypeSetAll)
+	return []Transaction{{Address7: Address7, Write: w}, {Address7: Address7, Write: c}}, nil
+}
+
+func GetSnapshotTransactions() []Transaction {
+	return []Transaction{{Address7: Address7, Write: append(pointer(RegCommand), protocol.TypeGetSnapshot)}}
+}
+
+func ReadRegister(reg uint16, n int) Transaction {
+	return Transaction{Address7: Address7, Write: pointer(reg), ReadLength: n, RepeatedStart: true}
+}
+
+func SnapshotReads(length uint16, chunk int) ([]Transaction, error) {
+	if chunk <= 0 {
+		return nil, fmt.Errorf("chunk must be positive")
+	}
+	if length == 0 {
+		return nil, nil
+	}
+	result := make([]Transaction, 0, (int(length)+chunk-1)/chunk)
+	for off := 0; off < int(length); off += chunk {
+		n := chunk
+		if rem := int(length) - off; rem < n {
+			n = rem
+		}
+		result = append(result, ReadRegister(RegSnapshotBase+uint16(off), n))
+	}
+	return result, nil
+}
+
+type Response struct{ OK, Command, Status, Detail byte }
+
+func DecodeResponse(regs []byte) (Response, error) {
+	if len(regs) < 4 {
+		return Response{}, fmt.Errorf("response requires 4 bytes")
+	}
+	return Response{OK: regs[0], Command: regs[1], Status: regs[2], Detail: regs[3]}, nil
+}

+ 46 - 0
internal/i2creg/i2creg_test.go

@@ -0,0 +1,46 @@
+package i2creg
+
+import (
+	"prod2u6400-uartkit/internal/protocol"
+	"testing"
+)
+
+func TestSetAllTransactions(t *testing.T) {
+	s := protocol.SetAll{}
+	for i := range s.Front {
+		s.Front[i] = 20
+	}
+	for i := range s.Rear {
+		s.Rear[i] = 20
+	}
+	s.Front[3], s.Rear[3] = 30, 10
+	for i := 18; i < 24; i++ {
+		s.PTC[i] = 100
+	}
+	ts_, err := SetAllTransactions(s)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(ts_) != 2 || ts_[0].Address7 != Address7 {
+		t.Fatalf("transactions=%+v", ts_)
+	}
+	if len(ts_[0].Write) != 34 || ts_[0].Write[0] != 1 || ts_[0].Write[1] != 0 {
+		t.Fatalf("staging write=%x", ts_[0].Write)
+	}
+	if len(ts_[1].Write) != 3 || ts_[1].Write[0] != 0 || ts_[1].Write[1] != 0x10 || ts_[1].Write[2] != 1 {
+		t.Fatalf("command write=%x", ts_[1].Write)
+	}
+}
+
+func TestSnapshotReads(t *testing.T) {
+	ts_, err := SnapshotReads(201, 64)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(ts_) != 4 || ts_[0].Write[0] != 2 || ts_[0].Write[1] != 0 {
+		t.Fatalf("reads=%+v", ts_)
+	}
+	if ts_[3].ReadLength != 9 || !ts_[3].RepeatedStart {
+		t.Fatalf("last=%+v", ts_[3])
+	}
+}

+ 115 - 0
internal/protocol/protocol.go

@@ -0,0 +1,115 @@
+package protocol
+
+import (
+	"encoding/binary"
+	"errors"
+	"fmt"
+)
+
+const (
+	Header0          byte = 0xA5
+	Header1          byte = 0x5A
+	TypeSetAll       byte = 0x01
+	TypeGetSnapshot  byte = 0x02
+	TypeReserved     byte = 0x03
+	TypeRemoved      byte = 0x04
+	TypeAck          byte = 0x06
+	TypeSnapshot     byte = 0x82
+	SetAllPayloadLen      = 32
+	FrameOverhead         = 6
+)
+
+var (
+	ErrHeader  = errors.New("bad A5 5A header")
+	ErrLength  = errors.New("frame length mismatch")
+	ErrCRC     = errors.New("CRC-16/CCITT-FALSE mismatch")
+	ErrPayload = errors.New("invalid SET_ALL payload")
+)
+
+type SetAll struct {
+	PTC   [24]byte
+	Front [4]byte
+	Rear  [4]byte
+}
+
+func (s SetAll) Payload() ([]byte, error) {
+	p := make([]byte, SetAllPayloadLen)
+	copy(p[0:24], s.PTC[:])
+	copy(p[24:28], s.Front[:])
+	copy(p[28:32], s.Rear[:])
+	for i, v := range p {
+		if v > 100 {
+			return nil, fmt.Errorf("%w: index %d value %d", ErrPayload, i, v)
+		}
+	}
+	return p, nil
+}
+
+func Encode(frameType byte, payload []byte) []byte {
+	b := make([]byte, 0, FrameOverhead+len(payload))
+	b = append(b, Header0, Header1, frameType, byte(len(payload)))
+	b = append(b, payload...)
+	c := CRC16(b[2:])
+	var le [2]byte
+	binary.LittleEndian.PutUint16(le[:], c)
+	return append(b, le[0], le[1])
+}
+
+func EncodeSetAll(s SetAll) ([]byte, error) {
+	p, err := s.Payload()
+	if err != nil {
+		return nil, err
+	}
+	return Encode(TypeSetAll, p), nil
+}
+
+func EncodeGetSnapshot() []byte { return Encode(TypeGetSnapshot, nil) }
+
+type Frame struct {
+	Type    byte
+	Payload []byte
+}
+
+func Decode(raw []byte) (Frame, error) {
+	if len(raw) < FrameOverhead || raw[0] != Header0 || raw[1] != Header1 {
+		return Frame{}, ErrHeader
+	}
+	n := int(raw[3])
+	if len(raw) != FrameOverhead+n {
+		return Frame{}, fmt.Errorf("%w: declared=%d actual=%d", ErrLength, n, len(raw))
+	}
+	if binary.LittleEndian.Uint16(raw[len(raw)-2:]) != CRC16(raw[2:len(raw)-2]) {
+		return Frame{}, ErrCRC
+	}
+	p := append([]byte(nil), raw[4:4+n]...)
+	return Frame{Type: raw[2], Payload: p}, nil
+}
+
+type Ack struct {
+	OK      bool
+	Request byte
+	Status  byte
+	Detail  byte
+}
+
+func DecodeAck(f Frame) (Ack, error) {
+	if f.Type != TypeAck || len(f.Payload) != 4 {
+		return Ack{}, fmt.Errorf("invalid ACK frame")
+	}
+	return Ack{OK: f.Payload[0] != 0, Request: f.Payload[1], Status: f.Payload[2], Detail: f.Payload[3]}, nil
+}
+
+func CRC16(data []byte) uint16 {
+	crc := uint16(0xFFFF)
+	for _, b := range data {
+		crc ^= uint16(b) << 8
+		for i := 0; i < 8; i++ {
+			if crc&0x8000 != 0 {
+				crc = (crc << 1) ^ 0x1021
+			} else {
+				crc <<= 1
+			}
+		}
+	}
+	return crc
+}

+ 81 - 0
internal/transport/transport.go

@@ -0,0 +1,81 @@
+package transport
+
+import (
+	"context"
+	"fmt"
+	"prod2u6400-uartkit/internal/protocol"
+	"sync"
+)
+
+type UARTTransport interface {
+	WriteSetAll(context.Context, protocol.SetAll) error
+	GetSnapshot(context.Context) ([]byte, error)
+}
+
+type MockTransport struct {
+	mu     sync.Mutex
+	last   protocol.SetAll
+	writes int
+}
+
+func (m *MockTransport) WriteSetAll(_ context.Context, s protocol.SetAll) error {
+	if _, err := s.Payload(); err != nil {
+		return err
+	}
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	m.last, m.writes = s, m.writes+1
+	return nil
+}
+
+func (m *MockTransport) GetSnapshot(context.Context) ([]byte, error) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	p, err := m.last.Payload()
+	if err != nil {
+		return nil, err
+	}
+	return append([]byte(nil), p...), nil
+}
+
+func (m *MockTransport) Last() (protocol.SetAll, int) {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return m.last, m.writes
+}
+
+type ReplayTransport struct {
+	Frames [][]byte
+	Index  int
+}
+
+func (r *ReplayTransport) WriteSetAll(_ context.Context, s protocol.SetAll) error {
+	p, err := s.Payload()
+	if err != nil {
+		return err
+	}
+	if r.Index >= len(r.Frames) {
+		return fmt.Errorf("replay exhausted")
+	}
+	fr, err := protocol.Decode(r.Frames[r.Index])
+	if err != nil {
+		return err
+	}
+	if fr.Type != protocol.TypeSetAll || string(fr.Payload) != string(p) {
+		return fmt.Errorf("replay SET_ALL mismatch")
+	}
+	r.Index++
+	return nil
+}
+
+func (r *ReplayTransport) GetSnapshot(context.Context) ([]byte, error) {
+	if r.Index >= len(r.Frames) {
+		return nil, fmt.Errorf("replay exhausted")
+	}
+	fr, err := protocol.Decode(r.Frames[r.Index])
+	if err != nil {
+		return nil, err
+	}
+	r.Index++
+	return fr.Payload, nil
+}

+ 20 - 0
internal/transport/transport_test.go

@@ -0,0 +1,20 @@
+package transport
+
+import (
+	"context"
+	"prod2u6400-uartkit/internal/protocol"
+	"testing"
+)
+
+func TestMockTransport(t *testing.T) {
+	m := &MockTransport{}
+	s := protocol.SetAll{}
+	s.Front[3], s.Rear[3] = 30, 10
+	if err := m.WriteSetAll(context.Background(), s); err != nil {
+		t.Fatal(err)
+	}
+	got, n := m.Last()
+	if n != 1 || got.Front[3] != 30 || got.Rear[3] != 10 {
+		t.Fatalf("last=%+v writes=%d", got, n)
+	}
+}

Makefile → legacy-hth/Makefile


RELEASE.zh-CN.md → legacy-hth/RELEASE.zh-CN.md


REQUIREMENTS_TRACEABILITY.md → legacy-hth/REQUIREMENTS_TRACEABILITY.md


api/proto/google/protobuf/README.md → legacy-hth/api/proto/google/protobuf/README.md


api/proto/google/protobuf/duration.proto → legacy-hth/api/proto/google/protobuf/duration.proto


api/proto/google/protobuf/timestamp.proto → legacy-hth/api/proto/google/protobuf/timestamp.proto


api/proto/hth.api.v1.desc.prev → legacy-hth/api/proto/hth.api.v1.desc.prev


api/proto/hth/api/v1/hth.desc → legacy-hth/api/proto/hth/api/v1/hth.desc


api/proto/hth/api/v1/hth.proto → legacy-hth/api/proto/hth/api/v1/hth.proto


buf.yaml → legacy-hth/buf.yaml


cmd/hth-capture/main.go → legacy-hth/cmd/hth-capture/main.go


+ 474 - 0
legacy-hth/cmd/hthctl/main.go

@@ -0,0 +1,474 @@
+package main
+
+import (
+	"context"
+	"encoding/json"
+	"flag"
+	"fmt"
+	"io"
+	"os"
+	"strings"
+	"time"
+
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/health/grpc_health_v1"
+	"google.golang.org/protobuf/encoding/protojson"
+	"google.golang.org/protobuf/proto"
+	"google.golang.org/protobuf/types/known/durationpb"
+	"google.golang.org/protobuf/types/known/timestamppb"
+	"hth/internal/app"
+	"hth/internal/config"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/grpcserver"
+	"hth/internal/profile"
+)
+
+func main() {
+	fs := flag.NewFlagSet("hthctl", flag.ExitOnError)
+	observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
+	control := fs.String("control-sock", "/tmp/hth-mock/control.sock", "control unix socket")
+	deviceID := fs.String("device", "prod2u-0", "device id")
+	cfgPath := fs.String("config", "", "optional local config for doctor")
+	realHW := fs.Bool("i-understand-this-is-real-hardware", false, "required for commands that mutate device state on non-mock backends")
+	timeout := fs.Duration("timeout", 0, "rpc timeout; 0 uses TimingCapabilities for mutating commands, 5s for observe")
+	count := fs.Int("count", 0, "watch/events count (0=until interrupt)")
+	holder := fs.String("holder", "hthctl", "lease holder")
+	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|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 {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(2)
+	}
+	if commandMutatesDevice(cmd) && (cmd != "doctor" || *cfgPath == "") {
+		if err := requireRealAck(*observe, *realHW); err != nil {
+			fmt.Fprintln(os.Stderr, err)
+			os.Exit(2)
+		}
+	}
+	rpcTimeout := *timeout
+	if rpcTimeout <= 0 {
+		if commandMutatesDevice(cmd) {
+			ms, err := timingDeadlineMS(*observe, *deviceID)
+			if err != nil || ms <= 0 {
+				fmt.Fprintln(os.Stderr, "FAIL CLOSED: mutating command requires --timeout or GetCapabilities TimingCapabilities.recommended_rpc_deadline_ms:", err)
+				os.Exit(2)
+			}
+			rpcTimeout = time.Duration(ms) * time.Millisecond
+		} else {
+			rpcTimeout = 5 * time.Second
+		}
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
+	defer cancel()
+	switch cmd {
+	case "doctor":
+		fatal(runDoctor(ctx, *cfgPath, *observe))
+	case "devices":
+		c := observeClient(*observe, rpcTimeout)
+		resp, err := c.ListDevices(ctx, &hthv1.ListDevicesRequest{})
+		fatal(err)
+		printMsg(resp)
+	case "capabilities":
+		c := observeClient(*observe, rpcTimeout)
+		resp, err := c.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
+		fatal(err)
+		printMsg(resp)
+	case "snapshot":
+		c := observeClient(*observe, rpcTimeout)
+		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})
+		fatal(err)
+		n := 0
+		for {
+			s, err := st.Recv()
+			fatal(err)
+			printMsg(s)
+			n++
+			if *count > 0 && n >= *count {
+				return
+			}
+		}
+	case "events":
+		c := observeClient(*observe, rpcTimeout)
+		st, err := c.SubscribeEvents(context.Background(), &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
+		fatal(err)
+		n := 0
+		for {
+			e, err := st.Recv()
+			fatal(err)
+			printMsg(e)
+			n++
+			if *count > 0 && n >= *count {
+				return
+			}
+		}
+	case "faults":
+		c := observeClient(*observe, rpcTimeout)
+		resp, err := c.GetFaults(ctx, &hthv1.GetFaultsRequest{DeviceId: *deviceID, IncludeInactive: true})
+		fatal(err)
+		printMsg(resp)
+	case "health":
+		conn := mustDial(*observe, rpcTimeout)
+		defer conn.Close()
+		hc := grpc_health_v1.NewHealthClient(conn)
+		resp, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
+		fatal(err)
+		fmt.Println(resp.Status.String())
+		oc := hthv1.NewObserveServiceClient(conn)
+		st, err := oc.WatchHealth(ctx, &hthv1.WatchHealthRequest{})
+		fatal(err)
+		msg, err := st.Recv()
+		fatal(err)
+		printMsg(msg)
+	case "validate-action":
+		batch := loadBatch(*file, *deviceID, *allowClamp)
+		c := controlClient(*control, rpcTimeout)
+		res, err := c.ValidateAction(ctx, &hthv1.ValidateActionRequest{Batch: batch})
+		fatal(err)
+		printAction(res)
+	case "apply-action":
+		cc := controlClient(*control, rpcTimeout)
+		oc := observeClient(*observe, rpcTimeout)
+		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
+		})
+		fatal(err)
+		snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
+		fatal(err)
+		batch := loadBatch(*file, *deviceID, *allowClamp)
+		batch.LeaseId = lease.Lease.LeaseId
+		batch.LeaseEpoch = lease.Lease.LeaseEpoch
+		batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
+		batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
+		if batch.ValidUntil == nil {
+			batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
+		}
+		if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
+			batch.CommandId = fmt.Sprintf("hthctl-%d", time.Now().UnixNano())
+		}
+		res, err := cc.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: batch})
+		fatal(err)
+		printAction(res)
+	case "enter-safe-mode":
+		cc := controlClient(*control, rpcTimeout)
+		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
+		})
+		fatal(err)
+		res, err := cc.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
+			DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "hthctl",
+		})
+		fatal(err)
+		printAction(res)
+	case "resume-from-safe":
+		cc := controlClient(*control, rpcTimeout)
+		oc := observeClient(*observe, rpcTimeout)
+		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
+		})
+		fatal(err)
+		snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
+		fatal(err)
+		batch := loadBatch(*file, *deviceID, false)
+		if len(batch.GetContinuousTargets()) == 0 {
+			fatal(fmt.Errorf("resume-from-safe FAIL CLOSED: --file must contain a complete ActionBatch; snapshot has no invented fan=10/ptc=0/doors=0 defaults"))
+		}
+		batch.LeaseId = lease.Lease.LeaseId
+		batch.LeaseEpoch = lease.Lease.LeaseEpoch
+		batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
+		batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
+		if batch.ValidUntil == nil {
+			batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
+		}
+		if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
+			batch.CommandId = fmt.Sprintf("hthctl-resume-%d", time.Now().UnixNano())
+		}
+		res, err := cc.ResumeFromSafe(ctx, &hthv1.ResumeFromSafeRequest{
+			DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Batch: batch,
+		})
+		fatal(err)
+		printAction(res)
+	case "step-replay":
+		cc := controlClient(*control, rpcTimeout)
+		res, err := cc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
+		fatal(err)
+		printMsg(res)
+	default:
+		fmt.Fprintln(os.Stderr, "unknown command", cmd)
+		os.Exit(2)
+	}
+}
+
+// parseHthctlArgs accepts both `hthctl --file x resume-from-safe` and
+// `hthctl resume-from-safe --file x`. Go's FlagSet stops at the first
+// non-flag, so flags after the subcommand must be parsed in a second pass.
+func parseHthctlArgs(fs *flag.FlagSet, argv []string) string {
+	_ = fs.Parse(argv)
+	args := fs.Args()
+	if len(args) == 0 {
+		return ""
+	}
+	cmd := args[0]
+	if len(args) > 1 {
+		_ = fs.Parse(args[1:])
+	}
+	return cmd
+}
+
+func commandMutatesDevice(cmd string) bool {
+	switch cmd {
+	case "apply-action", "enter-safe-mode", "resume-from-safe", "step-replay", "set-target", "stop", "run-stimulus":
+		return true
+	default:
+		return false
+	}
+}
+
+func timingDeadlineMS(observe, deviceID string) (uint32, error) {
+	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
+	if err != nil {
+		return 0, err
+	}
+	defer conn.Close()
+	cli := hthv1.NewObserveServiceClient(conn)
+	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+	defer cancel()
+	resp, err := cli.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: deviceID})
+	if err != nil {
+		return 0, err
+	}
+	t := resp.GetCapabilities().GetTiming()
+	if t == nil || t.GetRecommendedRpcDeadlineMs() == 0 {
+		return 0, fmt.Errorf("capabilities.timing.recommended_rpc_deadline_ms missing")
+	}
+	return t.GetRecommendedRpcDeadlineMs(), nil
+}
+
+func requireActionFile(cmd, file string) error {
+	switch cmd {
+	case "validate-action", "apply-action", "resume-from-safe", "run-stimulus":
+		if strings.TrimSpace(file) == "" {
+			return fmt.Errorf("%s requires --file with complete JSON input; refusing implicit values", cmd)
+		}
+	}
+	return nil
+}
+
+func backendRequiresHardwareAck(kind string) bool {
+	switch strings.ToLower(strings.TrimSpace(kind)) {
+	case "mock", "replay":
+		return false
+	default:
+		return true
+	}
+}
+
+func refuseIfSerialNeedsAck(kind, observe string, ack bool) error {
+	if !backendRequiresHardwareAck(kind) {
+		return nil
+	}
+	if ack {
+		return nil
+	}
+	return fmt.Errorf("refusing serial backend kind %q at observe %s without --i-understand-this-is-real-hardware (path is not used to detect mock)", kind, observe)
+}
+
+func requireRealAck(observe string, ack bool) error {
+	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
+	if err != nil {
+		return fmt.Errorf("cannot read DeviceIdentity.backend_kind from observe socket %s: %w", observe, err)
+	}
+	defer conn.Close()
+	cli := hthv1.NewObserveServiceClient(conn)
+	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+	defer cancel()
+	resp, err := cli.ListDevices(ctx, &hthv1.ListDevicesRequest{})
+	if err != nil {
+		return fmt.Errorf("ListDevices for backend_kind: %w", err)
+	}
+	if len(resp.GetDevices()) == 0 {
+		return refuseIfSerialNeedsAck("unknown", observe, ack)
+	}
+	for _, d := range resp.GetDevices() {
+		kind := ""
+		if d.GetIdentity() != nil {
+			kind = d.GetIdentity().GetBackendKind()
+		}
+		if err := refuseIfSerialNeedsAck(kind, observe, ack); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func runDoctor(ctx context.Context, cfgPath, observe string) error {
+	if cfgPath != "" {
+		cfg, err := config.Load(cfgPath)
+		if 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))
+		}
+	}
+	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
+	if err != nil {
+		if cfgPath != "" {
+			fmt.Println("live observe socket: not connected (", err, ")")
+			return nil
+		}
+		return err
+	}
+	defer conn.Close()
+	hc := grpc_health_v1.NewHealthClient(conn)
+	st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
+	if err != nil {
+		return err
+	}
+	fmt.Println("grpc_health", st.Status.String())
+	return nil
+}
+
+func observeClient(path string, d time.Duration) hthv1.ObserveServiceClient {
+	return hthv1.NewObserveServiceClient(mustDial(path, d))
+}
+
+func controlClient(path string, d time.Duration) hthv1.ControlServiceClient {
+	return hthv1.NewControlServiceClient(mustDial(path, d))
+}
+
+func mustDial(path string, d time.Duration) *grpc.ClientConn {
+	c, err := grpcserver.DialUnix(path, d)
+	fatal(err)
+	return c
+}
+
+func printMsg(m proto.Message) {
+	b, err := protojson.MarshalOptions{Multiline: true, UseProtoNames: true}.Marshal(m)
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+	fmt.Println(string(b))
+}
+
+func printAction(res *hthv1.ActionResult) {
+	fmt.Println("accepted", res.Accepted, "confirmation", res.Confirmation.String(), "reject", res.RejectReason.String())
+	fmt.Println("message", res.Message)
+	fmt.Println("replayed_from_cache", res.ReplayedFromCache)
+	printNamed("requested", res.Requested)
+	printNamed("accepted", res.AcceptedAction)
+	printNamed("dispatched", res.Dispatched)
+}
+
+func printNamed(name string, rec *hthv1.ActionRecord) {
+	if rec == nil {
+		fmt.Println(name, "(none)")
+		return
+	}
+	b, _ := protojson.MarshalOptions{UseProtoNames: true}.Marshal(rec)
+	fmt.Println(name, string(b))
+}
+
+func loadBatch(path, deviceID string, clamp bool) *hthv1.ActionBatch {
+	b := &hthv1.ActionBatch{DeviceId: deviceID, CommandId: "hthctl-validate", AllowClamp: clamp, ClientId: "hthctl"}
+	if strings.TrimSpace(path) == "" {
+		fatal(fmt.Errorf("ActionBatch --file is required"))
+	}
+	raw, err := os.ReadFile(path)
+	fatal(err)
+	fatal(protojson.Unmarshal(raw, b))
+	if b.DeviceId == "" {
+		b.DeviceId = deviceID
+	}
+	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)
+		os.Exit(1)
+	}
+}

cmd/hthctl/main_test.go → legacy-hth/cmd/hthctl/main_test.go


cmd/hthd/main.go → legacy-hth/cmd/hthd/main.go


contracts/6400/SHA256SUMS → legacy-hth/contracts/6400/SHA256SUMS


contracts/6400/host-contract.json → legacy-hth/contracts/6400/host-contract.json


contracts/evidence/RTL_REF.txt → legacy-hth/contracts/evidence/RTL_REF.txt


contracts/evidence/SHA256SUMS → legacy-hth/contracts/evidence/SHA256SUMS


contracts/evidence/golden-vectors.json → legacy-hth/contracts/evidence/golden-vectors.json


contracts/evidence/host-contract.json → legacy-hth/contracts/evidence/host-contract.json


deploy/amd64-release/README.md → legacy-hth/deploy/amd64-release/README.md


deploy/amd64-release/README.zh-CN.md → legacy-hth/deploy/amd64-release/README.zh-CN.md


deploy/amd64-release/config/hthd.6400-mock.yaml → legacy-hth/deploy/amd64-release/config/hthd.6400-mock.yaml


deploy/amd64-release/config/hthd.6400-serial.yaml → legacy-hth/deploy/amd64-release/config/hthd.6400-serial.yaml


deploy/amd64-release/install.sh → legacy-hth/deploy/amd64-release/install.sh


deploy/amd64-release/selftest.sh → legacy-hth/deploy/amd64-release/selftest.sh


deploy/amd64-release/uninstall.sh → legacy-hth/deploy/amd64-release/uninstall.sh


deploy/amd64-release/verify-install.sh → legacy-hth/deploy/amd64-release/verify-install.sh


deploy/examples/hthd.6400-mock.yaml → legacy-hth/deploy/examples/hthd.6400-mock.yaml


deploy/examples/hthd.6400-replay.yaml → legacy-hth/deploy/examples/hthd.6400-replay.yaml


deploy/examples/hthd.6400-serial.yaml → legacy-hth/deploy/examples/hthd.6400-serial.yaml


deploy/examples/hthd.mock.yaml → legacy-hth/deploy/examples/hthd.mock.yaml


deploy/examples/hthd.serial.yaml → legacy-hth/deploy/examples/hthd.serial.yaml


deploy/examples/podman-socket-only.sh → legacy-hth/deploy/examples/podman-socket-only.sh


deploy/install.sh → legacy-hth/deploy/install.sh


deploy/systemd/hth.conf → legacy-hth/deploy/systemd/hth.conf


deploy/systemd/hthd.service → legacy-hth/deploy/systemd/hthd.service


deploy/systemd/hthd@.service → legacy-hth/deploy/systemd/hthd@.service


deploy/sysusers.d/hth.conf → legacy-hth/deploy/sysusers.d/hth.conf


deploy/tmpfiles/hth.conf → legacy-hth/deploy/tmpfiles/hth.conf


deploy/udev/99-hth-controller.rules.template → legacy-hth/deploy/udev/99-hth-controller.rules.template


deploy/uninstall.sh → legacy-hth/deploy/uninstall.sh


docs/6400/migration.md → legacy-hth/docs/6400/migration.md


docs/TEST_MATRIX.zh-CN.md → legacy-hth/docs/TEST_MATRIX.zh-CN.md


docs/advanced/README.md → legacy-hth/docs/advanced/README.md


docs/amd64-release.zh-CN.md → legacy-hth/docs/amd64-release.zh-CN.md


docs/api-contract.zh-CN.md → legacy-hth/docs/api-contract.zh-CN.md


docs/architecture.zh-CN.md → legacy-hth/docs/architecture.zh-CN.md


docs/compatibility-policy.zh-CN.md → legacy-hth/docs/compatibility-policy.zh-CN.md


docs/deployment.zh-CN.md → legacy-hth/docs/deployment.zh-CN.md


docs/failure-semantics.zh-CN.md → legacy-hth/docs/failure-semantics.zh-CN.md


docs/known-gaps.zh-CN.md → legacy-hth/docs/known-gaps.zh-CN.md


docs/model-data-integration.zh-CN.md → legacy-hth/docs/model-data-integration.zh-CN.md


docs/operations.zh-CN.md → legacy-hth/docs/operations.zh-CN.md


docs/protocol-source-audit.zh-CN.md → legacy-hth/docs/protocol-source-audit.zh-CN.md


docs/python-sdk-guide.zh-CN.md → legacy-hth/docs/python-sdk-guide.zh-CN.md


docs/safety-contract.zh-CN.md → legacy-hth/docs/safety-contract.zh-CN.md


docs/signal-dictionary.zh-CN.md → legacy-hth/docs/signal-dictionary.zh-CN.md


docs/simple/ALGORITHM_API.md → legacy-hth/docs/simple/ALGORITHM_API.md


docs/simple/README_10_MINUTES.md → legacy-hth/docs/simple/README_10_MINUTES.md


generated/6400/golden-vectors.json → legacy-hth/generated/6400/golden-vectors.json


generated/6400/host-contract.json → legacy-hth/generated/6400/host-contract.json


generated/6400/import-source.json → legacy-hth/generated/6400/import-source.json


+ 18 - 0
legacy-hth/go.mod

@@ -0,0 +1,18 @@
+module hth
+
+go 1.25.0
+
+require (
+	go.uber.org/goleak v1.3.0
+	golang.org/x/sys v0.47.0
+	google.golang.org/grpc v1.82.1
+	google.golang.org/protobuf v1.36.12
+	gopkg.in/yaml.v3 v3.0.1
+)
+
+require (
+	github.com/kr/text v0.2.0 // indirect
+	golang.org/x/net v0.58.0 // indirect
+	golang.org/x/text v0.41.0 // indirect
+	google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
+)

go.sum → legacy-hth/go.sum


internal/app/app.go → legacy-hth/internal/app/app.go


internal/app/backend_linux.go → legacy-hth/internal/app/backend_linux.go


internal/backend/backend.go → legacy-hth/internal/backend/backend.go


internal/backend/backend_test.go → legacy-hth/internal/backend/backend_test.go


internal/backend/classify.go → legacy-hth/internal/backend/classify.go


internal/backend/mock.go → legacy-hth/internal/backend/mock.go


internal/backend/replay.go → legacy-hth/internal/backend/replay.go


internal/backend/replay_fuzz_test.go → legacy-hth/internal/backend/replay_fuzz_test.go


internal/backend/replay_strict_test.go → legacy-hth/internal/backend/replay_strict_test.go


internal/backend/serial_close_linux_test.go → legacy-hth/internal/backend/serial_close_linux_test.go


internal/backend/serial_get_linux_test.go → legacy-hth/internal/backend/serial_get_linux_test.go


internal/backend/serial_linux.go → legacy-hth/internal/backend/serial_linux.go


internal/backend/testdata/fuzz/FuzzReplayOpen/0255ca613fd7c6a1 → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0255ca613fd7c6a1


internal/backend/testdata/fuzz/FuzzReplayOpen/0938b7fa705ec552 → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0938b7fa705ec552


internal/backend/testdata/fuzz/FuzzReplayOpen/0cbd8c395f234c73 → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0cbd8c395f234c73


internal/backend/testdata/fuzz/FuzzReplayOpen/0ce8924336b00a4a → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/0ce8924336b00a4a


internal/backend/testdata/fuzz/FuzzReplayOpen/10668f0c64d180ee → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/10668f0c64d180ee


internal/backend/testdata/fuzz/FuzzReplayOpen/1e4976294bffeaa6 → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/1e4976294bffeaa6


internal/backend/testdata/fuzz/FuzzReplayOpen/247c677b3d2ee7d7 → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/247c677b3d2ee7d7


internal/backend/testdata/fuzz/FuzzReplayOpen/2940cad0e1b165c5 → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/2940cad0e1b165c5


internal/backend/testdata/fuzz/FuzzReplayOpen/2eafed28f42a799b → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/2eafed28f42a799b


internal/backend/testdata/fuzz/FuzzReplayOpen/2fa28f4c3423d42d → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/2fa28f4c3423d42d


internal/backend/testdata/fuzz/FuzzReplayOpen/406a65375d9339a3 → legacy-hth/internal/backend/testdata/fuzz/FuzzReplayOpen/406a65375d9339a3


+ 0 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/446e2c92d43d091a


Некоторые файлы не были показаны из-за большого количества измененных файлов