wangzhibo
2026-09-11 659c470eba542383987aad227b7f918100f131fa
xiaozhi-esp32-server/main/xiaozhi-server/core/websocket_server.py
@@ -35,6 +35,7 @@
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
from core.websocket_handshake import is_websocket_upgrade
TAG = __name__
@@ -67,6 +68,33 @@
        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)
        self.device_handlers = {}
        self.device_handlers_lock = asyncio.Lock()
    async def register_device_handler(self, device_id, handler):
        if not device_id:
            return
        async with self.device_handlers_lock:
            old = self.device_handlers.get(device_id)
            self.device_handlers[device_id] = handler
        if old is not None and old is not handler:
            self.logger.bind(tag=TAG).info(f"关闭同设备旧连接: {device_id}")
            asyncio.create_task(self._close_stale_handler(old))
    async def _close_stale_handler(self, handler):
        try:
            handler.stop_event.set()
            if handler.websocket:
                await handler.websocket.close()
        except Exception as e:
            self.logger.bind(tag=TAG).warning(f"关闭旧连接失败: {e}")
    async def unregister_device_handler(self, device_id, handler):
        if not device_id:
            return
        async with self.device_handlers_lock:
            if self.device_handlers.get(device_id) is handler:
                self.device_handlers.pop(device_id, None)
    async def start(self):
        server_config = self.config["server"]
@@ -144,13 +172,10 @@
                )
    async def _http_response(self, websocket, request_headers):
        # 检查是否为 WebSocket 升级请求
        if request_headers.headers.get("connection", "").lower() == "upgrade":
            # 如果是 WebSocket 请求,返回 None 允许握手继续
        headers = getattr(request_headers, "headers", None) or request_headers
        if is_websocket_upgrade(headers):
            return None
        else:
            # 如果是普通 HTTP 请求,返回 "server is running"
            return websocket.respond(200, "Server is running\n")
        return websocket.respond(200, "Server is running\n")
    async def update_config(self) -> bool:
        """更新服务器配置并重新初始化组件