Bladeren bron

document and demonstrate multi-language 6400 abstraction

高宇轩 3 maanden geleden
bovenliggende
commit
fdc05b9a2b

+ 154 - 5
README.zh-CN.md

@@ -1,7 +1,156 @@
-# Prod2U 6400 UART 抽象层(远端构建)
+# Prod2U 6400 抽象层使用说明
 
-该小型工具实现 6400 手动 UART/I2C 的 `SetAll`、`GetSnapshot`、CRC、ACK 解码和寄存器事务编码。
-通道 4 默认向量为:PTC18..23=100,Front3=30,Rear3=10,其余风扇=20。
+本目录是 6400-front-rear 的唯一活动 Host 抽象层,提供 Go、Python、
+Linux Shell 和 POSIX C 的可运行示例。它只生成和解析协议,不自动打开
+串口、不自动访问 I2C、不实现 MCU HAL、自动温控或 PID。
 
-它不实现 PID、自动温控或 MCU HAL;I2C 仅提供寄存器事务编码,不访问 `/dev/i2c-*`。`--dry-run` 只打印 Golden Frame;指定 `--port`
-时才打开 UART。生产使用前必须确认设备、波特率和串口独占权。
+## 1. 固定合同
+
+| 项目 | 值 |
+| --- | --- |
+| Product | 6400-front-rear |
+| Board | FCB V1.1 |
+| UART | 921600 8N1,A5 5A,CRC-16/CCITT-FALSE |
+| Host-I2C | 7-bit 0x2A,16-bit 寄存器地址,MSB first |
+| I2C 模式 | 100 kHz / 400 kHz,Repeated START,Sequential Read/Write |
+| SET_ALL | 32 bytes:PTC0..23、Front0..3、Rear0..3 |
+| 值域 | 每个 duty 为 0..100 |
+| Watchdog | 只有成功原子 SET_ALL 才加载 30 秒 |
+| SAFE | PTC=0%,Front=20%,Rear=20% |
+| 风扇语义 | 连接器侧高电平请求占空比;Front 反相一次,Rear 直通 |
+
+通道 4 示例:PTC18..23=100、Front3=30、Rear3=10,其余 PTC=0、
+其余风扇=20。
+
+合同文件:
+
+    manual-uart-contract.json
+    host-i2c-register-map.json
+
+Contract SHA-256:
+
+    3d1db034f6b60bc3d747e882defe60b168d37eb356449d46933da824c1c0214a
+
+## 2. Go API
+
+工具链要求 Go 1.25,先运行:
+
+    go test ./...
+
+公共包导出:
+
+    import "prod2u6400-uartkit/pkg/hth6400"
+    SetAllFrame(SetAll) ([]byte, error)
+    GetSnapshotFrame() []byte
+    DecodeAckNack([]byte) (Ack, error)
+    DecodeSnapshot([]byte) ([]byte, error)
+    SetAllI2C(SetAll) ([]I2CTransaction, error)
+    GetSnapshotI2C() I2CTransaction
+    SnapshotReadI2C(length uint16, chunk int) ([]I2CTransaction, error)
+
+传输抽象名称:
+
+    UARTTransport
+    I2CRegisterTransport
+    MockTransport
+    ReplayTransport
+
+运行 Go Demo:
+
+    go run ./examples/go
+
+Demo 打印 UART HEX、I2C staging/command 字节序列、ACK 解码结果,
+并执行 MockTransport,不接触真实设备。
+
+## 3. Python API
+
+Python 实现只依赖标准库:
+
+    python3 python/test_hth6400.py
+    python3 examples/python/demo.py
+
+核心函数:
+
+    from hth6400 import (
+        SetAll, set_all_uart, set_all_i2c,
+        get_snapshot_i2c, snapshot_reads,
+        decode_frame, decode_ack_nack, decode_snapshot,
+    )
+
+set_all_i2c() 返回两个事务:
+
+1. 0x2A W: 01 00 + 32 bytes,写入 0x0100..0x011F;
+2. 0x2A W: 00 10 01,写入 COMMAND=SET_ALL。
+
+get_snapshot_i2c() 生成 00 10 02。读取 Snapshot 时先读
+0x0007/0x0008 长度,再用 snapshot_reads(length, chunk) 生成
+多个 0x0200 + offset 读取事务。
+
+## 4. Linux Shell / UART
+
+只打印 HEX:
+
+    /home/cxkj/bin/prod2u6400-uart --preset channel4 --dry-run
+    /home/cxkj/bin/prod2u6400-uart --preset safe --dry-run
+
+发送并以 HEX 接收(最多 5 秒):
+
+    DEV=/dev/ttyUSB2
+    HEX='A5 5A 01 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 14 14 14 14 14 14 14 E7 0A'
+    /home/cxkj/prod2u/deployments/hth-platform-6400/current/send_uart_hex_debug.sh "$DEV" "$HEX"
+
+标准脚本路径:
+
+    /home/cxkj/prod2u/deployments/hth-platform-6400/current/send_uart_hex_debug.sh
+
+脚本会设置 921600 8N1、raw、关闭软件流控,发送二进制帧并用
+xxd 输出接收字节。它不会循环重试或启动 daemon。
+
+## 5. POSIX C Demo
+
+examples/c/uart_set_all.c 是无第三方库的 Linux 串口示例:
+
+    cc -std=c11 -Wall -Wextra -O2 examples/c/uart_set_all.c -o /tmp/6400-uart-c
+    /tmp/6400-uart-c
+    /tmp/6400-uart-c /dev/ttyUSB2
+
+不提供设备参数时只打印 channel4 帧;只有显式指定设备时才发送。
+
+## 6. ACK/NACK 和 Snapshot
+
+ACK/NACK payload 顺序:
+
+    ok, request_type, status, detail
+
+状态码:
+
+    0 OK
+    1 UNSUPPORTED
+    2 BAD_LENGTH
+    3 BAD_VALUE
+    4 SAFETY_LOCKED
+    5 BUSY
+
+I2C 总线 ACK 只代表字节被接收,不能代表 SET_ALL 已原子生效。
+应用结果必须读取 RESPONSE_OK/COMMAND/STATUS/DETAIL。
+
+## 7. 设备和发布边界
+
+- 不生成 STM32/GD32 工程或 MCU HAL。
+- 不自动访问 /dev/i2c-*。
+- GUI 是离线 HEX/事务生成器,不自动连接 COM 或 I2C。
+- 真实硬件、JTAG、COM、风扇转速、气流和热性能需单独验证。
+- legacy-hth/ 仅为历史归档,不属于活动 API 或发布包。
+
+## 8. 目录说明
+
+    pkg/hth6400/              Go 公共 API
+    internal/protocol/        UART CRC/Frame codec
+    internal/i2creg/          16-bit I2C 寄存器 codec
+    internal/transport/       UART/Mock/Replay 抽象
+    python/hth6400.py         Python codec
+    examples/go/              Go Demo
+    examples/python/          Python Demo
+    examples/bash/            Shell Demo
+    examples/c/               POSIX C Demo
+    send_uart_hex_debug.sh    有界 UART HEX 收发脚本

