feat(vision): 新增工位触发端点,放卡即可让设备拍照识别

- trigger_handler.py:新增 POST /mcp/vision/trigger {device_id},
  在活动连接中按 device_id 找到设备,主动调用其拍照工具(动态查找 take_photo),
  经 vision_handler 识别后返回规范手办名;不碰串口、不写卡。
  设备未在线/未识别等业务结果统一返回 HTTP 200,便于机器客户端解析。
- websocket_server.py:给 WebSocketServer 加 active_connections 注册表
  (基于镜像版打的最小补丁),供触发端点按 device_id 反查连接。
- http_server.py / app.py:SimpleHttpServer 接收 ws_server 引用并注册触发路由。
- vision_handler.py:识别返回增加 figurine 规范名字段(带下划线),供触发端点提取。
- docker-compose:挂载新增/改动的服务端文件使其在容器内生效。

配合 zebbingo-ai-agent 的 tools/figurine-capture-station 桌面工位使用。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MOLVMIN 2026-07-20 16:13:51 +08:00
parent 1d66fa6473
commit c6d7786b79
6 changed files with 239 additions and 9 deletions

View file

@ -60,8 +60,8 @@ async def main():
# 启动 WebSocket 服务器
ws_server = WebSocketServer(config)
ws_task = asyncio.create_task(ws_server.start())
# 启动 Simple http 服务器
ota_server = SimpleHttpServer(config)
# 启动 Simple http 服务器(传入 ws_server 以支持工位触发端点按 device_id 找设备连接)
ota_server = SimpleHttpServer(config, ws_server)
ota_task = asyncio.create_task(ota_server.start())
read_config_from_api = config.get("read_config_from_api", False)

View file

@ -0,0 +1,122 @@
# -*- coding: utf-8 -*-
"""
工位触发端点:外部事件(如放NFC卡)→ 让指定设备(Watcher)拍照识别 → 返回规范手办名。
用于"放卡写卡工位"(tools/figurine-capture-station):读卡器检测到卡到位后
POST 本端点,由服务器主动调用设备 MCP 工具 self.camera.take_photo,
经 vision_handler 识别后把规范手办名返回给工位程序,由工位程序写卡。
本端点不碰串口、不写卡(串口由工位程序独占)。
"""
import json
from aiohttp import web
from config.logger import setup_logging
from core.providers.tools.device_mcp.mcp_handler import call_mcp_tool
TAG = __name__
DEFAULT_QUESTION = "这是什么?"
def _find_camera_tool(mcp_client):
"""在设备已注册的工具里找拍照工具(用 sanitized 注册名,has_tool 校验的就是它)。
设备端工具名可能是 self_camera_take_photo 等,动态查找比写死更稳。"""
tools = getattr(mcp_client, "tools", {}) or {}
for cand in ("self_camera_take_photo", "take_photo"):
if cand in tools:
return cand
for name in tools:
low = name.lower()
if "take_photo" in low or "takephoto" in low or "photo" in low or "camera" in low:
return name
return None
class TriggerHandler:
def __init__(self, config: dict, ws_server):
self.config = config
self.ws_server = ws_server # 用于在 active_connections 中按 device_id 找设备连接
self.logger = setup_logging()
def _find_conn(self, device_id: str):
if not self.ws_server:
return None
for handler in list(self.ws_server.active_connections):
if getattr(handler, "device_id", None) == device_id:
return handler
return None
def _json(self, data: dict, status: int = 200):
resp = web.Response(
text=json.dumps(data, ensure_ascii=False, separators=(",", ":")),
content_type="application/json",
status=status,
)
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Access-Control-Allow-Methods"] = "POST, OPTIONS"
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, Device-Id"
return resp
async def handle_options(self, request):
return self._json({"ok": True})
async def handle_post(self, request):
try:
try:
body = await request.json()
except Exception:
body = {}
device_id = (body.get("device_id")
or request.headers.get("Device-Id", "")).strip()
question = body.get("question") or DEFAULT_QUESTION
# 以下都是"正常业务结果",统一返回 HTTP 200 + matched:false,
# 便于机器客户端(工位app)直接读 JSON,而不是把它当成"服务不可达"。
if not device_id:
return self._json({"matched": False, "error": "缺少 device_id"})
conn = self._find_conn(device_id)
if conn is None:
return self._json(
{"matched": False, "error": f"设备未在线或未连接: {device_id}"}
)
if not getattr(conn, "mcp_client", None):
return self._json({"matched": False, "error": "设备MCP未就绪"})
camera_tool = _find_camera_tool(conn.mcp_client)
if not camera_tool:
avail = list(getattr(conn.mcp_client, "tools", {}).keys())
return self._json(
{"matched": False, "error": f"设备无拍照工具;可用工具: {avail}"}
)
self.logger.bind(tag=TAG).info(
f"工位触发拍照识别:device={device_id} tool={camera_tool}"
)
# 主动让设备拍照;vision_handler 会识别并把结果作为工具返回值回传
raw = await call_mcp_tool(
conn, conn.mcp_client, camera_tool, json.dumps({"question": question})
)
# raw 是 vision_handler 的返回 JSON 字符串,如
# {"success":true,"action":"RESPONSE","response":"这是t-rex","figurine":"t-rex"}
figurine = None
response_text = raw
try:
parsed = json.loads(raw) if isinstance(raw, str) else raw
if isinstance(parsed, dict):
figurine = parsed.get("figurine")
response_text = parsed.get("response", raw)
except Exception:
pass
if figurine:
return self._json({"matched": True, "name": figurine, "raw": response_text})
return self._json({"matched": False, "name": None, "raw": response_text})
except Exception as e:
self.logger.bind(tag=TAG).error(f"工位触发端点异常: {e}")
return self._json({"matched": False, "error": str(e)}, status=500)

