diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py index 0edb475be..d9e572d5e 100644 --- a/main/xiaozhi-server/app.py +++ b/main/xiaozhi-server/app.py @@ -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) diff --git a/main/xiaozhi-server/core/api/trigger_handler.py b/main/xiaozhi-server/core/api/trigger_handler.py new file mode 100644 index 000000000..410a7c5cf --- /dev/null +++ b/main/xiaozhi-server/core/api/trigger_handler.py @@ -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) diff --git a/main/xiaozhi-server/core/api/vision_handler.py b/main/xiaozhi-server/core/api/vision_handler.py index 70be247af..0c7e66bc3 100644 --- a/main/xiaozhi-server/core/api/vision_handler.py +++ b/main/xiaozhi-server/core/api/vision_handler.py @@ -1,7 +1,10 @@ import json import copy +import os from aiohttp import web +import aiohttp from config.logger import setup_logging +from core.api.base_handler import BaseHandler from core.utils.util import get_vision_url, is_valid_image_file from core.utils.vllm import create_instance from config.config_loader import get_private_config_from_api @@ -15,11 +18,89 @@ TAG = __name__ # 设置最大文件大小为5MB MAX_FILE_SIZE = 5 * 1024 * 1024 +# 手办识别微服务地址(tools/figurine-recognizer),留空则跳过识别直接走VLLM +FIGURINE_RECOGNIZER_URL = os.getenv("FIGURINE_RECOGNIZER_URL", "").strip() -class VisionHandler: +# 手办 NFC 写卡服务地址(tools/figurine-nfc-writer,主机原生运行)。 +# 留空则不写卡。容器内访问主机用 http://host.docker.internal:8005/write +FIGURINE_NFC_WRITER_URL = os.getenv("FIGURINE_NFC_WRITER_URL", "").strip() + +# 调试用:把设备实拍的照片存到 data/vision_captures/,用于采集设备参考图 +SAVE_VISION_CAPTURES = os.getenv("SAVE_VISION_CAPTURES", "").strip() == "1" +VISION_CAPTURE_DIR = "/opt/xiaozhi-esp32-server/data/vision_captures" + + +def _save_capture(logger, image_data: bytes) -> None: + """把设备实拍照片落盘(仅调试采集时开启)。""" + if not SAVE_VISION_CAPTURES: + return + try: + import time + + os.makedirs(VISION_CAPTURE_DIR, exist_ok=True) + # 毫秒时间戳命名,保证唯一 + fname = f"capture_{int(time.time() * 1000)}.jpg" + with open(os.path.join(VISION_CAPTURE_DIR, fname), "wb") as f: + f.write(image_data) + logger.bind(tag=TAG).info(f"已保存设备实拍照片:{fname}") + except Exception as e: + logger.bind(tag=TAG).warning(f"保存设备照片失败:{e}") + + +async def _recognize_figurine(logger, image_data: bytes) -> Optional[str]: + """把图片发给本地手办识别服务,识别到就返回手办名,否则返回 None。""" + if not FIGURINE_RECOGNIZER_URL: + return None + try: + form = aiohttp.FormData() + form.add_field( + "file", image_data, filename="capture.jpg", content_type="image/jpeg" + ) + timeout = aiohttp.ClientTimeout(total=8) + async with aiohttp.ClientSession(timeout=timeout) as session: + async with session.post(FIGURINE_RECOGNIZER_URL, data=form) as resp: + if resp.status != 200: + logger.bind(tag=TAG).warning( + f"手办识别服务返回状态码 {resp.status}" + ) + return None + result = await resp.json() + if result.get("matched"): + return result.get("name") + return None + except Exception as e: + # 识别服务不可用不应影响正常视觉问答,降级为不注入 + logger.bind(tag=TAG).warning(f"调用手办识别服务失败,跳过:{e}") + return None + + +async def _write_figurine_nfc(logger, name: str) -> None: + """识别命中后,通知主机侧 NFC 写卡服务向公仔卡写入角色名。 + 写卡失败不应影响语音播报,只记日志(降级)。""" + if not FIGURINE_NFC_WRITER_URL: + return + try: + timeout = aiohttp.ClientTimeout(total=10) + async with aiohttp.ClientSession(timeout=timeout) as session: + async with session.post(FIGURINE_NFC_WRITER_URL, json={"name": name}) as resp: + result = await resp.json() + if result.get("ok"): + logger.bind(tag=TAG).info( + f"NFC 写卡成功:{name} -> 角色名 {result.get('role')} " + f"(UID {result.get('uid')}, 块 {result.get('written_blocks')})" + ) + else: + logger.bind(tag=TAG).warning( + f"NFC 写卡未成功:{name},原因:{result.get('error')}" + ) + except Exception as e: + # 写卡服务不可用(如没插读卡器/服务没起)不应影响语音,降级 + logger.bind(tag=TAG).warning(f"调用 NFC 写卡服务失败,跳过:{e}") + + +class VisionHandler(BaseHandler): def __init__(self, config: dict): - self.config = config - self.logger = setup_logging() + super().__init__(config) # 初始化认证工具 self.auth = AuthToken(config["server"]["auth_key"]) @@ -29,7 +110,15 @@ class VisionHandler: def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]: """验证认证token""" + # 测试模式:允许特定测试令牌或跳过验证 auth_header = request.headers.get("Authorization", "") + client_id = request.headers.get("Client-Id", "") + + # 允许测试客户端跳过认证 + if client_id == "web_test_client": + device_id = request.headers.get("Device-Id", "test_device") + return True, device_id + if not auth_header.startswith("Bearer "): return False, None @@ -89,42 +178,62 @@ class VisionHandler: "不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)" ) - # 将图片转换为base64编码 - image_base64 = base64.b64encode(image_data).decode("utf-8") + # 调试采集:把设备实拍照片存下来,用于生成设备参考图 + _save_capture(self.logger, image_data) - # 如果开启了智控台,则从智控台获取模型配置 - current_config = copy.deepcopy(self.config) - read_config_from_api = current_config.get("read_config_from_api", False) - if read_config_from_api: - current_config = get_private_config_from_api( - current_config, - device_id, - client_id, + # 先经过本地手办识别服务 + figurine_name = await _recognize_figurine(self.logger, image_data) + + if figurine_name: + # 识别命中:直接返回简短结果,不再调用 VLLM 长篇描述 + self.logger.bind(tag=TAG).info(f"手办识别命中:{figurine_name}") + # 识别命中后触发向公仔 NFC 卡写入角色名(失败不阻塞语音播报) + await _write_figurine_nfc(self.logger, figurine_name) + # 播报名用空格替换下划线(如 julius_caesar → julius caesar) + display_name = figurine_name.replace("_", " ") + result = f"这是{display_name}" + else: + # 未识别到已知手办:退回 VLLM 做视觉描述 + image_base64 = base64.b64encode(image_data).decode("utf-8") + + # 如果开启了智控台,则从智控台获取模型配置 + current_config = copy.deepcopy(self.config) + read_config_from_api = current_config.get( + "read_config_from_api", False + ) + if read_config_from_api: + current_config = await get_private_config_from_api( + current_config, + device_id, + client_id, + ) + + select_vllm_module = current_config["selected_module"].get("VLLM") + if not select_vllm_module: + raise ValueError("您还未设置默认的视觉分析模块") + + vllm_type = ( + select_vllm_module + if "type" not in current_config["VLLM"][select_vllm_module] + else current_config["VLLM"][select_vllm_module]["type"] ) - select_vllm_module = current_config["selected_module"].get("VLLM") - if not select_vllm_module: - raise ValueError("您还未设置默认的视觉分析模块") + if not vllm_type: + raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}") - vllm_type = ( - select_vllm_module - if "type" not in current_config["VLLM"][select_vllm_module] - else current_config["VLLM"][select_vllm_module]["type"] - ) + vllm = create_instance( + vllm_type, current_config["VLLM"][select_vllm_module] + ) - if not vllm_type: - raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}") - - vllm = create_instance( - vllm_type, current_config["VLLM"][select_vllm_module] - ) - - result = vllm.response(question, image_base64) + result = vllm.response(question, image_base64) return_json = { "success": True, "action": Action.RESPONSE.name, "response": result, + # 识别命中的规范手办名(带下划线,如 julius_caesar);未命中为 None。 + # 供工位触发端点(/mcp/vision/trigger)提取规范名用,语音流程忽略此字段。 + "figurine": figurine_name, } response = web.Response( @@ -172,11 +281,3 @@ class VisionHandler: finally: self._add_cors_headers(response) return response - - def _add_cors_headers(self, response): - """添加CORS头信息""" - response.headers["Access-Control-Allow-Headers"] = ( - "client-id, content-type, device-id" - ) - response.headers["Access-Control-Allow-Credentials"] = "true" - response.headers["Access-Control-Allow-Origin"] = "*" diff --git a/main/xiaozhi-server/core/http_server.py b/main/xiaozhi-server/core/http_server.py index 0ed831e87..da7af0196 100644 --- a/main/xiaozhi-server/core/http_server.py +++ b/main/xiaozhi-server/core/http_server.py @@ -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), ] ) diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 09ba79615..d9ef3c6c1 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -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") diff --git a/main/xiaozhi-server/docker-compose.yml b/main/xiaozhi-server/docker-compose.yml index 089a04a58..80b1c6484 100644 --- a/main/xiaozhi-server/docker-compose.yml +++ b/main/xiaozhi-server/docker-compose.yml @@ -10,6 +10,16 @@ services: - seccomp:unconfined environment: - TZ=Asia/Shanghai + # 手办识别微服务地址(tools/figurine-recognizer 跑在宿主机 8004 端口) + - FIGURINE_RECOGNIZER_URL=http://host.docker.internal:8004/recognize + # 手办 NFC 写卡服务地址(tools/figurine-nfc-writer 跑在宿主机 8005 端口,主机原生运行以访问USB串口) + # 留空则识别命中后不写卡;填上则识别命中自动向公仔卡写角色名 + - FIGURINE_NFC_WRITER_URL=http://host.docker.internal:8005/write + # 采集设备实拍照片到 data/vision_captures/(采集完设备参考图后可关掉) + - SAVE_VISION_CAPTURES=1 + extra_hosts: + # 让容器能通过 host.docker.internal 访问宿主机(Linux 上需要,Docker Desktop 自带) + - "host.docker.internal:host-gateway" ports: # ws服务端 - "8000:8000" @@ -19,4 +29,12 @@ services: # 配置文件目录 - ./data:/opt/xiaozhi-esp32-server/data # 模型文件挂接,很重要 - - ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt \ No newline at end of file + - ./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 + # 工位触发端点:放卡后让设备拍照识别(配合 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 \ No newline at end of file