From e47cb00cd6b4d8ab460e17d2acf1e3651fd2013a Mon Sep 17 00:00:00 2001 From: Chingfeng Li Date: Tue, 26 Aug 2025 14:06:32 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B6=88=E9=99=A4if=EF=BC=8C=E8=A7=A3=E8=80=A6?= =?UTF-8?q?=E6=B6=88=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../xiaozhi-server/core/handle/helloHandle.py | 32 ---- .../core/handle/messageHandlerRegistry.py | 45 +++++ .../core/handle/messageProcessor.py | 41 +++++ .../xiaozhi-server/core/handle/messageType.py | 11 ++ .../core/handle/receiveAudioHandle.py | 2 +- main/xiaozhi-server/core/handle/textHandle.py | 156 +----------------- .../handle/{ => textHandler}/abortHandle.py | 0 .../handle/textHandler/abortMessageHandler.py | 16 ++ .../handle/textHandler/helloMessageHandler.py | 38 +++++ .../handle/textHandler/iotMessageHandler.py | 20 +++ .../textHandler/listenMessageHandler.py | 49 ++++++ .../handle/textHandler/mcpMessageHandler.py | 20 +++ .../core/handle/textHandler/messageHandler.py | 21 +++ .../textHandler/serverMessageHandler.py | 96 +++++++++++ 14 files changed, 366 insertions(+), 181 deletions(-) delete mode 100644 main/xiaozhi-server/core/handle/helloHandle.py create mode 100644 main/xiaozhi-server/core/handle/messageHandlerRegistry.py create mode 100644 main/xiaozhi-server/core/handle/messageProcessor.py create mode 100644 main/xiaozhi-server/core/handle/messageType.py rename main/xiaozhi-server/core/handle/{ => textHandler}/abortHandle.py (100%) create mode 100644 main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py create mode 100644 main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py create mode 100644 main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py create mode 100644 main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py create mode 100644 main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py create mode 100644 main/xiaozhi-server/core/handle/textHandler/messageHandler.py create mode 100644 main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py deleted file mode 100644 index de9587b53..000000000 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ /dev/null @@ -1,32 +0,0 @@ -import json -import asyncio -from core.providers.tools.device_mcp import ( - MCPClient, - send_mcp_initialize_message, - send_mcp_tools_list_request, -) - -TAG = __name__ - - -async def handleHelloMessage(conn, msg_json): - """处理hello消息""" - audio_params = msg_json.get("audio_params") - if audio_params: - format = audio_params.get("format") - conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}") - conn.audio_format = format - conn.welcome_msg["audio_params"] = audio_params - features = msg_json.get("features") - if features: - conn.logger.bind(tag=TAG).info(f"客户端特性: {features}") - conn.features = features - if features.get("mcp"): - conn.logger.bind(tag=TAG).info("客户端支持MCP") - conn.mcp_client = MCPClient() - # 发送初始化 - asyncio.create_task(send_mcp_initialize_message(conn)) - # 发送mcp消息,获取tools列表 - asyncio.create_task(send_mcp_tools_list_request(conn)) - - await conn.websocket.send(json.dumps(conn.welcome_msg)) diff --git a/main/xiaozhi-server/core/handle/messageHandlerRegistry.py b/main/xiaozhi-server/core/handle/messageHandlerRegistry.py new file mode 100644 index 000000000..0ca287aa6 --- /dev/null +++ b/main/xiaozhi-server/core/handle/messageHandlerRegistry.py @@ -0,0 +1,45 @@ +from typing import Dict, Optional + +from core.handle.textHandler.abortMessageHandler import AbortMessageHandler +from core.handle.textHandler.helloMessageHandler import HelloMessageHandler +from core.handle.textHandler.iotMessageHandler import IotMessageHandler +from core.handle.textHandler.listenMessageHandler import ListenMessageHandler +from core.handle.textHandler.mcpMessageHandler import McpMessageHandler +from core.handle.textHandler.messageHandler import MessageHandler +from core.handle.textHandler.serverMessageHandler import ServerMessageHandler + +TAG = __name__ + + +class MessageHandlerRegistry: + """消息处理器注册表""" + + def __init__(self): + self._handlers: Dict[str, MessageHandler] = {} + self._register_default_handlers() + + def _register_default_handlers(self) -> None: + """注册默认的消息处理器""" + handlers = [ + HelloMessageHandler(), + AbortMessageHandler(), + ListenMessageHandler(), + IotMessageHandler(), + McpMessageHandler(), + ServerMessageHandler(), + ] + + for handler in handlers: + self.register_handler(handler) + + def register_handler(self, handler: MessageHandler) -> None: + """注册消息处理器""" + self._handlers[handler.message_type.value] = handler + + def get_handler(self, message_type: str) -> Optional[MessageHandler]: + """获取消息处理器""" + return self._handlers.get(message_type) + + def get_supported_types(self) -> list: + """获取支持的消息类型""" + return list(self._handlers.keys()) diff --git a/main/xiaozhi-server/core/handle/messageProcessor.py b/main/xiaozhi-server/core/handle/messageProcessor.py new file mode 100644 index 000000000..f6496f7d0 --- /dev/null +++ b/main/xiaozhi-server/core/handle/messageProcessor.py @@ -0,0 +1,41 @@ +import json + +from core.handle.messageHandlerRegistry import MessageHandlerRegistry + +TAG = __name__ + + +class MessageProcessor: + """消息处理器主类""" + + def __init__(self, registry: MessageHandlerRegistry): + self.registry = registry + + async def process_message(self, conn, message: str) -> None: + """处理消息的主入口""" + try: + # 解析JSON消息 + msg_json = json.loads(message) + + # 处理纯数字消息 + if isinstance(msg_json, int): + conn.logger.bind(tag=TAG).info(f"收到文本消息:{message}") + await conn.websocket.send(message) + return + + message_type = msg_json.get("type") + + # 记录日志 + conn.logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}") + + # 获取并执行处理器 + handler = self.registry.get_handler(message_type) + if handler: + await handler.handle(conn, msg_json) + else: + conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}") + + except json.JSONDecodeError: + # 非JSON消息直接转发 + conn.logger.bind(tag=TAG).error(f"解析到错误的消息:{message}") + await conn.websocket.send(message) diff --git a/main/xiaozhi-server/core/handle/messageType.py b/main/xiaozhi-server/core/handle/messageType.py new file mode 100644 index 000000000..53ff8b93d --- /dev/null +++ b/main/xiaozhi-server/core/handle/messageType.py @@ -0,0 +1,11 @@ +from enum import Enum + + +class MessageType(Enum): + """消息类型枚举""" + HELLO = "hello" + ABORT = "abort" + LISTEN = "listen" + IOT = "iot" + MCP = "mcp" + SERVER = "server" diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index e5b96be2f..acea85537 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -3,7 +3,7 @@ import json from core.handle.sendAudioHandle import send_stt_message from core.handle.intentHandler import handle_user_intent from core.utils.output_counter import check_device_output_limit -from core.handle.abortHandle import handleAbortMessage +from core.handle.textHandler.abortHandle import handleAbortMessage from core.handle.sendAudioHandle import SentenceType from core.utils.util import audio_to_data_stream diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index 86363217e..c1055fed8 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -1,154 +1,14 @@ -import json -import time -from core.handle.abortHandle import handleAbortMessage -from core.handle.helloHandle import handleHelloMessage -from core.providers.tools.device_mcp import handle_mcp_message -from core.utils.util import remove_punctuation_and_length, filter_sensitive_info -from core.handle.receiveAudioHandle import startToChat, handleAudioMessage -from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus -from core.handle.reportHandle import enqueue_asr_report -import asyncio +from core.handle.messageHandlerRegistry import MessageHandlerRegistry +from core.handle.messageProcessor import MessageProcessor TAG = __name__ +# 全局处理器注册表 +message_registry = MessageHandlerRegistry() + +# 创建全局消息处理器实例 +message_processor = MessageProcessor(message_registry) async def handleTextMessage(conn, message): """处理文本消息""" - try: - msg_json = json.loads(message) - if isinstance(msg_json, int): - conn.logger.bind(tag=TAG).info(f"收到文本消息:{message}") - await conn.websocket.send(message) - return - if msg_json["type"] == "hello": - conn.logger.bind(tag=TAG).info(f"收到hello消息:{message}") - await handleHelloMessage(conn, msg_json) - elif msg_json["type"] == "abort": - conn.logger.bind(tag=TAG).info(f"收到abort消息:{message}") - await handleAbortMessage(conn) - elif msg_json["type"] == "listen": - conn.logger.bind(tag=TAG).info(f"收到listen消息:{message}") - if "mode" in msg_json: - conn.client_listen_mode = msg_json["mode"] - conn.logger.bind(tag=TAG).debug( - f"客户端拾音模式:{conn.client_listen_mode}" - ) - if msg_json["state"] == "start": - conn.client_have_voice = True - conn.client_voice_stop = False - elif msg_json["state"] == "stop": - conn.client_have_voice = True - conn.client_voice_stop = True - if len(conn.asr_audio) > 0: - await handleAudioMessage(conn, b"") - elif msg_json["state"] == "detect": - conn.client_have_voice = False - conn.asr_audio.clear() - if "text" in msg_json: - conn.last_activity_time = time.time() * 1000 - original_text = msg_json["text"] # 保留原始文本 - filtered_len, filtered_text = remove_punctuation_and_length( - original_text - ) - # 识别是否是唤醒词 - is_wakeup_words = filtered_text in conn.config.get("wakeup_words") - if not is_wakeup_words: - # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) - enqueue_asr_report(conn, original_text, []) - # 否则需要LLM对文字内容进行答复 - await startToChat(conn, original_text) - elif msg_json["type"] == "iot": - conn.logger.bind(tag=TAG).info(f"收到iot消息:{message}") - if "descriptors" in msg_json: - asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"])) - if "states" in msg_json: - asyncio.create_task(handleIotStatus(conn, msg_json["states"])) - elif msg_json["type"] == "mcp": - conn.logger.bind(tag=TAG).info(f"收到mcp消息:{message[:100]}") - if "payload" in msg_json: - asyncio.create_task( - handle_mcp_message(conn, conn.mcp_client, msg_json["payload"]) - ) - elif msg_json["type"] == "server": - # 记录日志时过滤敏感信息 - conn.logger.bind(tag=TAG).info( - f"收到服务器消息:{filter_sensitive_info(msg_json)}" - ) - # 如果配置是从API读取的,则需要验证secret - if not conn.read_config_from_api: - return - # 获取post请求的secret - post_secret = msg_json.get("content", {}).get("secret", "") - secret = conn.config["manager-api"].get("secret", "") - # 如果secret不匹配,则返回 - if post_secret != secret: - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": "服务器密钥验证失败", - } - ) - ) - return - # 动态更新配置 - if msg_json["action"] == "update_config": - try: - # 更新WebSocketServer的配置 - if not conn.server: - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": "无法获取服务器实例", - "content": {"action": "update_config"}, - } - ) - ) - return - - if not await conn.server.update_config(): - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": "更新服务器配置失败", - "content": {"action": "update_config"}, - } - ) - ) - return - - # 发送成功响应 - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "success", - "message": "配置更新成功", - "content": {"action": "update_config"}, - } - ) - ) - except Exception as e: - conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}") - await conn.websocket.send( - json.dumps( - { - "type": "server", - "status": "error", - "message": f"更新配置失败: {str(e)}", - "content": {"action": "update_config"}, - } - ) - ) - # 重启服务器 - elif msg_json["action"] == "restart": - await conn.handle_restart(msg_json) - else: - conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}") - except json.JSONDecodeError: - await conn.websocket.send(message) + await message_processor.process_message(conn, message) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/abortHandle.py b/main/xiaozhi-server/core/handle/textHandler/abortHandle.py similarity index 100% rename from main/xiaozhi-server/core/handle/abortHandle.py rename to main/xiaozhi-server/core/handle/textHandler/abortHandle.py diff --git a/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py new file mode 100644 index 000000000..a9fccde6e --- /dev/null +++ b/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py @@ -0,0 +1,16 @@ +from typing import Dict, Any + +from core.handle.messageType import MessageType +from core.handle.textHandler.abortHandle import handleAbortMessage +from core.handle.textHandler.messageHandler import MessageHandler + + +class AbortMessageHandler(MessageHandler): + """Abort消息处理器""" + + @property + def message_type(self) -> MessageType: + return MessageType.ABORT + + async def handle(self, conn, msg_json: Dict[str, Any]) -> None: + await handleAbortMessage(conn) diff --git a/main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py new file mode 100644 index 000000000..a292f0ebf --- /dev/null +++ b/main/xiaozhi-server/core/handle/textHandler/helloMessageHandler.py @@ -0,0 +1,38 @@ +import asyncio +import json +from typing import Dict, Any + +from core.handle.messageType import MessageType +from core.handle.textHandler.messageHandler import MessageHandler +from core.providers.tools.device_mcp import send_mcp_initialize_message, send_mcp_tools_list_request, MCPClient + +TAG = __name__ + + +class HelloMessageHandler(MessageHandler): + """Hello消息处理器""" + + @property + def message_type(self) -> MessageType: + return MessageType.HELLO + + async def handle(self, conn, msg_json: Dict[str, Any]) -> None: + audio_params = msg_json.get("audio_params") + if audio_params: + audio_format = audio_params.get("format") + conn.logger.bind(tag=TAG).info(f"客户端音频格式: {audio_format}") + conn.audio_format = audio_format + conn.welcome_msg["audio_params"] = audio_params + features = msg_json.get("features") + if features: + conn.logger.bind(tag=TAG).info(f"客户端特性: {features}") + conn.features = features + if features.get("mcp"): + conn.logger.bind(tag=TAG).info("客户端支持MCP") + conn.mcp_client = MCPClient() + # 发送初始化 + asyncio.create_task(send_mcp_initialize_message(conn)) + # 发送mcp消息,获取tools列表 + asyncio.create_task(send_mcp_tools_list_request(conn)) + + await conn.websocket.send(json.dumps(conn.welcome_msg)) diff --git a/main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py new file mode 100644 index 000000000..eb69e036e --- /dev/null +++ b/main/xiaozhi-server/core/handle/textHandler/iotMessageHandler.py @@ -0,0 +1,20 @@ +import asyncio +from typing import Dict, Any + +from core.handle.messageType import MessageType +from core.handle.textHandler.messageHandler import MessageHandler +from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus + + +class IotMessageHandler(MessageHandler): + """IoT消息处理器""" + + @property + def message_type(self) -> MessageType: + return MessageType.IOT + + async def handle(self, conn, msg_json: Dict[str, Any]) -> None: + if "descriptors" in msg_json: + asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"])) + if "states" in msg_json: + asyncio.create_task(handleIotStatus(conn, msg_json["states"])) diff --git a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py new file mode 100644 index 000000000..7c553b4e8 --- /dev/null +++ b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py @@ -0,0 +1,49 @@ +import time +from typing import Dict, Any + +from core.handle.messageType import MessageType +from core.handle.receiveAudioHandle import startToChat, handleAudioMessage +from core.handle.reportHandle import enqueue_asr_report +from core.handle.textHandler.messageHandler import MessageHandler +from core.utils.util import remove_punctuation_and_length + +TAG = __name__ + + +class ListenMessageHandler(MessageHandler): + """Listen消息处理器""" + + @property + def message_type(self) -> MessageType: + return MessageType.LISTEN + + async def handle(self, conn, msg_json: Dict[str, Any]) -> None: + if "mode" in msg_json: + conn.client_listen_mode = msg_json["mode"] + conn.logger.bind(tag=TAG).debug( + f"客户端拾音模式:{conn.client_listen_mode}" + ) + if msg_json["state"] == "start": + conn.client_have_voice = True + conn.client_voice_stop = False + elif msg_json["state"] == "stop": + conn.client_have_voice = True + conn.client_voice_stop = True + if len(conn.asr_audio) > 0: + await handleAudioMessage(conn, b"") + elif msg_json["state"] == "detect": + conn.client_have_voice = False + conn.asr_audio.clear() + if "text" in msg_json: + conn.last_activity_time = time.time() * 1000 + original_text = msg_json["text"] # 保留原始文本 + filtered_len, filtered_text = remove_punctuation_and_length( + original_text + ) + # 识别是否是唤醒词 + is_wakeup_words = filtered_text in conn.config.get("wakeup_words") + if not is_wakeup_words: + # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) + enqueue_asr_report(conn, original_text, []) + # 否则需要LLM对文字内容进行答复 + await startToChat(conn, original_text) diff --git a/main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py new file mode 100644 index 000000000..2000ac0dd --- /dev/null +++ b/main/xiaozhi-server/core/handle/textHandler/mcpMessageHandler.py @@ -0,0 +1,20 @@ +import asyncio +from typing import Dict, Any + +from core.handle.messageType import MessageType +from core.handle.textHandler.messageHandler import MessageHandler +from core.providers.tools.device_mcp import handle_mcp_message + + +class McpMessageHandler(MessageHandler): + """MCP消息处理器""" + + @property + def message_type(self) -> MessageType: + return MessageType.MCP + + async def handle(self, conn, msg_json: Dict[str, Any]) -> None: + if "payload" in msg_json: + asyncio.create_task( + handle_mcp_message(conn, conn.mcp_client, msg_json["payload"]) + ) diff --git a/main/xiaozhi-server/core/handle/textHandler/messageHandler.py b/main/xiaozhi-server/core/handle/textHandler/messageHandler.py new file mode 100644 index 000000000..1e42acf64 --- /dev/null +++ b/main/xiaozhi-server/core/handle/textHandler/messageHandler.py @@ -0,0 +1,21 @@ +from abc import abstractmethod, ABC +from typing import Dict, Any + +from core.handle.messageType import MessageType + +TAG = __name__ + + +class MessageHandler(ABC): + """消息处理器抽象基类""" + + @abstractmethod + async def handle(self, conn, msg_json: Dict[str, Any]) -> None: + """处理消息的抽象方法""" + pass + + @property + @abstractmethod + def message_type(self) -> MessageType: + """返回处理的消息类型""" + pass diff --git a/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py new file mode 100644 index 000000000..2ca818c6a --- /dev/null +++ b/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py @@ -0,0 +1,96 @@ +import json +from typing import Dict, Any + +from core.handle.messageType import MessageType +from core.handle.textHandler.messageHandler import MessageHandler +from core.utils.util import filter_sensitive_info + +TAG = __name__ + + +class ServerMessageHandler(MessageHandler): + """服务器消息处理器""" + + @property + def message_type(self) -> MessageType: + return MessageType.SERVER + + async def handle(self, conn, msg_json: Dict[str, Any]) -> None: + # 记录日志时过滤敏感信息 + conn.logger.bind(tag=TAG).info( + f"收到服务器消息:{filter_sensitive_info(msg_json)}" + ) + # 如果配置是从API读取的,则需要验证secret + if not conn.read_config_from_api: + return + # 获取post请求的secret + post_secret = msg_json.get("content", {}).get("secret", "") + secret = conn.config["manager-api"].get("secret", "") + # 如果secret不匹配,则返回 + if post_secret != secret: + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": "服务器密钥验证失败", + } + ) + ) + return + # 动态更新配置 + if msg_json["action"] == "update_config": + try: + # 更新WebSocketServer的配置 + if not conn.server: + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": "无法获取服务器实例", + "content": {"action": "update_config"}, + } + ) + ) + return + + if not await conn.server.update_config(): + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": "更新服务器配置失败", + "content": {"action": "update_config"}, + } + ) + ) + return + + # 发送成功响应 + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "success", + "message": "配置更新成功", + "content": {"action": "update_config"}, + } + ) + ) + except Exception as e: + conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}") + await conn.websocket.send( + json.dumps( + { + "type": "server", + "status": "error", + "message": f"更新配置失败: {str(e)}", + "content": {"action": "update_config"}, + } + ) + ) + # 重启服务器 + elif msg_json["action"] == "restart": + await conn.handle_restart(msg_json)