jim800121chen f8533a6b04 fix(local-tool): sidebar icon + Wails Windows icon.ico + 掃裝置路徑修復
sidebar E icon:
- frontend/src/components/layout/sidebar.tsx 左上角的 "E" 方塊換成 <img> 指向
  /visiona-logo.png,從 frontend/public/visiona-logo.png serve

Wails 桌面/工作列 icon:
- 把 branding/icon.ico 複製到 visiona-local/build/windows/icon.ico
- Wails v2 Windows build 偵測到這個檔案就會直接用它當 exe embedded icon,
  不再從 appicon.png 自動 resize(解析度更好)

掃裝置根因修復:
1. server main.go:新增 resolveBridgeScript() 智慧找 kneron_bridge.py
   - 優先 <exe>/scripts/kneron_bridge.py
   - fallback <exe>/../scripts/... 對應 Windows installer 的 {app}\bin\ + {app}\scripts\ 佈局
   - fallback <exe>/../Resources/scripts/... 對應 macOS app bundle

2. server kneron/detector.go:ResolvePython 重寫
   - 最高優先:VISIONA_PYTHON 環境變數(由 Wails 殼層注入)
   - 加入 visiona-local 新路徑:%APPDATA%\visiona-local\runtime\venv、
     ~/Library/Application Support/visiona-local/runtime/venv、
     ~/.local/share/visiona-local/runtime/venv
   - 保留 edge-ai-platform 舊路徑作為 legacy fallback

3. visiona-local/app.go:spawn server 時 export VISIONA_PYTHON=<pyBin>
   讓 detector 直接用 Wails 殼層已經 resolve 好的 python interpreter,
   不再自己獨立去找造成不一致。

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 04:59:23 +08:00

250 lines
6.4 KiB
Go

package kneron
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"visiona-local/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-local\runtime\venv (Windows installer seeded venv)
// 4. ~/.local/share/visiona-local/runtime/venv (Linux)
// 5. ~/Library/Application Support/visiona-local/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-local)
if home, err := os.UserHomeDir(); err == nil {
candidates = append(candidates,
// Windows: %APPDATA%\visiona-local\runtime\venv
filepath.Join(os.Getenv("APPDATA"), "visiona-local", "runtime", "venv", "Scripts", "python.exe"),
// macOS
filepath.Join(home, "Library", "Application Support", "visiona-local", "runtime", "venv", "bin", "python3"),
// Linux
filepath.Join(home, ".local", "share", "visiona-local", "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
}
// 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
}
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,
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)
}