jim800121chen b9ee184586 feat(device): WP-0 序號串通 + serial 路由(ADR-018 走向 A' 第一階段)
- local-agent/server:detector 保留 kn_number(parseScanDevices 可測化、
  合成 ID 語意不動)+ DeviceInfo.SerialNumber + Manager serialToLocalID
  反查表 + GetDevice 雙查(sessions 先、serial 後,純加法)
- visiona-agent:pairing exchange 帶本地裝置清單(DeviceLister 失敗不中斷
  配對、timeout 2s、omitempty 舊版相容)
- visionA-backend:exchange 收 devices —— R1 取第一顆可用序號、R2 假序號
  0x00000000 寫 NULL、R4 同 owner 同序號復用既有 device_id(防 23505)、
  pg+mem 兩實作對齊
- 五個 proxy 操作(flash/inference/camera/connect/disconnect)收斂於
  GetDevice 單一入口,serial 路由一處涵蓋
- docs:api-spec.md §2 增補 POST /api/pairing/exchange(schema + R1/R2/R4)
- 測試:行為級四環節鏈 + dbtest 130 實跑 6/6 + DBOn 回歸 4/4;
  三 module build/vet/test 全綠
- review:通過 0C/0M/6Mi/5Sug(.autoflow/05-implementation/review/
  wp0-serial-routing-review.md);Minor #1 Rescan stale session 掛 WP-C 前置

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:31:51 +08:00

274 lines
7.5 KiB
Go

package kneron
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"visiona-agent/server/internal/driver"
)
// ResolvePython finds the best Python interpreter for the given script path.
//
// Search order:
// 1. VISIONA_PYTHON env var (highest priority — set by Wails shell when it
// has already provisioned a bundled venv)
// 2. Script-local venv / parent venv
// 3. %APPDATA%\visiona-agent\runtime\venv (Windows installer seeded venv)
// 4. ~/.local/share/visiona-agent/runtime/venv (Linux)
// 5. ~/Library/Application Support/visiona-agent/runtime/venv (macOS)
// 6. Legacy: ~/.edge-ai-platform/venv / %LOCALAPPDATA%\EdgeAIPlatform\venv
// 7. System python3 / python
func ResolvePython(scriptPath string) string {
// 1. Environment variable override (set by Wails shell)
if p := os.Getenv("VISIONA_PYTHON"); p != "" {
if _, err := os.Stat(p); err == nil {
return p
}
}
scriptDir := filepath.Dir(scriptPath)
parentDir := filepath.Dir(scriptDir)
// 2. Script-local / parent venv
var candidates []string
for _, base := range []string{scriptDir, parentDir} {
candidates = append(candidates,
filepath.Join(base, "venv", "bin", "python3"), // Unix
filepath.Join(base, "venv", "Scripts", "python.exe"), // Windows
)
}
// 3-5. Platform-specific data dir (visiona-agent)
if home, err := os.UserHomeDir(); err == nil {
candidates = append(candidates,
// Windows: %APPDATA%\visiona-agent\runtime\venv
filepath.Join(os.Getenv("APPDATA"), "visiona-agent", "runtime", "venv", "Scripts", "python.exe"),
// macOS
filepath.Join(home, "Library", "Application Support", "visiona-agent", "runtime", "venv", "bin", "python3"),
// Linux
filepath.Join(home, ".local", "share", "visiona-agent", "runtime", "venv", "bin", "python3"),
// 6. Legacy edge-ai-platform paths (backwards compat for upgrades)
filepath.Join(home, ".edge-ai-platform", "venv", "bin", "python3"),
filepath.Join(home, ".edge-ai-platform", "venv", "Scripts", "python.exe"),
)
}
// 6b. Legacy %LOCALAPPDATA%\EdgeAIPlatform\venv
if appData := os.Getenv("LOCALAPPDATA"); appData != "" {
candidates = append(candidates,
filepath.Join(appData, "EdgeAIPlatform", "venv", "Scripts", "python.exe"),
)
}
for _, p := range candidates {
if p == "" {
continue
}
if _, err := os.Stat(p); err == nil {
return p
}
}
// 7. Fallback to system python
for _, name := range []string{"python3", "python"} {
if p, err := exec.LookPath(name); err == nil {
return p
}
}
return "python3"
}
// KneronVendorID is the USB vendor ID for Kneron devices.
const KneronVendorID uint16 = 0x3231
// Known Kneron product IDs.
const (
ProductIDKL520 = "0x0100"
ProductIDKL720 = "0x0200"
ProductIDKL720Alt = "0x0720"
)
// chipFromProductID returns the chip name and device type from the product_id
// reported by the Python bridge scan result.
func chipFromProductID(productID string) (chip string, deviceType string) {
pid := strings.ToLower(strings.TrimSpace(productID))
switch pid {
case "0x0100":
return "KL520", "kneron_kl520"
case "0x0200", "0x0720":
return "KL720", "kneron_kl720"
default:
// Unknown product — default to KL520 for USB Boot devices,
// otherwise use the raw product ID as suffix.
return "KL520", "kneron_kl520"
}
}
// DetectDevices attempts to discover all connected Kneron devices (KL520, KL720, etc.)
// by invoking the Python bridge script with a scan command. If Python or
// the bridge script is not available, it returns an empty list.
func DetectDevices(scriptPath string) []driver.DeviceInfo {
// Try to run the bridge script with a scan command via a short-lived process.
pythonBin := ResolvePython(scriptPath)
cmd := exec.Command(pythonBin, scriptPath)
cmd.Stdin = nil
// Ensure libusb-1.0.dll can be found on Windows by adding the binary's
// directory to PATH (the installer places the DLL there).
scriptDir := filepath.Dir(scriptPath)
installDir := filepath.Dir(scriptDir)
cmd.Env = append(os.Environ(),
fmt.Sprintf("PATH=%s;%s;%s", installDir, scriptDir, os.Getenv("PATH")),
)
stdinPipe, err := cmd.StdinPipe()
if err != nil {
return nil
}
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
stdinPipe.Close()
return nil
}
if err := cmd.Start(); err != nil {
return nil
}
defer func() {
stdinPipe.Close()
cmd.Process.Kill()
cmd.Wait()
}()
// Read the ready signal.
decoder := json.NewDecoder(stdoutPipe)
var readyResp map[string]interface{}
done := make(chan error, 1)
go func() {
done <- decoder.Decode(&readyResp)
}()
select {
case err := <-done:
if err != nil {
return nil
}
case <-time.After(5 * time.Second):
return nil
}
if status, ok := readyResp["status"].(string); !ok || status != "ready" {
return nil
}
// Send the scan command.
scanCmd, _ := json.Marshal(map[string]interface{}{"cmd": "scan"})
scanCmd = append(scanCmd, '\n')
if _, err := stdinPipe.Write(scanCmd); err != nil {
return nil
}
// Read the scan response.
var scanResp map[string]interface{}
scanDone := make(chan error, 1)
go func() {
scanDone <- decoder.Decode(&scanResp)
}()
select {
case err := <-scanDone:
if err != nil {
return nil
}
case <-time.After(5 * time.Second):
return nil
}
// Parse detected devices from the response.
devicesRaw, ok := scanResp["devices"].([]interface{})
if !ok || len(devicesRaw) == 0 {
return nil
}
return parseScanDevices(devicesRaw)
}
// parseScanDevices converts the raw `devices` array from the Python bridge
// scan response into driver.DeviceInfo entries.
//
// Extracted from DetectDevices so the parsing logic is unit-testable without
// spawning the Python bridge subprocess.
//
// Serial number (kn_number) handling:
// - The bridge reports kn_number formatted "0x%08X" (SDK scan branch).
// - A missing or non-string kn_number yields an empty SerialNumber; the
// device is still registered (serial is additive metadata — a device must
// never be dropped because its serial could not be read).
// - The synthetic ID ("kl520-0") stays untouched: it remains the local
// sessions routing key (flash/inference depend on it). The serial travels
// in the new SerialNumber field only (ADR-018 serial routing).
func parseScanDevices(devicesRaw []interface{}) []driver.DeviceInfo {
// Track per-chip counters for naming (e.g. "KL520 #1", "KL720 #1").
chipCount := map[string]int{}
var devices []driver.DeviceInfo
for _, devRaw := range devicesRaw {
dev, ok := devRaw.(map[string]interface{})
if !ok {
continue
}
port := ""
if p, ok := dev["port"].(string); ok {
port = p
}
fw := ""
if f, ok := dev["firmware"].(string); ok {
fw = f
}
productID := ""
if p, ok := dev["product_id"].(string); ok {
productID = p
}
serial := ""
if s, ok := dev["kn_number"].(string); ok {
serial = strings.TrimSpace(s)
}
chip, devType := chipFromProductID(productID)
chipCount[chip]++
idx := chipCount[chip]
info := driver.DeviceInfo{
ID: fmt.Sprintf("%s-%d", strings.ToLower(chip), idx-1),
Name: fmt.Sprintf("Kneron %s #%d", chip, idx),
Type: devType,
Port: port,
SerialNumber: serial,
VendorID: KneronVendorID,
Status: driver.StatusDetected,
FirmwareVer: fw,
}
devices = append(devices, info)
}
return devices
}
// DetectKL720Devices is a backward-compatible alias for DetectDevices.
// Deprecated: Use DetectDevices instead.
func DetectKL720Devices(scriptPath string) []driver.DeviceInfo {
return DetectDevices(scriptPath)
}