mirror of
https://gitcode.com/JianFeeeee/HomeAgent.git
synced 2026-09-21 17:38:10 +00:00
feat: 设备桥共享库 + CLI全能力补齐 + GUI omniparse/computeruse 重构
- 抽取设备桥 WS 协议层为共享库 (internal/devicebridge/client/)
- CLI 补齐 11 项 caps 能力(screensee/screensue/speakeruse/camerasue/...)
- GUI 新增 omniparse 能力(Windows UIA 窗口解析)
- GUI computeruse 改用 koffi 直接调用 user32.dll,不再依赖 PowerShell C# 编译
- GUI computeruse JSON 解析兼容非标准格式 {x:500,y:300}
- 新增 mock-server 用于本地测试设备桥协议
- 新增 GUI DLL 桥接模块 (devicebridge_dll.js)
This commit is contained in:
101
internal/devicebridge/client/binary.go
Normal file
101
internal/devicebridge/client/binary.go
Normal file
@ -0,0 +1,101 @@
|
||||
package client
|
||||
|
||||
// BinaryChunker 提供二进制数据分块传输功能。
|
||||
// 用于将大体积数据(如录像 mp4、大图片)按分块协议发送。
|
||||
// 协议:
|
||||
// cmd_data_start {op, req_id, kind, total, chunk_size, mime} —— 文本帧
|
||||
// <N 个二进制帧 0x2> —— data bytes
|
||||
// cmd_data_end {op, req_id, status:ok|error, error?} —— 文本帧
|
||||
|
||||
const (
|
||||
// DefaultChunkSize 默认分块大小(8KB)
|
||||
DefaultChunkSize = 8192
|
||||
|
||||
// MaxBinaryFrameSize 二进制帧最大大小(8MB)
|
||||
MaxBinaryFrameSize = 8 << 20
|
||||
)
|
||||
|
||||
// ChunkCallback 分块发送回调,用于逐块处理。
|
||||
type ChunkCallback func(chunk []byte) error
|
||||
|
||||
// ChunkData 将数据按指定大小分块。
|
||||
func ChunkData(data []byte, chunkSize int) [][]byte {
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = DefaultChunkSize
|
||||
}
|
||||
total := len(data)
|
||||
var chunks [][]byte
|
||||
for off := 0; off < total; off += chunkSize {
|
||||
end := off + chunkSize
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
chunks = append(chunks, data[off:end])
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
// SendChunked 使用回调逐块发送数据。
|
||||
func SendChunked(data []byte, chunkSize int, fn ChunkCallback) error {
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = DefaultChunkSize
|
||||
}
|
||||
chunks := ChunkData(data, chunkSize)
|
||||
for _, chunk := range chunks {
|
||||
if err := fn(chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ===== 数据聚合(接收端) =====
|
||||
|
||||
// DataAccumulator 聚合从设备接收的二进制分块数据。
|
||||
type DataAccumulator struct {
|
||||
ReqID string
|
||||
Kind string
|
||||
MIME string
|
||||
Total int
|
||||
Got int
|
||||
Chunks [][]byte
|
||||
}
|
||||
|
||||
// NewDataAccumulator 创建数据聚合器。
|
||||
func NewDataAccumulator(reqID, kind, mime string, total int) *DataAccumulator {
|
||||
return &DataAccumulator{
|
||||
ReqID: reqID,
|
||||
Kind: kind,
|
||||
MIME: mime,
|
||||
Total: total,
|
||||
Chunks: make([][]byte, 0),
|
||||
}
|
||||
}
|
||||
|
||||
// Append 追加一块数据。
|
||||
func (da *DataAccumulator) Append(chunk []byte) {
|
||||
da.Chunks = append(da.Chunks, chunk)
|
||||
da.Got += len(chunk)
|
||||
}
|
||||
|
||||
// Assemble 聚合所有分块为完整数据。
|
||||
func (da *DataAccumulator) Assemble() []byte {
|
||||
total := 0
|
||||
for _, c := range da.Chunks {
|
||||
total += len(c)
|
||||
}
|
||||
data := make([]byte, 0, total)
|
||||
for _, c := range da.Chunks {
|
||||
data = append(data, c...)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// ExceededLimit 检查是否超出限制(声明的 2 倍或硬上限 64MB)。
|
||||
func (da *DataAccumulator) ExceededLimit() bool {
|
||||
limit := da.Total*2 + 1024
|
||||
if limit < 64<<20 {
|
||||
limit = 64 << 20
|
||||
}
|
||||
return da.Got > limit
|
||||
}
|
||||
483
internal/devicebridge/client/bridge.go
Normal file
483
internal/devicebridge/client/bridge.go
Normal file
@ -0,0 +1,483 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CmdHandler 是命令处理回调类型。
|
||||
// 当收到 remotedevice 下发的 cmd 时调用,reqID 用于回执,command 是命令内容。
|
||||
type CmdHandler func(reqID, command string)
|
||||
|
||||
// CmdResult 是命令执行结果回调(用于异步通知 GUI 层)。
|
||||
type CmdResultHandler func(reqID, status, output, errMsg string)
|
||||
|
||||
// DataHandler 是二进制数据接收回调(如 TTS 音频)。
|
||||
type DataHandler func(reqID, kind, mime string, data []byte)
|
||||
|
||||
// Bridge 是设备桥客户端核心结构体。
|
||||
// 管理 WebSocket 连接、消息路由、心跳保活和命令分发。
|
||||
type Bridge struct {
|
||||
mu sync.RWMutex
|
||||
gateway string
|
||||
token string
|
||||
deviceID string
|
||||
name string
|
||||
kind string
|
||||
caps []string
|
||||
info map[string]interface{}
|
||||
|
||||
ws *wsConn
|
||||
stopCh chan struct{}
|
||||
doneCh chan struct{}
|
||||
started bool
|
||||
|
||||
// 回调
|
||||
cmdHandler CmdHandler
|
||||
resultHandler CmdResultHandler
|
||||
dataHandler DataHandler
|
||||
|
||||
// 二进制数据聚合(服务端→设备,如 TTS 音频)
|
||||
speechAccum *speechBuffer
|
||||
|
||||
// 心跳间隔
|
||||
pingInterval time.Duration
|
||||
}
|
||||
|
||||
// speechBuffer 聚合服务端分块推送的二进制数据。
|
||||
type speechBuffer struct {
|
||||
reqID string
|
||||
kind string
|
||||
mime string
|
||||
total int
|
||||
data []byte
|
||||
}
|
||||
|
||||
// New 创建设备桥客户端。
|
||||
// gateway: ws://host:port(可选 /api/v1/device/ws 路径)
|
||||
// token: 接入令牌
|
||||
// deviceID: 设备唯一标识
|
||||
// name: 设备显示名称
|
||||
// caps: 能力列表(如 ["status","cmdrun","screensee","computeruse"])
|
||||
// info: 额外设备信息(hostname, platform, arch 等),可为 nil
|
||||
func New(gateway, token, deviceID, name string, caps []string, info map[string]interface{}) *Bridge {
|
||||
if info == nil {
|
||||
info = make(map[string]interface{})
|
||||
}
|
||||
// 填充默认信息
|
||||
if _, ok := info["hostname"]; !ok {
|
||||
hostname, _ := os.Hostname()
|
||||
info["hostname"] = hostname
|
||||
}
|
||||
if _, ok := info["platform"]; !ok {
|
||||
info["platform"] = runtime.GOOS
|
||||
}
|
||||
if _, ok := info["arch"]; !ok {
|
||||
info["arch"] = runtime.GOARCH
|
||||
}
|
||||
if _, ok := info["cpus"]; !ok {
|
||||
info["cpus"] = runtime.NumCPU()
|
||||
}
|
||||
|
||||
return &Bridge{
|
||||
gateway: gateway,
|
||||
token: token,
|
||||
deviceID: deviceID,
|
||||
name: name,
|
||||
kind: "computer",
|
||||
caps: caps,
|
||||
info: info,
|
||||
stopCh: make(chan struct{}),
|
||||
doneCh: make(chan struct{}),
|
||||
pingInterval: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// OnCmd 注册命令处理器。当收到 remotedevice 下发的 cmd 时调用。
|
||||
func (b *Bridge) OnCmd(handler CmdHandler) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.cmdHandler = handler
|
||||
}
|
||||
|
||||
// OnResult 注册命令结果回调(用于异步通知)。
|
||||
func (b *Bridge) OnResult(handler CmdResultHandler) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.resultHandler = handler
|
||||
}
|
||||
|
||||
// OnData 注册二进制数据接收回调(如 TTS 音频)。
|
||||
func (b *Bridge) OnData(handler DataHandler) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.dataHandler = handler
|
||||
}
|
||||
|
||||
// SetPingInterval 设置心跳间隔(默认 30 秒)。
|
||||
func (b *Bridge) SetPingInterval(d time.Duration) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.pingInterval = d
|
||||
}
|
||||
|
||||
// Start 启动设备桥连接。
|
||||
// 会阻塞直到连接建立或超时失败。
|
||||
func (b *Bridge) Start() error {
|
||||
b.mu.Lock()
|
||||
if b.started {
|
||||
b.mu.Unlock()
|
||||
return fmt.Errorf("devicebridge: already started")
|
||||
}
|
||||
b.started = true
|
||||
b.mu.Unlock()
|
||||
|
||||
ws, err := dialWS(b.gateway, b.token, 10*time.Second)
|
||||
if err != nil {
|
||||
b.mu.Lock()
|
||||
b.started = false
|
||||
b.mu.Unlock()
|
||||
return fmt.Errorf("devicebridge: dial: %w", err)
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
b.ws = ws
|
||||
b.mu.Unlock()
|
||||
|
||||
// 发送 hello
|
||||
b.sendJSON(map[string]interface{}{
|
||||
"op": "hello",
|
||||
"device": map[string]interface{}{
|
||||
"device_id": b.deviceID,
|
||||
"name": b.name,
|
||||
"kind": b.kind,
|
||||
"caps": b.caps,
|
||||
"info": b.info,
|
||||
},
|
||||
})
|
||||
|
||||
// 发送 bind
|
||||
b.sendJSON(map[string]interface{}{
|
||||
"op": "bind",
|
||||
"device_id": b.deviceID,
|
||||
"token": b.token,
|
||||
})
|
||||
|
||||
go b.readLoop()
|
||||
go b.pingLoop()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop 停止设备桥连接。
|
||||
func (b *Bridge) Stop() {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if !b.started {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-b.stopCh:
|
||||
return
|
||||
default:
|
||||
close(b.stopCh)
|
||||
}
|
||||
if b.ws != nil {
|
||||
_ = b.ws.close()
|
||||
b.ws = nil
|
||||
}
|
||||
}
|
||||
|
||||
// Wait 等待设备桥连接关闭。
|
||||
func (b *Bridge) Wait() {
|
||||
<-b.doneCh
|
||||
}
|
||||
|
||||
// DeviceID 返回设备 ID。
|
||||
func (b *Bridge) DeviceID() string {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
return b.deviceID
|
||||
}
|
||||
|
||||
// Connected 返回是否已连接。
|
||||
func (b *Bridge) Connected() bool {
|
||||
b.mu.RLock()
|
||||
defer b.mu.RUnlock()
|
||||
return b.ws != nil && !b.ws.closed
|
||||
}
|
||||
|
||||
// ===== 发送消息 =====
|
||||
|
||||
// SendResult 发送命令执行结果。
|
||||
func (b *Bridge) SendResult(reqID, status, output, errMsg string) {
|
||||
msg := map[string]interface{}{
|
||||
"op": "cmd_result",
|
||||
"req_id": reqID,
|
||||
"status": status,
|
||||
"device_id": b.deviceID,
|
||||
}
|
||||
if output != "" {
|
||||
msg["output"] = output
|
||||
}
|
||||
if errMsg != "" {
|
||||
msg["error"] = errMsg
|
||||
}
|
||||
b.sendJSON(msg)
|
||||
}
|
||||
|
||||
// SendDataStart 开始二进制数据传输(设备→网关,如录像回传)。
|
||||
func (b *Bridge) SendDataStart(reqID, kind, mime string, total int) {
|
||||
b.sendJSON(map[string]interface{}{
|
||||
"op": "cmd_data_start",
|
||||
"req_id": reqID,
|
||||
"kind": kind,
|
||||
"mime": mime,
|
||||
"total": total,
|
||||
"chunk_size": 8192,
|
||||
})
|
||||
}
|
||||
|
||||
// SendDataChunk 发送一块二进制数据。
|
||||
func (b *Bridge) SendDataChunk(data []byte) error {
|
||||
b.mu.RLock()
|
||||
ws := b.ws
|
||||
b.mu.RUnlock()
|
||||
if ws == nil || ws.closed {
|
||||
return fmt.Errorf("devicebridge: not connected")
|
||||
}
|
||||
return ws.writeBinary(data)
|
||||
}
|
||||
|
||||
// SendDataEnd 结束二进制数据传输。
|
||||
func (b *Bridge) SendDataEnd(reqID, status, errMsg string) {
|
||||
msg := map[string]interface{}{
|
||||
"op": "cmd_data_end",
|
||||
"req_id": reqID,
|
||||
"status": status,
|
||||
}
|
||||
if errMsg != "" {
|
||||
msg["error"] = errMsg
|
||||
}
|
||||
b.sendJSON(msg)
|
||||
}
|
||||
|
||||
// SendDataChunked 便捷方法:自动分块发送完整二进制数据。
|
||||
func (b *Bridge) SendDataChunked(reqID, kind, mime string, data []byte) {
|
||||
total := len(data)
|
||||
b.SendDataStart(reqID, kind, mime, total)
|
||||
const chunkSize = 8192
|
||||
for off := 0; off < total; off += chunkSize {
|
||||
end := off + chunkSize
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
if err := b.SendDataChunk(data[off:end]); err != nil {
|
||||
b.SendDataEnd(reqID, "error", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
b.SendDataEnd(reqID, "ok", "")
|
||||
}
|
||||
|
||||
// SendEvent 发送设备主动上报事件。
|
||||
func (b *Bridge) SendEvent(eventType string, payload interface{}) {
|
||||
b.sendJSON(map[string]interface{}{
|
||||
"op": "event",
|
||||
"device_id": b.deviceID,
|
||||
"type": eventType,
|
||||
"payload": payload,
|
||||
})
|
||||
}
|
||||
|
||||
// SendStatus 发送设备状态更新。
|
||||
func (b *Bridge) SendStatus(status string) {
|
||||
b.sendJSON(map[string]interface{}{
|
||||
"op": "status",
|
||||
"device_id": b.deviceID,
|
||||
"status": status,
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 内部方法 =====
|
||||
|
||||
func (b *Bridge) sendJSON(v interface{}) {
|
||||
b.mu.RLock()
|
||||
ws := b.ws
|
||||
b.mu.RUnlock()
|
||||
if ws == nil || ws.closed {
|
||||
return
|
||||
}
|
||||
payload := mustJSON(v)
|
||||
_ = ws.writeText(payload)
|
||||
}
|
||||
|
||||
func (b *Bridge) readLoop() {
|
||||
defer func() {
|
||||
b.mu.Lock()
|
||||
b.started = false
|
||||
if b.ws != nil {
|
||||
_ = b.ws.close()
|
||||
b.ws = nil
|
||||
}
|
||||
b.mu.Unlock()
|
||||
close(b.doneCh)
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-b.stopCh:
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
// 设置读超时(2 倍 ping 间隔)
|
||||
b.mu.RLock()
|
||||
ws := b.ws
|
||||
interval := b.pingInterval
|
||||
b.mu.RUnlock()
|
||||
if ws == nil {
|
||||
return
|
||||
}
|
||||
|
||||
ws.setDeadline(time.Now().Add(interval * 2))
|
||||
payload, isClose, opcode, err := ws.readFrame()
|
||||
if err != nil {
|
||||
if err == errPing {
|
||||
_ = ws.writePong()
|
||||
continue
|
||||
}
|
||||
// 超时或其他错误,退出
|
||||
return
|
||||
}
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if opcode == 0x2 {
|
||||
// 二进制帧:处于聚合状态时追加
|
||||
b.handleBinaryFrame(payload)
|
||||
continue
|
||||
}
|
||||
|
||||
var msg map[string]interface{}
|
||||
if err := json.Unmarshal(payload, &msg); err != nil {
|
||||
continue
|
||||
}
|
||||
b.handleMessage(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bridge) handleMessage(msg map[string]interface{}) {
|
||||
op, _ := msg["op"].(string)
|
||||
switch op {
|
||||
case "cmd":
|
||||
reqID, _ := msg["req_id"].(string)
|
||||
command, _ := msg["command"].(string)
|
||||
cmdType, _ := msg["cmd_type"].(string)
|
||||
if reqID == "" || command == "" {
|
||||
return
|
||||
}
|
||||
// 记录日志
|
||||
log.Printf("[devicebridge] cmd req=%s type=%s cmd=%s", reqID, cmdType, truncateString(command, 60))
|
||||
|
||||
b.mu.RLock()
|
||||
handler := b.cmdHandler
|
||||
b.mu.RUnlock()
|
||||
if handler != nil {
|
||||
handler(reqID, command)
|
||||
}
|
||||
|
||||
case "hello_ack", "bind_ack":
|
||||
log.Printf("[devicebridge] %s device=%v", op, msg["device"])
|
||||
|
||||
case "cmd_speech_start":
|
||||
reqID, _ := msg["req_id"].(string)
|
||||
kind, _ := msg["kind"].(string)
|
||||
mime, _ := msg["mime"].(string)
|
||||
total := 0
|
||||
if v, ok := msg["total"].(float64); ok {
|
||||
total = int(v)
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.speechAccum = &speechBuffer{
|
||||
reqID: reqID,
|
||||
kind: kind,
|
||||
mime: mime,
|
||||
total: total,
|
||||
}
|
||||
b.mu.Unlock()
|
||||
|
||||
case "cmd_speech_end":
|
||||
reqID, _ := msg["req_id"].(string)
|
||||
b.mu.Lock()
|
||||
acc := b.speechAccum
|
||||
b.speechAccum = nil
|
||||
b.mu.Unlock()
|
||||
if acc == nil || acc.reqID != reqID {
|
||||
return
|
||||
}
|
||||
data := acc.data
|
||||
b.mu.RLock()
|
||||
dh := b.dataHandler
|
||||
b.mu.RUnlock()
|
||||
if dh != nil {
|
||||
dh(reqID, acc.kind, acc.mime, data)
|
||||
}
|
||||
|
||||
default:
|
||||
log.Printf("[devicebridge] unhandled op=%s", op)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bridge) handleBinaryFrame(payload []byte) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if b.speechAccum == nil {
|
||||
return
|
||||
}
|
||||
b.speechAccum.data = append(b.speechAccum.data, payload...)
|
||||
// 防滥用:超出声明 total 的 2 倍或硬上限 64MB 时放弃
|
||||
limit := b.speechAccum.total*2 + 1024
|
||||
if limit < 64<<20 {
|
||||
limit = 64 << 20
|
||||
}
|
||||
if len(b.speechAccum.data) > limit {
|
||||
log.Printf("[devicebridge] speech data exceeded limit, dropped")
|
||||
b.speechAccum = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bridge) pingLoop() {
|
||||
b.mu.RLock()
|
||||
interval := b.pingInterval
|
||||
b.mu.RUnlock()
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-b.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
b.mu.RLock()
|
||||
ws := b.ws
|
||||
b.mu.RUnlock()
|
||||
if ws != nil && !ws.closed {
|
||||
_ = ws.writeFrame(0x9, nil) // ping
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func truncateString(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "..."
|
||||
}
|
||||
120
internal/devicebridge/client/cmdrouter.go
Normal file
120
internal/devicebridge/client/cmdrouter.go
Normal file
@ -0,0 +1,120 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// CmdRouter 命令路由器,支持按命令前缀分发到不同 handler。
|
||||
// 用于 CLI 和 GUI 根据能力类型注册不同的执行函数。
|
||||
type CmdRouter struct {
|
||||
mu sync.RWMutex
|
||||
prefixes map[string]CmdHandler
|
||||
default_ CmdHandler
|
||||
}
|
||||
|
||||
// NewCmdRouter 创建命令路由器。
|
||||
func NewCmdRouter() *CmdRouter {
|
||||
return &CmdRouter{
|
||||
prefixes: make(map[string]CmdHandler),
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 注册匹配指定前缀的命令处理器。
|
||||
// 例如 Handle("homeagent-", homeagentHandler) 会处理所有 homeagent-* 命令。
|
||||
func (r *CmdRouter) Handle(prefix string, handler CmdHandler) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.prefixes[prefix] = handler
|
||||
}
|
||||
|
||||
// HandleDefault 注册默认命令处理器(无前缀匹配时使用)。
|
||||
func (r *CmdRouter) HandleDefault(handler CmdHandler) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.default_ = handler
|
||||
}
|
||||
|
||||
// Dispatch 分发命令到匹配的处理器。
|
||||
// 返回 true 表示已处理,false 表示无匹配。
|
||||
func (r *CmdRouter) Dispatch(reqID, command string) bool {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
// 先按前缀匹配
|
||||
for prefix, handler := range r.prefixes {
|
||||
if strings.HasPrefix(command, prefix) {
|
||||
handler(reqID, command)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// 无前缀匹配,使用默认
|
||||
if r.default_ != nil {
|
||||
r.default_(reqID, command)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ===== 能力解析辅助 =====
|
||||
|
||||
// ParseHomeagentCmd 解析 homeagent-* 命令,返回能力名和参数。
|
||||
// 例如 "homeagent-screensue 5 你好" → ("screensue", "5 你好")
|
||||
// 也支持 "screensue 5 你好"(无前缀)
|
||||
func ParseHomeagentCmd(command string) (capability, args string) {
|
||||
cmd := strings.TrimSpace(command)
|
||||
// 去掉 homeagent- 前缀
|
||||
cmd = strings.TrimPrefix(cmd, "homeagent-")
|
||||
parts := strings.SplitN(cmd, " ", 2)
|
||||
capability = parts[0]
|
||||
if len(parts) > 1 {
|
||||
args = parts[1]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ParseJSONCmd 解析 JSON 格式的命令参数。
|
||||
// 例如 "computeruse {\"x\":100,\"y\":200,\"action\":\"click\"}"
|
||||
// 返回动作名和参数 map。
|
||||
func ParseJSONCmd(command string) (action string, params map[string]interface{}, err error) {
|
||||
cmd := strings.TrimSpace(command)
|
||||
// 去掉 homeagent- 前缀
|
||||
cmd = strings.TrimPrefix(cmd, "homeagent-")
|
||||
|
||||
idx := strings.IndexByte(cmd, '{')
|
||||
if idx < 0 {
|
||||
action = cmd
|
||||
return
|
||||
}
|
||||
action = strings.TrimSpace(cmd[:idx])
|
||||
jsonStr := cmd[idx:]
|
||||
if err = json.Unmarshal([]byte(jsonStr), ¶ms); err != nil {
|
||||
err = fmt.Errorf("parse json params: %w", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// BaseResult 构造基础命令结果。
|
||||
func BaseResult(reqID, status, output, errMsg string) map[string]interface{} {
|
||||
res := map[string]interface{}{
|
||||
"op": "cmd_result",
|
||||
"req_id": reqID,
|
||||
"status": status,
|
||||
}
|
||||
if output != "" {
|
||||
res["output"] = output
|
||||
}
|
||||
if errMsg != "" {
|
||||
res["error"] = errMsg
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// ResultJSON 序列化结果 map 为 JSON。
|
||||
func ResultJSON(res map[string]interface{}) string {
|
||||
b, _ := json.Marshal(res)
|
||||
return string(b)
|
||||
}
|
||||
106
internal/devicebridge/client/protocol.go
Normal file
106
internal/devicebridge/client/protocol.go
Normal file
@ -0,0 +1,106 @@
|
||||
// Package client 提供设备桥客户端共享库,实现与 remotedevice 插件通信的完整协议。
|
||||
// 编译为 C 共享库后,GUI (Electron) 可通过 FFI 调用;CLI (waiter) 可直接导入 Go 包。
|
||||
package client
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// ===== 消息类型(与 remotedevice plugin 协议对齐) =====
|
||||
|
||||
// HelloMsg 设备登记消息
|
||||
type HelloMsg struct {
|
||||
Op string `json:"op"`
|
||||
Device DeviceMeta `json:"device"`
|
||||
}
|
||||
|
||||
// DeviceMeta 设备元信息
|
||||
type DeviceMeta struct {
|
||||
DeviceID string `json:"device_id"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Caps []string `json:"caps"`
|
||||
Info map[string]interface{} `json:"info,omitempty"`
|
||||
}
|
||||
|
||||
// BindMsg 设备绑定消息
|
||||
type BindMsg struct {
|
||||
Op string `json:"op"`
|
||||
DeviceID string `json:"device_id"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// CmdMsg 服务端下发的命令消息
|
||||
type CmdMsg struct {
|
||||
Op string `json:"op"`
|
||||
ReqID string `json:"req_id"`
|
||||
Command string `json:"command"`
|
||||
CmdType string `json:"cmd_type"`
|
||||
}
|
||||
|
||||
// CmdResult 命令执行结果
|
||||
type CmdResult struct {
|
||||
Op string `json:"op"`
|
||||
ReqID string `json:"req_id"`
|
||||
Status string `json:"status"`
|
||||
Output string `json:"output,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
}
|
||||
|
||||
// DataStart 二进制数据传输开始(设备→网关)
|
||||
type DataStart struct {
|
||||
Op string `json:"op"`
|
||||
ReqID string `json:"req_id"`
|
||||
Kind string `json:"kind"`
|
||||
MIME string `json:"mime"`
|
||||
Total int `json:"total"`
|
||||
ChunkSize int `json:"chunk_size,omitempty"`
|
||||
}
|
||||
|
||||
// DataEnd 二进制数据传输结束
|
||||
type DataEnd struct {
|
||||
Op string `json:"op"`
|
||||
ReqID string `json:"req_id"`
|
||||
Status string `json:"status"`
|
||||
Total int `json:"total,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// SpeechStart TTS 音频数据开始(网关→设备)
|
||||
type SpeechStart struct {
|
||||
Op string `json:"op"`
|
||||
ReqID string `json:"req_id"`
|
||||
Kind string `json:"kind"`
|
||||
MIME string `json:"mime"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// SpeechEnd TTS 音频数据结束
|
||||
type SpeechEnd struct {
|
||||
Op string `json:"op"`
|
||||
ReqID string `json:"req_id"`
|
||||
}
|
||||
|
||||
// StatusMsg 设备状态上报
|
||||
type StatusMsg struct {
|
||||
Op string `json:"op"`
|
||||
DeviceID string `json:"device_id"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// EventMsg 设备主动上报事件
|
||||
type EventMsg struct {
|
||||
Op string `json:"op"`
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Payload interface{} `json:"payload,omitempty"`
|
||||
}
|
||||
|
||||
// ===== 序列化辅助 =====
|
||||
|
||||
func mustJSON(v interface{}) []byte {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return []byte("{}")
|
||||
}
|
||||
return b
|
||||
}
|
||||
360
internal/devicebridge/client/transport.go
Normal file
360
internal/devicebridge/client/transport.go
Normal file
@ -0,0 +1,360 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
wsGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
wsVersion = "13"
|
||||
crlf = "\r\n"
|
||||
)
|
||||
|
||||
// wsConn 封装一条 WebSocket 连接(客户端视角,帧带 mask)。
|
||||
type wsConn struct {
|
||||
conn net.Conn
|
||||
br *bufio.Reader
|
||||
bw *bufio.Writer
|
||||
closed bool
|
||||
}
|
||||
|
||||
// dialWS 发起 WS 客户端握手升级。
|
||||
// 支持 ws:// 和 wss://(wss 暂未实现,若需要需加 TLS dial)。
|
||||
func dialWS(rawURL, token string, timeout time.Duration) (*wsConn, error) {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("devicebridge: invalid ws url %q: %w", rawURL, err)
|
||||
}
|
||||
host := u.Host
|
||||
if u.Port() == "" {
|
||||
if u.Scheme == "wss" {
|
||||
host = host + ":443"
|
||||
} else {
|
||||
host = host + ":80"
|
||||
}
|
||||
}
|
||||
path := u.Path
|
||||
if u.RawQuery != "" {
|
||||
path = path + "?" + u.RawQuery
|
||||
}
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
// 默认路径
|
||||
if token != "" && strings.Index(path, "token=") < 0 {
|
||||
if strings.ContainsRune(path, '?') {
|
||||
path = path + "&token=" + urlEscape(token)
|
||||
} else {
|
||||
path = path + "?token=" + urlEscape(token)
|
||||
}
|
||||
}
|
||||
|
||||
dialer := net.Dialer{Timeout: timeout}
|
||||
conn, err := dialer.Dial("tcp", host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("devicebridge: dial %s: %w", host, err)
|
||||
}
|
||||
|
||||
key := wsKey()
|
||||
var sb strings.Builder
|
||||
sb.WriteString("GET " + path + " HTTP/1.1" + crlf)
|
||||
sb.WriteString("Host: " + host + crlf)
|
||||
sb.WriteString("Upgrade: websocket" + crlf)
|
||||
sb.WriteString("Connection: Upgrade" + crlf)
|
||||
sb.WriteString("Sec-WebSocket-Key: " + key + crlf)
|
||||
sb.WriteString("Sec-WebSocket-Version: " + wsVersion + crlf + crlf)
|
||||
if _, err := conn.Write([]byte(sb.String())); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("devicebridge: write upgrade: %w", err)
|
||||
}
|
||||
|
||||
br := bufio.NewReader(conn)
|
||||
var headerBuf strings.Builder
|
||||
for {
|
||||
line, err := br.ReadString('\n')
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("devicebridge: read upgrade resp: %w", err)
|
||||
}
|
||||
headerBuf.WriteString(line)
|
||||
if strings.Contains(headerBuf.String(), crlf+crlf) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !strings.Contains(headerBuf.String(), " 101 ") {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("devicebridge: upgrade failed: %s", firstLine(headerBuf.String()))
|
||||
}
|
||||
|
||||
return &wsConn{conn: conn, br: br, bw: bufio.NewWriter(conn)}, nil
|
||||
}
|
||||
|
||||
// writeText 发送 WS 文本帧(0x1,带 mask)。
|
||||
func (w *wsConn) writeText(payload []byte) error {
|
||||
return w.writeFrame(0x1, payload)
|
||||
}
|
||||
|
||||
// writeBinary 发送 WS 二进制帧(0x2,带 mask)。
|
||||
func (w *wsConn) writeBinary(payload []byte) error {
|
||||
return w.writeFrame(0x2, payload)
|
||||
}
|
||||
|
||||
// writeFrame 发送一个 WS 帧(客户端 mask 模式)。
|
||||
func (w *wsConn) writeFrame(opcode byte, payload []byte) error {
|
||||
if w.closed {
|
||||
return fmt.Errorf("devicebridge: connection closed")
|
||||
}
|
||||
length := len(payload)
|
||||
|
||||
// 帧头
|
||||
hdrLen := 2
|
||||
switch {
|
||||
case length < 126:
|
||||
// 1 byte length
|
||||
case length <= 0xffff:
|
||||
hdrLen += 2
|
||||
default:
|
||||
hdrLen += 8
|
||||
}
|
||||
hdrLen += 4 // mask key
|
||||
|
||||
hdr := make([]byte, hdrLen)
|
||||
hdr[0] = 0x80 | opcode
|
||||
switch {
|
||||
case length < 126:
|
||||
hdr[1] = 0x80 | byte(length)
|
||||
case length <= 0xffff:
|
||||
hdr[1] = 0x80 | 126
|
||||
binary.BigEndian.PutUint16(hdr[2:4], uint16(length))
|
||||
default:
|
||||
hdr[1] = 0x80 | 127
|
||||
binary.BigEndian.PutUint64(hdr[2:10], uint64(length))
|
||||
}
|
||||
|
||||
// mask key
|
||||
var maskKey [4]byte
|
||||
rand.Read(maskKey[:])
|
||||
copy(hdr[hdrLen-4:], maskKey[:])
|
||||
|
||||
// mask payload
|
||||
masked := make([]byte, length)
|
||||
for i := 0; i < length; i++ {
|
||||
masked[i] = payload[i] ^ maskKey[i&3]
|
||||
}
|
||||
|
||||
if _, err := w.bw.Write(hdr); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.bw.Write(masked); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.bw.Flush()
|
||||
}
|
||||
|
||||
// readFrame 读取一个 WS 帧。返回 (payload, isClose, opcode, error)。
|
||||
// 客户端收到的帧不带 mask。
|
||||
func (w *wsConn) readFrame() ([]byte, bool, byte, error) {
|
||||
if w.closed {
|
||||
return nil, true, 0, fmt.Errorf("devicebridge: connection closed")
|
||||
}
|
||||
b0, err := w.br.ReadByte()
|
||||
if err != nil {
|
||||
return nil, true, 0, err
|
||||
}
|
||||
opcode := b0 & 0x0f
|
||||
b1, err := w.br.ReadByte()
|
||||
if err != nil {
|
||||
return nil, true, 0, err
|
||||
}
|
||||
length := uint64(b1 & 0x7f)
|
||||
if length == 126 {
|
||||
var ext [2]byte
|
||||
if _, err := io.ReadFull(w.br, ext[:]); err != nil {
|
||||
return nil, true, opcode, err
|
||||
}
|
||||
length = uint64(binary.BigEndian.Uint16(ext[:]))
|
||||
} else if length == 127 {
|
||||
var ext [8]byte
|
||||
if _, err := io.ReadFull(w.br, ext[:]); err != nil {
|
||||
return nil, true, opcode, err
|
||||
}
|
||||
length = binary.BigEndian.Uint64(ext[:])
|
||||
}
|
||||
// 二进制帧允许更大(8MB),文本帧 1MB
|
||||
maxFrame := uint64(1 << 20)
|
||||
if opcode == 0x2 {
|
||||
maxFrame = 8 << 20
|
||||
}
|
||||
if length > maxFrame {
|
||||
return nil, true, opcode, fmt.Errorf("devicebridge: frame too large (%d bytes)", length)
|
||||
}
|
||||
payload := make([]byte, length)
|
||||
if _, err := io.ReadFull(w.br, payload); err != nil {
|
||||
return nil, true, opcode, err
|
||||
}
|
||||
switch opcode {
|
||||
case 0x1, 0x2:
|
||||
return payload, false, opcode, nil
|
||||
case 0x8:
|
||||
return nil, true, opcode, nil
|
||||
case 0x9: // ping
|
||||
return nil, false, opcode, errPing
|
||||
case 0xa: // pong
|
||||
return nil, false, opcode, nil
|
||||
default:
|
||||
return nil, false, opcode, fmt.Errorf("devicebridge: unsupported opcode %x", opcode)
|
||||
}
|
||||
}
|
||||
|
||||
// writePong 发送 pong 帧。
|
||||
func (w *wsConn) writePong() error {
|
||||
return w.writeFrame(0xa, nil)
|
||||
}
|
||||
|
||||
// close 发送关闭帧并关闭连接。
|
||||
func (w *wsConn) close() error {
|
||||
w.closed = true
|
||||
_ = w.writeFrame(0x8, nil)
|
||||
return w.conn.Close()
|
||||
}
|
||||
|
||||
// ===== 辅助函数 =====
|
||||
|
||||
var errPing = fmt.Errorf("ping")
|
||||
|
||||
func wsKey() string {
|
||||
var b [16]byte
|
||||
rand.Read(b[:])
|
||||
return base64.StdEncoding.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
func urlEscape(s string) string {
|
||||
var sb strings.Builder
|
||||
const hex = "0123456789ABCDEF"
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~' {
|
||||
sb.WriteByte(c)
|
||||
} else {
|
||||
sb.WriteByte('%')
|
||||
sb.WriteByte(hex[c>>4])
|
||||
sb.WriteByte(hex[c&0xf])
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func firstLine(s string) string {
|
||||
if i := strings.IndexByte(s, '\n'); i >= 0 {
|
||||
return strings.TrimSpace(s[:i])
|
||||
}
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func wsAccept(key string) string {
|
||||
h := sha256.Sum256([]byte(key + wsGUID))
|
||||
return base64.StdEncoding.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// readWSFrame 读取一个 WS 帧(从已有的 bufio.Reader,兼容非 wsConn 场景)。
|
||||
func readWSFrame(br *bufio.Reader) ([]byte, bool, byte, error) {
|
||||
b0, err := br.ReadByte()
|
||||
if err != nil {
|
||||
return nil, true, 0, err
|
||||
}
|
||||
opcode := b0 & 0x0f
|
||||
b1, err := br.ReadByte()
|
||||
if err != nil {
|
||||
return nil, true, 0, err
|
||||
}
|
||||
length := uint64(b1 & 0x7f)
|
||||
if length == 126 {
|
||||
var ext [2]byte
|
||||
if _, err := io.ReadFull(br, ext[:]); err != nil {
|
||||
return nil, true, opcode, err
|
||||
}
|
||||
length = uint64(binary.BigEndian.Uint16(ext[:]))
|
||||
} else if length == 127 {
|
||||
var ext [8]byte
|
||||
if _, err := io.ReadFull(br, ext[:]); err != nil {
|
||||
return nil, true, opcode, err
|
||||
}
|
||||
length = binary.BigEndian.Uint64(ext[:])
|
||||
}
|
||||
maxFrame := uint64(1 << 20)
|
||||
if opcode == 0x2 {
|
||||
maxFrame = 8 << 20
|
||||
}
|
||||
if length > maxFrame {
|
||||
return nil, true, opcode, fmt.Errorf("frame too large")
|
||||
}
|
||||
payload := make([]byte, length)
|
||||
if _, err := io.ReadFull(br, payload); err != nil {
|
||||
return nil, true, opcode, err
|
||||
}
|
||||
switch opcode {
|
||||
case 0x1, 0x2:
|
||||
return payload, false, opcode, nil
|
||||
case 0x8:
|
||||
return nil, true, opcode, nil
|
||||
default:
|
||||
return nil, false, opcode, nil
|
||||
}
|
||||
}
|
||||
|
||||
// writeWSFrame 发送一个 WS 帧(非 mask 模式,服务端用)。
|
||||
func writeWSFrame(w io.Writer, opcode byte, payload []byte) error {
|
||||
length := len(payload)
|
||||
hdr := []byte{0x80 | opcode}
|
||||
switch {
|
||||
case length < 126:
|
||||
hdr = append(hdr, byte(length))
|
||||
case length <= 0xffff:
|
||||
hdr = append(hdr, 126, 0, 0)
|
||||
binary.BigEndian.PutUint16(hdr[len(hdr)-2:], uint16(length))
|
||||
default:
|
||||
hdr = append(hdr, 127, 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
binary.BigEndian.PutUint64(hdr[len(hdr)-8:], uint64(length))
|
||||
}
|
||||
if _, err := w.Write(hdr); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(payload); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureTimeout 设置连接读写超时。
|
||||
func (w *wsConn) setDeadline(t time.Time) {
|
||||
if w.conn != nil {
|
||||
w.conn.SetDeadline(t)
|
||||
}
|
||||
}
|
||||
|
||||
// LocalAddr 返回本地地址。
|
||||
func (w *wsConn) LocalAddr() net.Addr {
|
||||
if w.conn != nil {
|
||||
return w.conn.LocalAddr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoteAddr 返回远程地址。
|
||||
func (w *wsConn) RemoteAddr() net.Addr {
|
||||
if w.conn != nil {
|
||||
return w.conn.RemoteAddr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user