View file

@ -231,6 +231,9 @@ class VisionHandler(BaseHandler):
"success": True,
"action": Action.RESPONSE.name,
"response": result,
# 识别命中的规范手办名(带下划线,如 julius_caesar);未命中为 None。
# 供工位触发端点(/mcp/vision/trigger)提取规范名用,语音流程忽略此字段。
"figurine": figurine_name,
}
response = web.Response(

View file

@ -3,16 +3,19 @@ from aiohttp import web
from config.logger import setup_logging
from core.api.ota_handler import OTAHandler
from core.api.vision_handler import VisionHandler
from core.api.trigger_handler import TriggerHandler
TAG = __name__
class SimpleHttpServer:
def __init__(self, config: dict):
def __init__(self, config: dict, ws_server=None):
self.config = config
self.logger = setup_logging()
self.ota_handler = OTAHandler(config)
self.vision_handler = VisionHandler(config)
# 工位触发端点需要按 device_id 找设备连接,故需 WebSocketServer 引用
self.trigger_handler = TriggerHandler(config, ws_server)
def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址
@ -57,6 +60,9 @@ class SimpleHttpServer:
web.get("/mcp/vision/explain", self.vision_handler.handle_get),
web.post("/mcp/vision/explain", self.vision_handler.handle_post),
web.options("/mcp/vision/explain", self.vision_handler.handle_post),
# 工位触发端点:放卡后让指定设备拍照识别并返回规范手办名
web.post("/mcp/vision/trigger", self.trigger_handler.handle_post),
web.options("/mcp/vision/trigger", self.trigger_handler.handle_options),
]
)

View file