+ 12 - 0
examples/bash/channel4.sh

@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+echo "1) Offline frame generation"
+/home/cxkj/bin/prod2u6400-uart --preset channel4 --dry-run
+
+echo "2) Explicit UART HEX send/receive"
+DEV=/dev/ttyUSB2
+HEX='A5 5A 01 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 14 14 14 14 14 14 14 E7 0A'
+if [ "$#" -ge 1 ]; then DEV="$1"; fi
+if [ "$#" -ge 2 ]; then HEX="$2"; fi
+/home/cxkj/prod2u/deployments/hth-platform-6400/current/send_uart_hex_debug.sh "$DEV" "$HEX"

+ 76 - 0
examples/c/uart_set_all.c

@@ -0,0 +1,76 @@
+#define _DEFAULT_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/select.h>
+#include <termios.h>
+#include <unistd.h>
+
+static uint16_t crc16(const uint8_t *data, size_t length) {
+    uint16_t crc = 0xFFFF;
+    for (size_t i = 0; i < length; ++i) {
+        crc ^= (uint16_t)data[i] << 8;
+        for (int bit = 0; bit < 8; ++bit)
+            crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);
+    }
+    return crc;
+}
+
+static size_t make_channel4(uint8_t *out, size_t capacity) {
+    if (capacity < 38) return 0;
+    uint8_t payload[32] = {0};
+    for (int i = 18; i < 24; ++i) payload[i] = 100;
+    for (int i = 24; i < 32; ++i) payload[i] = 20;
+    payload[27] = 30;
+    payload[31] = 10;
+    out[0] = 0xA5; out[1] = 0x5A; out[2] = 0x01; out[3] = 0x20;
+    memcpy(out + 4, payload, sizeof(payload));
+    uint16_t crc = crc16(out + 2, 34);
+    out[36] = (uint8_t)(crc & 0xFF);
+    out[37] = (uint8_t)(crc >> 8);
+    return 38;
+}
+
+static void dump_hex(const uint8_t *data, size_t length) {
+    for (size_t i = 0; i < length; ++i) printf("%02X%s", data[i], i + 1 == length ? "\n" : " ");
+}
+
+int main(int argc, char **argv) {
+    uint8_t frame[64];
+    size_t frame_length = make_channel4(frame, sizeof(frame));
+    if (frame_length == 0) return 2;
+    if (argc == 1) {
+        printf("TX "); dump_hex(frame, frame_length);
+        return 0;
+    }
+    int fd = open(argv[1], O_RDWR | O_NOCTTY | O_NONBLOCK);
+    if (fd < 0) { perror("open"); return 2; }
+    struct termios tio;
+    if (tcgetattr(fd, &tio) != 0) { perror("tcgetattr"); close(fd); return 2; }
+    cfmakeraw(&tio);
+    cfsetispeed(&tio, B921600);
+    cfsetospeed(&tio, B921600);
+    tio.c_cflag |= CLOCAL | CREAD;
+    tio.c_cflag &= (tcflag_t)~CRTSCTS;
+    if (tcsetattr(fd, TCSANOW, &tio) != 0) { perror("tcsetattr"); close(fd); return 2; }
+    ssize_t sent = 0;
+    while ((size_t)sent < frame_length) {
+        ssize_t n = write(fd, frame + sent, frame_length - (size_t)sent);
+        if (n > 0) sent += n;
+        else if (errno != EAGAIN && errno != EINTR) { perror("write"); close(fd); return 2; }
+    }
+    printf("TX "); dump_hex(frame, frame_length);
+    uint8_t rx[256]; size_t used = 0; fd_set set; struct timeval timeout = {5, 0};
+    FD_ZERO(&set); FD_SET(fd, &set);
+    if (select(fd + 1, &set, NULL, NULL, &timeout) > 0) {
+        ssize_t n = read(fd, rx, sizeof(rx));
+        if (n > 0) { used = (size_t)n; printf("RX "); dump_hex(rx, used); }
+    } else {
+        puts("RX timeout/no complete response");
+    }
+    close(fd);
+    return used ? 0 : 1;
+}

+ 40 - 0
examples/go/main.go

@@ -0,0 +1,40 @@
+package main
+
+import (
+    "context"
+    "encoding/hex"
+    "fmt"
+    "prod2u6400-uartkit/pkg/hth6400"
+)
+
+func main() {
+    value := hth6400.SetAll{}
+    for i := range value.Front { value.Front[i] = 20 }
+    for i := range value.Rear { value.Rear[i] = 20 }
+    for i := 18; i < 24; i++ { value.PTC[i] = 100 }
+    value.Front[3], value.Rear[3] = 30, 10
+
+    uart, err := hth6400.SetAllFrame(value)
+    if err != nil { panic(err) }
+    fmt.Println("UART_SET_ALL", hex.EncodeToString(uart))
+
+    txns, err := hth6400.SetAllI2C(value)
+    if err != nil { panic(err) }
+    for i, txn := range txns {
+        fmt.Printf("I2C[%d] addr=0x%02X write=%s read=%d repeated=%t\n",
+            i, txn.Address7, hex.EncodeToString(txn.Write), txn.ReadLength, txn.RepeatedStart)
+    }
+
+    ack := hth6400.EncodeFrame(0x06, []byte{1, 0x01, 0, 0})
+    decoded, err := hth6400.DecodeAckNack(ack)
+    if err != nil { panic(err) }
+    fmt.Printf("ACK ok=%t request=0x%02X status=%d detail=%d\n",
+        decoded.OK, decoded.Request, decoded.Status, decoded.Detail)
+
+    mock := &hth6400.MockTransport{}
+    if err := mock.WriteSetAll(context.Background(), value); err != nil { panic(err) }
+    snapshot, err := mock.GetSnapshot(context.Background())
+    if err != nil { panic(err) }
+    _, writes := mock.Last()
+    fmt.Printf("MOCK snapshot_bytes=%d writes=%d\n", len(snapshot), writes)
+}