@ -1,8 +1,38 @@
import asyncio
import logging
import websockets
from config.logger import setup_logging
class SuppressInvalidHandshakeFilter(logging.Filter):
"""过滤掉无效握手错误日志(如HTTPS访问WS端口)"""
def filter(self, record):
msg = record.getMessage()
suppress_keywords = [
"opening handshake failed",
"did not receive a valid HTTP request",
"connection closed while reading HTTP request",
"line without CRLF",
]
return not any(keyword in msg for keyword in suppress_keywords)
def _setup_websockets_logger():
"""配置 websockets 相关的所有 logger,过滤无效握手错误"""
filter_instance = SuppressInvalidHandshakeFilter()
for logger_name in ["websockets", "websockets.server", "websockets.client"]:
logger = logging.getLogger(logger_name)
logger.addFilter(filter_instance)
_setup_websockets_logger()
from core.connection import ConnectionHandler
from config.config_loader import get_config_from_api
from config.config_loader import get_config_from_api_async
from core.auth import AuthManager, AuthenticationError
from core.utils.modules_initialize import initialize_modules
from core.utils.util import check_vad_update, check_asr_update
@ -30,6 +60,14 @@ class WebSocketServer:
self._intent = modules["intent"] if "intent" in modules else None
self._memory = modules["memory"] if "memory" in modules else None
auth_config = self.config["server"].get("auth", {})
self.auth_enable = auth_config.get("enabled", False)
# 设备白名单
self.allowed_devices = set(auth_config.get("allowed_devices", []))
secret_key = self.config["server"]["auth_key"]
expire_seconds = auth_config.get("expire_seconds", None)
self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds)
# 活动连接注册表:供工位触发端点(/mcp/vision/trigger)按 device_id 反查设备连接
self.active_connections = set()
async def start(self):
@ -42,8 +80,41 @@ class WebSocketServer:
):
await asyncio.Future()
async def _handle_connection(self, websocket):
async def _handle_connection(self, websocket: websockets.ServerConnection):
headers = dict(websocket.request.headers)
if headers.get("device-id", None) is None:
# 尝试从 URL 的查询参数中获取 device-id
from urllib.parse import parse_qs, urlparse
# 从 WebSocket 请求中获取路径
request_path = websocket.request.path
if not request_path:
self.logger.bind(tag=TAG).error("无法获取请求路径")
await websocket.close()
return
parsed_url = urlparse(request_path)
query_params = parse_qs(parsed_url.query)
if "device-id" not in query_params:
await websocket.send("端口正常,如需测试连接,请启动digital-human测试")
await websocket.close()
return
else:
websocket.request.headers["device-id"] = query_params["device-id"][0]
if "client-id" in query_params:
websocket.request.headers["client-id"] = query_params["client-id"][0]
if "authorization" in query_params:
websocket.request.headers["authorization"] = query_params[
"authorization"
][0]
"""处理新连接,每次创建独立的ConnectionHandler"""
# 先认证,后建立连接
try:
await self._handle_auth(websocket)
except AuthenticationError:
await websocket.send("认证失败")
await websocket.close()
return
# 创建ConnectionHandler时传入当前server实例
handler = ConnectionHandler(
self.config,
@ -60,7 +131,6 @@ class WebSocketServer:
except Exception as e:
self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}")
finally:
# 确保从活动连接集合中移除
self.active_connections.discard(handler)
# 强制关闭连接(如果还没有关闭的话)
try:
@ -94,8 +164,8 @@ class WebSocketServer:
"""
try:
async with self.config_lock:
# 重新获取配置
new_config = get_config_from_api(self.config)
# 重新获取配置(使用异步版本)
new_config = await get_config_from_api_async(self.config)
if new_config is None:
self.logger.bind(tag=TAG).error("获取新配置失败")
return False
@ -136,3 +206,26 @@ class WebSocketServer:
except Exception as e:
self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}")
return False
async def _handle_auth(self, websocket: websockets.ServerConnection):
# 先认证,后建立连接
if self.auth_enable:
headers = dict(websocket.request.headers)
device_id = headers.get("device-id", None)
client_id = headers.get("client-id", None)
if self.allowed_devices and device_id in self.allowed_devices:
# 如果属于白名单内的设备,不校验token,直接放行
return
else:
# 否则校验token
token = headers.get("authorization", "")
if token.startswith("Bearer "):
token = token[7:] # 移除'Bearer '前缀
else:
raise AuthenticationError("Missing or invalid Authorization header")
# 进行认证
auth_success = self.auth.verify_token(
token, client_id=client_id, username=device_id
)
if not auth_success:
raise AuthenticationError("Invalid token")

View file

@ -31,4 +31,10 @@ services:
# 模型文件挂接,很重要
- ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt
# 手办识别接线补丁:用 fork 里改过的 vision_handler.py 覆盖镜像内的原文件
- ./core/api/vision_handler.py:/opt/xiaozhi-esp32-server/core/api/vision_handler.py
- ./core/api/vision_handler.py:/opt/xiaozhi-esp32-server/core/api/vision_handler.py
# 工位触发端点:放卡后让设备拍照识别(配合 tools/figurine-capture-station)
- ./core/api/trigger_handler.py:/opt/xiaozhi-esp32-server/core/api/trigger_handler.py
- ./core/http_server.py:/opt/xiaozhi-esp32-server/core/http_server.py
- ./app.py:/opt/xiaozhi-esp32-server/app.py
# 给 WebSocketServer 加活动连接注册表(基于镜像版打的最小补丁),供触发端点按device_id反查
- ./core/websocket_server.py:/opt/xiaozhi-esp32-server/core/websocket_server.py