+ 25 - 0
examples/python/demo.py

@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+from pathlib import Path
+import sys
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python"))
+from hth6400 import (
+    SetAll, set_all_uart, set_all_i2c, get_snapshot_i2c,
+    snapshot_reads, uart_frame, decode_ack_nack,
+)
+
+value = SetAll(
+    ptc=(0,) * 18 + (100,) * 6,
+    front=(20, 20, 20, 30),
+    rear=(20, 20, 20, 10),
+)
+print("UART_SET_ALL", set_all_uart(value).hex().upper())
+for index, (address, write, read_length) in enumerate(set_all_i2c(value)):
+    print("I2C[%d] address=0x%02X write=%s read=%d" %
+          (index, address, write.hex().upper(), read_length))
+address, write, read_length = get_snapshot_i2c()
+print("I2C_GET address=0x%02X write=%s read=%d" %
+      (address, write.hex().upper(), read_length))
+print("I2C_SNAPSHOT_READS", [(tx[1].hex().upper(), tx[2]) for tx in snapshot_reads(199, 64)])
+ack = uart_frame(0x06, bytes((1, 0x01, 0, 0)))
+print("ACK", decode_ack_nack(ack))

+ 10 - 0
pkg/hth6400/hth6400.go

@@ -21,6 +21,16 @@ type I2CRegisterTransport interface {
 type MockTransport = transport.MockTransport
 type ReplayTransport = transport.ReplayTransport
 
+// EncodeFrame is the shared A5 5A + CRC codec for response/replay fixtures.
+func EncodeFrame(frameType byte, payload []byte) []byte {
+	return protocol.Encode(frameType, payload)
+}
+
+// DecodeFrame validates framing and CRC without assigning application meaning.
+func DecodeFrame(raw []byte) (Frame, error) {
+	return protocol.Decode(raw)
+}
+
 func SetAllFrame(s SetAll) ([]byte, error) { return protocol.EncodeSetAll(s) }
 func GetSnapshotFrame() []byte             { return protocol.EncodeGetSnapshot() }
 func DecodeAckNack(raw []byte) (Ack, error) {

+ 8 - 0
pkg/hth6400/hth6400_test.go

@@ -31,3 +31,11 @@ func TestPublicTransportNames(t *testing.T) {
 	var _ I2CRegisterTransport = (*MockTransport)(nil)
 	var _ I2CRegisterTransport = (*ReplayTransport)(nil)
 }
+
+func TestPublicFrameCodec(t *testing.T) {
+	raw := EncodeFrame(0x06, []byte{1, 0x01, 0, 0})
+	ack, err := DecodeAckNack(raw)
+	if err != nil || !ack.OK || ack.Request != 0x01 || ack.Status != 0 || ack.Detail != 0 {
+		t.Fatalf("unexpected ACK: %+v %v", ack, err)
+	}
+}

+ 38 - 0
python/hth6400.py

@@ -4,6 +4,19 @@ SLAVE_ADDRESS = 0x2A
 REG_COMMAND = 0x0010
 REG_STAGING_BASE = 0x0100
 REG_SNAPSHOT_BASE = 0x0200
+REG_DEVICE_STATUS = 0x0000
+REG_RESPONSE_OK = 0x0001
+REG_RESPONSE_COMMAND = 0x0002
+REG_RESPONSE_STATUS = 0x0003
+REG_RESPONSE_DETAIL = 0x0004
+REG_WATCHDOG_REMAINING_SECONDS = 0x0005
+REG_SET_ALL_BYTES_WRITTEN = 0x0006
+REG_SNAPSHOT_LENGTH_L = 0x0007
+REG_SNAPSHOT_LENGTH_H = 0x0008
+ACK_STATUS = {
+    0: 'OK', 1: 'UNSUPPORTED', 2: 'BAD_LENGTH',
+    3: 'BAD_VALUE', 4: 'SAFETY_LOCKED', 5: 'BUSY',
+}
 
 def crc16(data: bytes) -> int:
     value = 0xFFFF
@@ -17,6 +30,31 @@ def uart_frame(frame_type: int, payload: bytes = b'') -> bytes:
     body = bytes((frame_type, len(payload))) + payload
     return b'\xA5\x5A' + body + crc16(body).to_bytes(2, 'little')
 
+def decode_frame(raw: bytes) -> tuple[int, bytes]:
+    if len(raw) < 6 or raw[:2] != b'\xA5\x5A':
+        raise ValueError('bad A5 5A header or short frame')
+    if len(raw) != raw[3] + 6:
+        raise ValueError('UART frame length mismatch')
+    if int.from_bytes(raw[-2:], 'little') != crc16(raw[2:-2]):
+        raise ValueError('CRC-16/CCITT-FALSE mismatch')
+    return raw[2], raw[4:-2]
+
+def decode_ack_nack(raw: bytes) -> dict[str, int | bool | str]:
+    kind, payload = decode_frame(raw)
+    if kind != 0x06 or len(payload) != 4:
+        raise ValueError('ACK/NACK requires type 0x06 and four payload bytes')
+    ok, request, status, detail = payload
+    return {'ok': bool(ok), 'request': request, 'status': status,
+            'status_name': ACK_STATUS.get(status, 'UNKNOWN'), 'detail': detail}
+
+def decode_snapshot(raw: bytes, expected_length: int | None = None) -> bytes:
+    kind, payload = decode_frame(raw)
+    if kind != 0x82:
+        raise ValueError('SNAPSHOT_DATA requires type 0x82')
+    if expected_length is not None and len(payload) != expected_length:
+        raise ValueError('SNAPSHOT_DATA length mismatch')
+    return payload
+
 @dataclass(frozen=True)
 class SetAll:
     ptc: tuple[int, ...]

+ 11 - 1
python/test_hth6400.py

@@ -1,7 +1,17 @@
-from hth6400 import SetAll, set_all_uart, set_all_i2c, snapshot_reads
+from hth6400 import (
+    SetAll, set_all_uart, set_all_i2c, snapshot_reads,
+    uart_frame, decode_frame, decode_ack_nack, decode_snapshot,
+)
 
 v = SetAll((0,) * 18 + (100,) * 6, (20, 20, 20, 30), (20, 20, 20, 10))
 assert set_all_uart(v).hex().upper() == 'A55A01200000000000000000000000000000000000006464646464641414141E1414140A4205'
 assert len(set_all_i2c(v)) == 2
 assert [x[2] for x in snapshot_reads(201)] == [64, 64, 64, 9]
+ack = uart_frame(0x06, bytes((1, 0x01, 0, 0)))
+assert decode_frame(ack)[0] == 0x06
+assert decode_ack_nack(ack) == {
+    'ok': True, 'request': 1, 'status': 0, 'status_name': 'OK', 'detail': 0,
+}
+snapshot = uart_frame(0x82, bytes(range(16)))
+assert decode_snapshot(snapshot, 16) == bytes(range(16))
 print('PY6400_PASS')