This commit is contained in:
Alireza Jahanshahlou 2025-10-17 01:02:26 +03:30
parent 69d722599b
commit 6aedb3c3f5
19 changed files with 317 additions and 318 deletions

View file

@ -17,21 +17,21 @@ class OTAHandler(BaseHandler):
super().__init__(config) super().__init__(config)
auth_config = config["server"].get("auth", {}) auth_config = config["server"].get("auth", {})
self.auth_enable = auth_config.get("enabled", False) self.auth_enable = auth_config.get("enabled", False)
# 设备白名单 # Device whitelist
self.allowed_devices = set(auth_config.get("allowed_devices", [])) self.allowed_devices = set(auth_config.get("allowed_devices", []))
secret_key = config["server"]["auth_key"] secret_key = config["server"]["auth_key"]
expire_seconds = auth_config.get("expire_seconds") expire_seconds = auth_config.get("expire_seconds")
self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds) self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds)
def generate_password_signature(self, content: str, secret_key: str) -> str: def generate_password_signature(self, content: str, secret_key: str) -> str:
"""生成MQTT密码签名 """Generate MQTT cryptographic signature
Args: Args:
content: 签名内容 (clientId + '|' + username) content: signature content (clientId + '|' + username)
secret_key: 密钥 secret_key: key
Returns: Returns:
str: Base64编码的HMAC-SHA256签名 str: Base64 encoded HMAC-SHA256 signature
""" """
try: try:
hmac_obj = hmac.new( hmac_obj = hmac.new(
@ -40,46 +40,46 @@ class OTAHandler(BaseHandler):
signature = hmac_obj.digest() signature = hmac_obj.digest()
return base64.b64encode(signature).decode("utf-8") return base64.b64encode(signature).decode("utf-8")
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"生成MQTT密码签名失败: {e}") self.logger.bind(tag=TAG).error(f"Failed to generate mqtt password signature: {e}")
return "" return ""
def _get_websocket_url(self, local_ip: str, port: int) -> str: def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址 """Get websocket address
Args: Args:
local_ip: 本地IP地址 local_ip: local IP address
port: 端口号 port: port number
Returns: Returns:
str: websocket地址 str: websocket address
""" """
server_config = self.config["server"] server_config = self.config["server"]
websocket_config = server_config.get("websocket", "") websocket_config = server_config.get("websocket", "")
if "你的" not in websocket_config: if "your" not in websocket_config:
return websocket_config return websocket_config
else: else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/" return f"ws://{local_ip}:{port}/xiaozhi/v1/"
async def handle_post(self, request): async def handle_post(self, request):
"""处理 OTA POST 请求""" """Handling OTA POST requests"""
try: try:
data = await request.text() data = await request.text()
self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}") self.logger.bind(tag=TAG).debug(f"Ota request method: {request.method}")
self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}") self.logger.bind(tag=TAG).debug(f"Ota request header: {request.headers}")
self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}") self.logger.bind(tag=TAG).debug(f"Ota request data: {data}")
device_id = request.headers.get("device-id", "") device_id = request.headers.get("device-id", "")
if device_id: if device_id:
self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}") self.logger.bind(tag=TAG).info(f"Ota requests device id: {device_id}")
else: else:
raise Exception("OTA请求设备ID为空") raise Exception("Ota request device id is empty")
client_id = request.headers.get("client-id", "") client_id = request.headers.get("client-id", "")
if client_id: if client_id:
self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}") self.logger.bind(tag=TAG).info(f"Ota requests client id: {client_id}")
else: else:
raise Exception("OTA请求ClientID为空") raise Exception("Ota request client id is empty")
data_json = json.loads(data) data_json = json.loads(data)
@ -100,8 +100,8 @@ class OTAHandler(BaseHandler):
mqtt_gateway_endpoint = server_config.get("mqtt_gateway") mqtt_gateway_endpoint = server_config.get("mqtt_gateway")
if mqtt_gateway_endpoint: # 如果配置了非空字符串 if mqtt_gateway_endpoint: # If a non-empty string is configured
# 尝试从请求数据中获取设备型号 # Try to get the device model from the request data
device_model = "default" device_model = "default"
try: try:
if "device" in data_json and isinstance(data_json["device"], dict): if "device" in data_json and isinstance(data_json["device"], dict):
@ -110,13 +110,13 @@ class OTAHandler(BaseHandler):
device_model = data_json["model"] device_model = data_json["model"]
group_id = f"GID_{device_model}".replace(":", "_").replace(" ", "_") group_id = f"GID_{device_model}".replace(":", "_").replace(" ", "_")
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"获取设备型号失败: {e}") self.logger.bind(tag=TAG).error(f"Failed to obtain device model: {e}")
group_id = "GID_default" group_id = "GID_default"
mac_address_safe = device_id.replace(":", "_") mac_address_safe = device_id.replace(":", "_")
mqtt_client_id = f"{group_id}@@@{mac_address_safe}@@@{mac_address_safe}" mqtt_client_id = f"{group_id}@@@{mac_address_safe}@@@{mac_address_safe}"
# 构建用户数据 # Build user data
user_data = {"ip": "unknown"} user_data = {"ip": "unknown"}
try: try:
user_data_json = json.dumps(user_data) user_data_json = json.dumps(user_data)
@ -124,10 +124,10 @@ class OTAHandler(BaseHandler):
"utf-8" "utf-8"
) )
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"生成用户名失败: {e}") self.logger.bind(tag=TAG).error(f"Failed to generate username: {e}")
username = "" username = ""
# 生成密码 # Generate password
password = "" password = ""
signature_key = server_config.get("mqtt_signature_key", "") signature_key = server_config.get("mqtt_signature_key", "")
if signature_key: if signature_key:
@ -135,11 +135,11 @@ class OTAHandler(BaseHandler):
mqtt_client_id + "|" + username, signature_key mqtt_client_id + "|" + username, signature_key
) )
if not password: if not password:
password = "" # 签名失败则留空,由设备决定是否允许无密码 password = "" # If the signature fails, leave it blank and the device will decide whether to allow no password.
else: else:
self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空") self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空")
# 构建MQTT配置(直接使用 mqtt_gateway 字符串) #Build MQTT configuration (using mqtt_gateway string directly)
return_json["mqtt_gateway"] = { return_json["mqtt_gateway"] = {
"endpoint": mqtt_gateway_endpoint, "endpoint": mqtt_gateway_endpoint,
"client_id": mqtt_client_id, "client_id": mqtt_client_id,
@ -150,8 +150,8 @@ class OTAHandler(BaseHandler):
} }
self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置") self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置")
else: # 未配置 mqtt_gateway,下发 WebSocket else: # mqtt_gateway is not configured, and WebSocket is delivered
# 如果开启了认证,则进行认证校验 # If authentication is turned on, perform authentication verification
token = "" token = ""
if self.auth_enable: if self.auth_enable:
if self.allowed_devices: if self.allowed_devices:
@ -164,7 +164,7 @@ class OTAHandler(BaseHandler):
"token": token, "token": token,
} }
self.logger.bind(tag=TAG).info( self.logger.bind(tag=TAG).info(
f"未配置MQTT网关,为设备 {device_id} 下发WebSocket配置" f"The MQTT gateway is not configured, and the WebSocket configuration is delivered to the device {device_id}."
) )
self.logger.bind(tag=TAG).info(f"{return_json}") self.logger.bind(tag=TAG).info(f"{return_json}")
@ -183,17 +183,17 @@ class OTAHandler(BaseHandler):
return response return response
async def handle_get(self, request): async def handle_get(self, request):
"""处理 OTA GET 请求""" """Handling OTA GET requests"""
try: try:
server_config = self.config["server"] server_config = self.config["server"]
local_ip = get_local_ip() local_ip = get_local_ip()
port = int(server_config.get("port", 8000)) port = int(server_config.get("port", 8000))
websocket_url = self._get_websocket_url(local_ip, port) websocket_url = self._get_websocket_url(local_ip, port)
message = f"OTA接口运行正常,向设备发送的websocket地址是:{websocket_url}" message = f"The Ota interface is running normally, and the websocket address sent to the device is: {websocket url}"
response = web.Response(text=message, content_type="text/plain") response = web.Response(text=message, content_type="text/plain")
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}") self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}")
response = web.Response(text="OTA接口异常", content_type="text/plain") response = web.Response(text="Ota interface exception", content_type="text/plain")
finally: finally:
self._add_cors_headers(response) self._add_cors_headers(response)
return response return response

View file

@ -12,7 +12,7 @@ from plugins_func.register import Action
TAG = __name__ TAG = __name__
# 设置最大文件大小为5MB # Set maximum file size to 5 mb
MAX_FILE_SIZE = 5 * 1024 * 1024 MAX_FILE_SIZE = 5 * 1024 * 1024
@ -20,27 +20,27 @@ class VisionHandler:
def __init__(self, config: dict): def __init__(self, config: dict):
self.config = config self.config = config
self.logger = setup_logging() self.logger = setup_logging()
# 初始化认证工具 # Initialization authentication tool
self.auth = AuthToken(config["server"]["auth_key"]) self.auth = AuthToken(config["server"]["auth_key"])
def _create_error_response(self, message: str) -> dict: def _create_error_response(self, message: str) -> dict:
"""创建统一的错误响应格式""" """Create a unified error response format"""
return {"success": False, "message": message} return {"success": False, "message": message}
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]: def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
"""验证认证token""" """Verify authentication token"""
auth_header = request.headers.get("Authorization", "") auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "): if not auth_header.startswith("Bearer "):
return False, None return False, None
token = auth_header[7:] # 移除"Bearer "前缀 token = auth_header[7:] # Remove "Bearer" prefix
return self.auth.verify_token(token) return self.auth.verify_token(token)
async def handle_post(self, request): async def handle_post(self, request):
"""处理 MCP Vision POST 请求""" """处理 MCP Vision POST 请求"""
response = None # 初始化response变量 response = None # Initialize response variable
try: try:
# 验证token # Verification token
is_valid, token_device_id = self._verify_auth_token(request) is_valid, token_device_id = self._verify_auth_token(request)
if not is_valid: if not is_valid:
response = web.Response( response = web.Response(
@ -52,47 +52,47 @@ class VisionHandler:
) )
return response return response
# 获取请求头信息 # Get request header information
device_id = request.headers.get("Device-Id", "") device_id = request.headers.get("Device-Id", "")
client_id = request.headers.get("Client-Id", "") client_id = request.headers.get("Client-Id", "")
if device_id != token_device_id: if device_id != token_device_id:
raise ValueError("设备ID与token不匹配") raise ValueError("Device id and token do not match")
# 解析multipart/form-data请求 # Parse multipart/form data requests
reader = await request.multipart() reader = await request.multipart()
# 读取question字段 # Read question field
question_field = await reader.next() question_field = await reader.next()
if question_field is None: if question_field is None:
raise ValueError("缺少问题字段") raise ValueError("Missing question field")
question = await question_field.text() question = await question_field.text()
self.logger.bind(tag=TAG).debug(f"Question: {question}") self.logger.bind(tag=TAG).debug(f"Question: {question}")
# 读取图片文件 # Read image files
image_field = await reader.next() image_field = await reader.next()
if image_field is None: if image_field is None:
raise ValueError("缺少图片文件") raise ValueError("Missing image file")
# 读取图片数据 # Read image data
image_data = await image_field.read() image_data = await image_field.read()
if not image_data: if not image_data:
raise ValueError("图片数据为空") raise ValueError("Image data is empty")
# 检查文件大小 # Check file size
if len(image_data) > MAX_FILE_SIZE: if len(image_data) > MAX_FILE_SIZE:
raise ValueError( raise ValueError(
f"图片大小超过限制,最大允许{MAX_FILE_SIZE/1024/1024}MB" f"The image size exceeds the limit, the maximum allowed is {max file size/1024/1024}mb"
) )
# 检查文件格式 # Check file format
if not is_valid_image_file(image_data): if not is_valid_image_file(image_data):
raise ValueError( raise ValueError(
"不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)" "Unsupported file format, please upload a valid image file (supports jpeg, png, gif, bmp, tiff, webp formats)"
) )
# 将图片转换为base64编码 # Convert image to base64 encoding
image_base64 = base64.b64encode(image_data).decode("utf-8") image_base64 = base64.b64encode(image_data).decode("utf-8")
# 如果开启了智控台,则从智控台获取模型配置 # If the smart console is turned on, get the model configuration from the smart console
current_config = copy.deepcopy(self.config) current_config = copy.deepcopy(self.config)
read_config_from_api = current_config.get("read_config_from_api", False) read_config_from_api = current_config.get("read_config_from_api", False)
if read_config_from_api: if read_config_from_api:
@ -104,7 +104,7 @@ class VisionHandler:
select_vllm_module = current_config["selected_module"].get("VLLM") select_vllm_module = current_config["selected_module"].get("VLLM")
if not select_vllm_module: if not select_vllm_module:
raise ValueError("您还未设置默认的视觉分析模块") raise ValueError("You have not set up a default visual analysis module")
vllm_type = ( vllm_type = (
select_vllm_module select_vllm_module
@ -113,7 +113,7 @@ class VisionHandler:
) )
if not vllm_type: if not vllm_type:
raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}") raise ValueError(f"Unable to find provider for vllm module{vllm_type}")
vllm = create_instance( vllm = create_instance(
vllm_type, current_config["VLLM"][select_vllm_module] vllm_type, current_config["VLLM"][select_vllm_module]
@ -132,15 +132,15 @@ class VisionHandler:
content_type="application/json", content_type="application/json",
) )
except ValueError as e: except ValueError as e:
self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}") self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}")
return_json = self._create_error_response(str(e)) return_json = self._create_error_response(str(e))
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json", content_type="application/json",
) )
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}") self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}")
return_json = self._create_error_response("处理请求时发生错误") return_json = self._create_error_response("An error occurred while processing the request")
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json", content_type="application/json",
@ -151,20 +151,20 @@ class VisionHandler:
return response return response
async def handle_get(self, request): async def handle_get(self, request):
"""处理 MCP Vision GET 请求""" """Handling MCP Vision GET requests"""
try: try:
vision_explain = get_vision_url(self.config) vision_explain = get_vision_url(self.config)
if vision_explain and len(vision_explain) > 0 and "null" != vision_explain: if vision_explain and len(vision_explain) > 0 and "null" != vision_explain:
message = ( message = (
f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}" f"The MCP Vision interface is running normally, and the address of the visual interpretation interface is:{vision_explain}"
) )
else: else:
message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址" message = "The MCP Vision interface is not running properly. Please open the .config.yaml file in the data directory, find [server.vision_explain], and set the address."
response = web.Response(text=message, content_type="text/plain") response = web.Response(text=message, content_type="text/plain")
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}") self.logger.bind(tag=TAG).error(f"MCP Vision GET request exception:{e}")
return_json = self._create_error_response("服务器内部错误") return_json = self._create_error_response("Server internal error")
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json", content_type="application/json",
@ -174,7 +174,7 @@ class VisionHandler:
return response return response
def _add_cors_headers(self, response): def _add_cors_headers(self, response):
"""添加CORS头信息""" """Add cors header information"""
response.headers["Access-Control-Allow-Headers"] = ( response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id" "client-id, content-type, device-id"
) )

View file

@ -5,10 +5,10 @@ TAG = __name__
async def handleAbortMessage(conn): async def handleAbortMessage(conn):
conn.logger.bind(tag=TAG).info("Abort message received") conn.logger.bind(tag=TAG).info("Abort message received")
# 设置成打断状态,会自动打断llm、tts任务 # Set to interrupt state, it will automatically interrupt llm and tts tasks
conn.client_abort = True conn.client_abort = True
conn.clear_queues() conn.clear_queues()
# 打断客户端说话状态 # Interrupt client speaking state
await conn.websocket.send( await conn.websocket.send(
json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id}) json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id})
) )

View file

@ -19,43 +19,43 @@ TAG = __name__
WAKEUP_CONFIG = { WAKEUP_CONFIG = {
"refresh_time": 10, "refresh_time": 10,
"responses": [ "responses": [
"我一直都在呢,您请说。", "I'm always here, please tell me.",
"在的呢,请随时吩咐我。", "I'm here, please give me orders at any time.",
"来啦来啦,请告诉我吧。", "Come on, come on, please tell me.",
"您请说,我正听着。", "Please speak, I am listening.",
"请您讲话,我准备好了。", "Please speak, I'm ready.",
"请您说出指令吧。", "Please give the command.",
"我认真听着呢,请讲。", "I'm listening carefully. Please speak.",
"请问您需要什么帮助?", "What help do you need?",
"我在这里,等候您的指令。", "I'm here, waiting for your instructions.",
], ],
} }
# 创建全局的唤醒词配置管理器 # Create a global wake word configuration manager
wakeup_words_config = WakeupWordsConfig() wakeup_words_config = WakeupWordsConfig()
# 用于防止并发调用wakeupWordsResponse的锁 # Lock used to prevent concurrent calls to wakeup words response
_wakeup_response_lock = asyncio.Lock() _wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json): async def handleHelloMessage(conn, msg_json):
"""处理hello消息""" """Handle hello message"""
audio_params = msg_json.get("audio_params") audio_params = msg_json.get("audio_params")
if audio_params: if audio_params:
format = audio_params.get("format") format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}") conn.logger.bind(tag=TAG).info(f"Client audio format: {format}")
conn.audio_format = format conn.audio_format = format
conn.welcome_msg["audio_params"] = audio_params conn.welcome_msg["audio_params"] = audio_params
features = msg_json.get("features") features = msg_json.get("features")
if features: if features:
conn.logger.bind(tag=TAG).info(f"客户端特性: {features}") conn.logger.bind(tag=TAG).info(f"Client features: {features}")
conn.features = features conn.features = features
if features.get("mcp"): if features.get("mcp"):
conn.logger.bind(tag=TAG).info("客户端支持MCP") conn.logger.bind(tag=TAG).info("Client supports mcp")
conn.mcp_client = MCPClient() conn.mcp_client = MCPClient()
# 发送初始化 # Send initialization
asyncio.create_task(send_mcp_initialize_message(conn)) asyncio.create_task(send_mcp_initialize_message(conn))
# 发送mcp消息,获取tools列表 # Send mcp message and get tools list
asyncio.create_task(send_mcp_tools_list_request(conn)) asyncio.create_task(send_mcp_tools_list_request(conn))
await conn.websocket.send(json.dumps(conn.welcome_msg)) await conn.websocket.send(json.dumps(conn.welcome_msg))
@ -66,7 +66,7 @@ async def checkWakeupWords(conn, text):
"enable_wakeup_words_response_cache" "enable_wakeup_words_response_cache"
] ]
# 等待tts初始化,最多等待3秒 # Wait for tts to initialize, up to 3 seconds
start_time = time.time() start_time = time.time()
while time.time() - start_time < 3: while time.time() - start_time < 3:
if conn.tts: if conn.tts:
@ -85,34 +85,34 @@ async def checkWakeupWords(conn, text):
conn.just_woken_up = True conn.just_woken_up = True
await send_tts_message(conn, "start") await send_tts_message(conn, "start")
# 获取当前音色 # Get the current sound
voice = getattr(conn.tts, "voice", "default") voice = getattr(conn.tts, "voice", "default")
if not voice: if not voice:
voice = "default" voice = "default"
# 获取唤醒词回复配置 # Get wake word reply configuration
response = wakeup_words_config.get_wakeup_response(voice) response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"): if not response or not response.get("file_path"):
response = { response = {
"voice": "default", "voice": "default",
"file_path": "config/assets/wakeup_words_short.wav", "file_path": "config/assets/wakeup_words_short.wav",
"time": 0, "time": 0,
"text": "我在这里哦!", "text": "I'm here!",
} }
# 获取音频数据 # Get audio data
opus_packets = audio_to_data(response.get("file_path")) opus_packets = audio_to_data(response.get("file_path"))
# 播放唤醒词回复 # Play wake word reply
conn.client_abort = False conn.client_abort = False
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}") conn.logger.bind(tag=TAG).info(f"Play wake word reply: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text")) await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None) await sendAudioMessage(conn, SentenceType.LAST, [], None)
# 补充对话 # Supplementary dialogue
conn.dialogue.put(Message(role="assistant", content=response.get("text"))) conn.dialogue.put(Message(role="assistant", content=response.get("text")))
# 检查是否需要更新唤醒词回复 # Check if wake word reply needs to be updated
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]: if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked(): if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn)) asyncio.create_task(wakeupWordsResponse(conn))
@ -124,30 +124,30 @@ async def wakeupWordsResponse(conn):
return return
try: try:
# 尝试获取锁,如果获取不到就返回 # Try to acquire the lock, and return if unable
if not await _wakeup_response_lock.acquire(): if not await _wakeup_response_lock.acquire():
return return
# 从预定义回复列表中随机选择一个回复 # Randomly select a reply from a list of predefined replies
result = random.choice(WAKEUP_CONFIG["responses"]) result = random.choice(WAKEUP_CONFIG["responses"])
if not result or len(result) == 0: if not result or len(result) == 0:
return return
# 生成TTS音频 # Generate tts audio
tts_result = await asyncio.to_thread(conn.tts.to_tts, result) tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result: if not tts_result:
return return
# 获取当前音色 # Get the current sound
voice = getattr(conn.tts, "voice", "default") voice = getattr(conn.tts, "voice", "default")
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000) wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
file_path = wakeup_words_config.generate_file_path(voice) file_path = wakeup_words_config.generate_file_path(voice)
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
f.write(wav_bytes) f.write(wav_bytes)
# 更新配置 # Update configuration
wakeup_words_config.update_wakeup_response(voice, file_path, result) wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally: finally:
# 确保在任何情况下都释放锁 # Make sure the lock is released under any circumstances
if _wakeup_response_lock.locked(): if _wakeup_response_lock.locked():
_wakeup_response_lock.release() _wakeup_response_lock.release()

View file

@ -13,45 +13,44 @@ TAG = __name__
async def handle_user_intent(conn, text): async def handle_user_intent(conn, text):
# 预处理输入文本,处理可能的JSON格式 # Preprocess input text, handle possible json formats
try: try:
if text.strip().startswith('{') and text.strip().endswith('}'): if text.strip().startswith('{') and text.strip().endswith('}'):
parsed_data = json.loads(text) parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data: if isinstance(parsed_data, dict) and "content" in parsed_data:
text = parsed_data["content"] # 提取content用于意图分析 text = parsed_data["content"] # Extract content for intent analysis
conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息 conn.current_speaker = parsed_data.get("speaker") # Keep speaker information
except (json.JSONDecodeError, TypeError): except (json.JSONDecodeError, TypeError):
pass pass
# 检查是否有明确的退出命令 # Check if there is an explicit exit command
_, filtered_text = remove_punctuation_and_length(text) _, filtered_text = remove_punctuation_and_length(text)
if await check_direct_exit(conn, filtered_text): if await check_direct_exit(conn, filtered_text):
return True return True
# 检查是否是唤醒词 # Check if it is wake word
if await checkWakeupWords(conn, filtered_text): if await checkWakeupWords(conn, filtered_text):
return True return True
if conn.intent_type == "function_call": if conn.intent_type == "function_call":
# 使用支持function calling的聊天方法,不再进行意图分析 # Use chat methods that support function calling and no longer perform intent analysis. return False
return False # Using llm for intent analysis
# 使用LLM进行意图分析
intent_result = await analyze_intent_with_llm(conn, text) intent_result = await analyze_intent_with_llm(conn, text)
if not intent_result: if not intent_result:
return False return False
# 会话开始时生成sentence_id # Sentence id is generated at the beginning of the session
conn.sentence_id = str(uuid.uuid4().hex) conn.sentence_id = str(uuid.uuid4().hex)
# 处理各种意图 # Handle various intentions
return await process_intent_result(conn, intent_result, text) return await process_intent_result(conn, intent_result, text)
async def check_direct_exit(conn, text): async def check_direct_exit(conn, text):
"""检查是否有明确的退出命令""" """Check if there is an explicit exit command"""
_, text = remove_punctuation_and_length(text) _, text = remove_punctuation_and_length(text)
cmd_exit = conn.cmd_exit cmd_exit = conn.cmd_exit
for cmd in cmd_exit: for cmd in cmd_exit:
if text == cmd: if text == cmd:
conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}") conn.logger.bind(tag=TAG).info(f"Explicit exit command recognized: {text}")
await send_stt_message(conn, text) await send_stt_message(conn, text)
await conn.close() await conn.close()
return True return True
@ -59,33 +58,33 @@ async def check_direct_exit(conn, text):
async def analyze_intent_with_llm(conn, text): async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图""" """Analyze user intent using llm"""
if not hasattr(conn, "intent") or not conn.intent: if not hasattr(conn, "intent") or not conn.intent:
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化") conn.logger.bind(tag=TAG).warning("Intent recognition service not initialized")
return None return None
# 对话历史记录 # Conversation history
dialogue = conn.dialogue dialogue = conn.dialogue
try: try:
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text) intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
return intent_result return intent_result
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}") conn.logger.bind(tag=TAG).error(f"Intent recognition failed: {str(e)}")
return None return None
async def process_intent_result(conn, intent_result, original_text): async def process_intent_result(conn, intent_result, original_text):
"""处理意图识别结果""" """Processing intent recognition results"""
try: try:
# 尝试将结果解析为JSON # Try parsing the result into json
intent_data = json.loads(intent_result) intent_data = json.loads(intent_result)
# 检查是否有function_call # Check if there is a function call
if "function_call" in intent_data: if "function_call" in intent_data:
# 直接从意图识别获取了function_call # The function call is obtained directly from the intent recognition
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}" f"Intent result in function call format detected: {intent_data['function_call']['name']}"
) )
function_name = intent_data["function_call"]["name"] function_name = intent_data["function_call"]["name"]
if function_name == "continue_chat": if function_name == "continue_chat":
@ -102,12 +101,12 @@ async def process_intent_result(conn, intent_result, original_text):
current_time, today_date, today_weekday, lunar_date = get_current_time_info() current_time, today_date, today_weekday, lunar_date = get_current_time_info()
# 构建带上下文的基础提示 # Build contextual foundational prompts
context_prompt = f"""当前时间:{current_time} context_prompt = f"""Current time:{current_time}
今天日期:{today_date} ({today_weekday}) Today’s date:{today_date} ({today_weekday})
今天农历:{lunar_date} Today’s lunar calendar:{lunar_date}
请根据以上信息回答用户的问题:{original_text}""" Please answer the user's questions based on the above information:{original_text}"""
response = conn.intent.replyResult(context_prompt, original_text) response = conn.intent.replyResult(context_prompt, original_text)
speak_txt(conn, response) speak_txt(conn, response)
@ -120,7 +119,7 @@ async def process_intent_result(conn, intent_result, original_text):
function_args = intent_data["function_call"]["arguments"] function_args = intent_data["function_call"]["arguments"]
if function_args is None: if function_args is None:
function_args = {} function_args = {}
# 确保参数是字符串格式的JSON # Make sure the parameter is json in string format
if isinstance(function_args, dict): if isinstance(function_args, dict):
function_args = json.dumps(function_args) function_args = json.dumps(function_args)
@ -133,11 +132,11 @@ async def process_intent_result(conn, intent_result, original_text):
await send_stt_message(conn, original_text) await send_stt_message(conn, original_text)
conn.client_abort = False conn.client_abort = False
# 使用executor执行函数调用和结果处理 # Use executors to perform function calls and result processing
def process_function_call(): def process_function_call():
conn.dialogue.put(Message(role="user", content=original_text)) conn.dialogue.put(Message(role="user", content=original_text))
# 使用统一工具处理器处理所有工具调用 # Use a unified tool processor to handle all tool calls
try: try:
result = asyncio.run_coroutine_threadsafe( result = asyncio.run_coroutine_threadsafe(
conn.func_handler.handle_llm_function_call( conn.func_handler.handle_llm_function_call(
@ -146,17 +145,17 @@ async def process_intent_result(conn, intent_result, original_text):
conn.loop, conn.loop,
).result() ).result()
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"工具调用失败: {e}") conn.logger.bind(tag=TAG).error(f"Tool call failed: {e}")
result = ActionResponse( result = ActionResponse(
action=Action.ERROR, result=str(e), response=str(e) action=Action.ERROR, result=str(e), response=str(e)
) )
if result: if result:
if result.action == Action.RESPONSE: # 直接回复前端 if result.action == Action.RESPONSE: # Reply directly to the front end
text = result.response text = result.response
if text is not None: if text is not None:
speak_txt(conn, text) speak_txt(conn, text)
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 elif result.action == Action.REQLLM: # After calling the function, request llm to generate a reply
text = result.result text = result.result
conn.dialogue.put(Message(role="tool", content=text)) conn.dialogue.put(Message(role="tool", content=text))
llm_result = conn.intent.replyResult(text, original_text) llm_result = conn.intent.replyResult(text, original_text)
@ -172,19 +171,19 @@ async def process_intent_result(conn, intent_result, original_text):
speak_txt(conn, text) speak_txt(conn, text)
elif function_name != "play_music": elif function_name != "play_music":
# For backward compatibility with original code # For backward compatibility with original code
# 获取当前最新的文本索引 # Get the latest text index
text = result.response text = result.response
if text is None: if text is None:
text = result.result text = result.result
if text is not None: if text is not None:
speak_txt(conn, text) speak_txt(conn, text)
# 将函数执行放在线程池中 # Put function execution in thread pool
conn.executor.submit(process_function_call) conn.executor.submit(process_function_call)
return True return True
return False return False
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}") conn.logger.bind(tag=TAG).error(f"Error while processing intent result: {e}")
return False return False

View file

@ -11,53 +11,53 @@ TAG = __name__
async def handleAudioMessage(conn, audio): async def handleAudioMessage(conn, audio):
# 当前片段是否有人说话 # Is anyone speaking in the current segment?
have_voice = conn.vad.is_vad(conn, audio) have_voice = conn.vad.is_vad(conn, audio)
# 如果设备刚刚被唤醒,短暂忽略VAD检测 # If the device has just been woken up, briefly ignore vad detection
if hasattr(conn, "just_woken_up") and conn.just_woken_up: if hasattr(conn, "just_woken_up") and conn.just_woken_up:
have_voice = False have_voice = False
# 设置一个短暂延迟后恢复VAD检测 # Resume vad detection after setting a short delay
conn.asr_audio.clear() conn.asr_audio.clear()
if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done(): if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
return return
# manual 模式下不打断正在播放的内容 # manual Do not interrupt the content being played in mode
if have_voice: if have_voice:
if conn.client_is_speaking and conn.client_listen_mode != "manual": if conn.client_is_speaking and conn.client_listen_mode != "manual":
await handleAbortMessage(conn) await handleAbortMessage(conn)
# 设备长时间空闲检测,用于say goodbye # Device idle detection for a long time, used for say goodbye
await no_voice_close_connect(conn, have_voice) await no_voice_close_connect(conn, have_voice)
# 接收音频 # receive audio
await conn.asr.receive_audio(conn, audio, have_voice) await conn.asr.receive_audio(conn, audio, have_voice)
async def resume_vad_detection(conn): async def resume_vad_detection(conn):
# 等待2秒后恢复VAD检测 # Wait 2 seconds before resuming vad detection
await asyncio.sleep(1) await asyncio.sleep(1)
conn.just_woken_up = False conn.just_woken_up = False
async def startToChat(conn, text): async def startToChat(conn, text):
# 检查输入是否是JSON格式(包含说话人信息) # Check whether the input is in json format (contains speaker information)
speaker_name = None speaker_name = None
actual_text = text actual_text = text
try: try:
# 尝试解析JSON格式的输入 # Try to parse input in json format
if text.strip().startswith("{") and text.strip().endswith("}"): if text.strip().startswith("{") and text.strip().endswith("}"):
data = json.loads(text) data = json.loads(text)
if "speaker" in data and "content" in data: if "speaker" in data and "content" in data:
speaker_name = data["speaker"] speaker_name = data["speaker"]
actual_text = data["content"] actual_text = data["content"]
conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}") conn.logger.bind(tag=TAG).info(f"Parse to speaker information: {speaker_name}")
# 直接使用JSON格式的文本,不解析 # Use text in json format directly without parsing
actual_text = text actual_text = text
except (json.JSONDecodeError, KeyError): except (json.JSONDecodeError, KeyError):
# 如果解析失败,继续使用原始文本 # If parsing fails, continue using the original text
pass pass
# 保存说话人信息到连接对象 # Save speaker information to the connection object
if speaker_name: if speaker_name:
conn.current_speaker = speaker_name conn.current_speaker = speaker_name
else: else:
@ -67,25 +67,25 @@ async def startToChat(conn, text):
await check_bind_device(conn) await check_bind_device(conn)
return return
# 如果当日的输出字数大于限定的字数 # If the number of words output on that day is greater than the limited number of words,
if conn.max_output_size > 0: if conn.max_output_size > 0:
if check_device_output_limit( if check_device_output_limit(
conn.headers.get("device-id"), conn.max_output_size conn.headers.get("device-id"), conn.max_output_size
): ):
await max_out_size(conn) await max_out_size(conn)
return return
# manual 模式下不打断正在播放的内容 # manual Do not interrupt the content being played in mode
if conn.client_is_speaking and conn.client_listen_mode != "manual": if conn.client_is_speaking and conn.client_listen_mode != "manual":
await handleAbortMessage(conn) await handleAbortMessage(conn)
# 首先进行意图分析,使用实际文本内容 # Do intent analysis first, using actual text content
intent_handled = await handle_user_intent(conn, actual_text) intent_handled = await handle_user_intent(conn, actual_text)
if intent_handled: if intent_handled:
# 如果意图已被处理,不再进行聊天 # If the intent has been processed, the chat will no longer proceed
return return
# 意图未被处理,继续常规聊天流程,使用实际文本内容 # Intent not processed, continue the regular chat flow with actual text content
await send_stt_message(conn, actual_text) await send_stt_message(conn, actual_text)
conn.executor.submit(conn.chat, actual_text) conn.executor.submit(conn.chat, actual_text)
@ -94,7 +94,7 @@ async def no_voice_close_connect(conn, have_voice):
if have_voice: if have_voice:
conn.last_activity_time = time.time() * 1000 conn.last_activity_time = time.time() * 1000
return return
# 只有在已经初始化过时间戳的情况下才进行超时检查 # Only perform timeout checks if the timestamp has been initialized
if conn.last_activity_time > 0.0: if conn.last_activity_time > 0.0:
no_voice_time = time.time() * 1000 - conn.last_activity_time no_voice_time = time.time() * 1000 - conn.last_activity_time
close_connection_no_voice_time = int( close_connection_no_voice_time = int(
@ -108,19 +108,19 @@ async def no_voice_close_connect(conn, have_voice):
conn.client_abort = False conn.client_abort = False
end_prompt = conn.config.get("end_prompt", {}) end_prompt = conn.config.get("end_prompt", {})
if end_prompt and end_prompt.get("enable", True) is False: if end_prompt and end_prompt.get("enable", True) is False:
conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语") conn.logger.bind(tag=TAG).info("End the conversation without sending an end message")
await conn.close() await conn.close()
return return
prompt = end_prompt.get("prompt") prompt = end_prompt.get("prompt")
if not prompt: if not prompt:
prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!" prompt = "Please end this conversation with words of 'Time flies so fast' and words that are full of emotion and reluctance. !"
await startToChat(conn, prompt) await startToChat(conn, prompt)
async def max_out_size(conn): async def max_out_size(conn):
# 播放超出最大输出字数的提示 # Play prompt exceeding maximum output word count
conn.client_abort = False conn.client_abort = False
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!" text = "Sorry, I'm busy with something right now. We'll talk again at this time tomorrow. We've made an appointment! See you tomorrow, bye!"
await send_stt_message(conn, text) await send_stt_message(conn, text)
file_path = "config/assets/max_output_size.wav" file_path = "config/assets/max_output_size.wav"
opus_packets = audio_to_data(file_path) opus_packets = audio_to_data(file_path)
@ -130,23 +130,23 @@ async def max_out_size(conn):
async def check_bind_device(conn): async def check_bind_device(conn):
if conn.bind_code: if conn.bind_code:
# 确保bind_code是6位数字 # Make sure the bind code is 6 digits
if len(conn.bind_code) != 6: if len(conn.bind_code) != 6:
conn.logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}") conn.logger.bind(tag=TAG).error(f"Invalid binding code format: {conn.bind_code}")
text = "绑定码格式错误,请检查配置。" text = "The binding code format is incorrect, please check the configuration."
await send_stt_message(conn, text) await send_stt_message(conn, text)
return return
text = f"请登录控制面板,输入{conn.bind_code},绑定设备。" text = f"Please log in to the control panel and enter {conn.bind }code to bind the device."
await send_stt_message(conn, text) await send_stt_message(conn, text)
# 播放提示音 # Play tone
music_path = "config/assets/bind_code.wav" music_path = "config/assets/bind_code.wav"
opus_packets = audio_to_data(music_path) opus_packets = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text)) conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# 逐个播放数字 # Play numbers one by one
for i in range(6): # 确保只播放6位数字 for i in range(6): # Make sure to only play 6 digits
try: try:
digit = conn.bind_code[i] digit = conn.bind_code[i]
num_path = f"config/assets/bind_code/{digit}.wav" num_path = f"config/assets/bind_code/{digit}.wav"
@ -157,9 +157,9 @@ async def check_bind_device(conn):
continue continue
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None)) conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
else: else:
# 播放未绑定提示 # Play unbound prompt
conn.client_abort = False conn.client_abort = False
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。" text = f"The version information of the device was not found. Please configure the OTA address correctly and then recompile the firmware."
await send_stt_message(conn, text) await send_stt_message(conn, text)
music_path = "config/assets/bind_not_found.wav" music_path = "config/assets/bind_not_found.wav"
opus_packets = audio_to_data(music_path) opus_packets = audio_to_data(music_path)

View file

@ -1,12 +1,12 @@
""" """
TTS上报功能已集成到ConnectionHandler类中。 The TTS reporting function has been integrated into the ConnectionHandler class.
上报功能包括: Reporting functions include:
1. 每个连接对象拥有自己的上报队列和处理线程 1. Each connection object has its own reporting queue and processing thread
2. 上报线程的生命周期与连接对象绑定 2. The life cycle of the reporting thread is bound to the connection object
3. 使用ConnectionHandler.enqueue_tts_report方法进行上报 3. Use ConnectionHandler.enqueue_tts_report method to report
具体实现请参考core/connection.py中的相关代码。 For specific implementation, please refer to the relevant code in core/connection.py.
""" """
import time import time
@ -19,21 +19,21 @@ TAG = __name__
def report(conn, type, text, opus_data, report_time): def report(conn, type, text, opus_data, report_time):
"""执行聊天记录上报操作 """Execute chat record reporting operation
Args: Args:
conn: 连接对象 conn: connection object
type: 上报类型,1为用户,2为智能体 type: reporting type, 1 is user, 2 is agent
text: 合成文本 text: synthetic text
opus_data: opus音频数据 opus_data: opus audio data
report_time: 上报时间 report_time: report time
""" """
try: try:
if opus_data: if opus_data:
audio_data = opus_to_wav(conn, opus_data) audio_data = opus_to_wav(conn, opus_data)
else: else:
audio_data = None audio_data = None
# 执行上报 # Execute reporting
manage_report( manage_report(
mac_address=conn.device_id, mac_address=conn.device_id,
session_id=conn.session_id, session_id=conn.session_id,
@ -43,20 +43,20 @@ def report(conn, type, text, opus_data, report_time):
report_time=report_time, report_time=report_time,
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}") conn.logger.bind(tag=TAG).error(f"Failed to report chat history: {e}")
def opus_to_wav(conn, opus_data): def opus_to_wav(conn, opus_data):
"""将Opus数据转换为WAV格式的字节流 """Convert Opus data to byte stream in WAV format
Args: Args:
output_dir: 输出目录(保留参数以保持接口兼容) output_dir: output directory (parameters retained to maintain interface compatibility)
opus_data: opus音频数据 opus_data: opus audio data
Returns: Returns:
bytes: WAV格式的音频数据 bytes: audio data in WAV format
""" """
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 decoder = opuslib_next.Decoder(16000, 1) #16kHz, mono
pcm_data = [] pcm_data = []
for opus_packet in opus_data: for opus_packet in opus_data:
@ -64,16 +64,16 @@ def opus_to_wav(conn, opus_data):
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
pcm_data.append(pcm_frame) pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e: except opuslib_next.OpusError as e:
conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) conn.logger.bind(tag=TAG).error(f"Opus decoding error: {e}", exc_info=True)
if not pcm_data: if not pcm_data:
raise ValueError("没有有效的PCM数据") raise ValueError("No valid pcm datacm data")
# 创建WAV文件头 # Create wav file header
pcm_data_bytes = b"".join(pcm_data) pcm_data_bytes = b"".join(pcm_data)
num_samples = len(pcm_data_bytes) // 2 # 16-bit samples num_samples = len(pcm_data_bytes) // 2 # 16-bit samples
# WAV文件头 # Wav file header
wav_header = bytearray() wav_header = bytearray()
wav_header.extend(b"RIFF") # ChunkID wav_header.extend(b"RIFF") # ChunkID
wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize
@ -89,7 +89,7 @@ def opus_to_wav(conn, opus_data):
wav_header.extend(b"data") # Subchunk2ID wav_header.extend(b"data") # Subchunk2ID
wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size
# 返回完整的WAV数据 # Return complete wav data
return bytes(wav_header) + pcm_data_bytes return bytes(wav_header) + pcm_data_bytes
@ -98,27 +98,27 @@ def enqueue_tts_report(conn, text, opus_data):
return return
if conn.chat_history_conf == 0: if conn.chat_history_conf == 0:
return return
"""将TTS数据加入上报队列 """Add TTS data to the reporting queue
Args: Args:
conn: 连接对象 conn: connection object
text: 合成文本 text: synthetic text
opus_data: opus音频数据 opus_data: opus audio data
""" """
try: try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径 # Use a queue of connection objects, passing in text and binary data instead of file paths
if conn.chat_history_conf == 2: if conn.chat_history_conf == 2:
conn.report_queue.put((2, text, opus_data, int(time.time()))) conn.report_queue.put((2, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " f"TTS data has been added to the reporting queue: {conn.device_id}, audio size: {len(opus_data)}"
) )
else: else:
conn.report_queue.put((2, text, None, int(time.time()))) conn.report_queue.put((2, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频" f"TTS data has been added to the reporting queue: {conn.device_id}, audio is not reported"
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}") conn.logger.bind(tag=TAG).error(f"Failed to join tts reporting queue: {text}, {e}")
def enqueue_asr_report(conn, text, opus_data): def enqueue_asr_report(conn, text, opus_data):
@ -126,24 +126,24 @@ def enqueue_asr_report(conn, text, opus_data):
return return
if conn.chat_history_conf == 0: if conn.chat_history_conf == 0:
return return
"""将ASR数据加入上报队列 """Add ASR data to the reporting queue
Args: Args:
conn: 连接对象 conn: connection object
text: 合成文本 text: synthetic text
opus_data: opus音频数据 opus_data: opus audio data
""" """
try: try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径 # Use a queue of connection objects, passing in text and binary data instead of file paths
if conn.chat_history_conf == 2: if conn.chat_history_conf == 2:
conn.report_queue.put((1, text, opus_data, int(time.time()))) conn.report_queue.put((1, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " f"ASR data has been added to the reporting queue: {conn.device_id}, audio size: {len(opus_data)}"
) )
else: else:
conn.report_queue.put((1, text, None, int(time.time()))) conn.report_queue.put((1, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频" f"ASR data has been added to the reporting queue: {conn.device_id}, audio is not reported"
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}") conn.logger.bind(tag=TAG).debug(f"Failed to join the asr reporting queue: {text}, {e}")

View file

@ -10,7 +10,7 @@ TAG = __name__
async def sendAudioMessage(conn, sentenceType, audios, text): async def sendAudioMessage(conn, sentenceType, audios, text):
if conn.tts.tts_audio_first_sentence: if conn.tts.tts_audio_first_sentence:
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}") conn.logger.bind(tag=TAG).info(f"Send the first voice message: {text}")
conn.tts.tts_audio_first_sentence = False conn.tts.tts_audio_first_sentence = False
await send_tts_message(conn, "start", None) await send_tts_message(conn, "start", None)
@ -18,11 +18,11 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await send_tts_message(conn, "sentence_start", text) await send_tts_message(conn, "sentence_start", text)
await sendAudio(conn, audios) await sendAudio(conn, audios)
# 发送句子开始消息 # Send sentence start message
if sentenceType is not SentenceType.MIDDLE: if sentenceType is not SentenceType.MIDDLE:
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}") conn.logger.bind(tag=TAG).info(f"Send audio message: {sentenceType}, {text}")
# 发送结束消息(如果是最后一个文本) # Send end message (if last text)
if conn.llm_finish_task and sentenceType == SentenceType.LAST: if conn.llm_finish_task and sentenceType == SentenceType.LAST:
await send_tts_message(conn, "stop", None) await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False conn.client_is_speaking = False
@ -32,60 +32,60 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
def calculate_timestamp_and_sequence(conn, start_time, packet_index, frame_duration=60): def calculate_timestamp_and_sequence(conn, start_time, packet_index, frame_duration=60):
""" """
计算音频数据包的时间戳和序列号 Calculate timestamp and sequence number of audio packets
Args: Args:
conn: 连接对象 conn: connection object
start_time: 起始时间(性能计数器值) start_time: start time (performance counter value)
packet_index: 数据包索引 packet_index: packet index
frame_duration: 帧时长(毫秒),匹配 Opus 编码 frame_duration: frame duration (milliseconds), matching Opus encoding
Returns: Returns:
tuple: (timestamp, sequence) tuple: (timestamp, sequence)
""" """
# 计算时间戳(使用播放位置计算) # Calculate timestamp (calculated using playback position)
timestamp = int((start_time + packet_index * frame_duration / 1000) * 1000) % ( timestamp = int((start_time + packet_index * frame_duration / 1000) * 1000) % (
2**32 2**32
) )
# 计算序列号 # Calculate serial number
if hasattr(conn, "audio_flow_control"): if hasattr(conn, "audio_flow_control"):
sequence = conn.audio_flow_control["sequence"] sequence = conn.audio_flow_control["sequence"]
else: else:
sequence = packet_index # 如果没有流控状态,直接使用索引 sequence = packet_index # If there is no flow control state, use the index directly
return timestamp, sequence return timestamp, sequence
async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence): async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
""" """
发送带16字节头部的opus数据包给mqtt_gateway Send opus packet with 16-byte header to mqtt_gateway
Args: Args:
conn: 连接对象 conn: connection object
opus_packet: opus数据包 opus_packet: opus data packet
timestamp: 时间戳 timestamp: timestamp
sequence: 序列号 sequence: sequence number
""" """
# 为opus数据包添加16字节头部 # Add 16-byte header to opus packets
header = bytearray(16) header = bytearray(16)
header[0] = 1 # type header[0] = 1 # type
header[2:4] = len(opus_packet).to_bytes(2, "big") # payload length header[2:4] = len(opus_packet).to_bytes(2, "big") # payload length
header[4:8] = sequence.to_bytes(4, "big") # sequence header[4:8] = sequence.to_bytes(4, "big") # sequence
header[8:12] = timestamp.to_bytes(4, "big") # 时间戳 header[8:12] = timestamp.to_bytes(4, "big") # Timestamp
header[12:16] = len(opus_packet).to_bytes(4, "big") # opus长度 header[12:16] = len(opus_packet).to_bytes(4, "big") # Opus length
# 发送包含头部的完整数据包 # Send complete packet including headers
complete_packet = bytes(header) + opus_packet complete_packet = bytes(header) + opus_packet
await conn.websocket.send(complete_packet) await conn.websocket.send(complete_packet)
# 播放音频 # Play audio
async def sendAudio(conn, audios, frame_duration=60): async def sendAudio(conn, audios, frame_duration=60):
""" """
发送单个opus包,支持流控 Send a single opus packet, support flow control
Args: Args:
conn: 连接对象 conn: connection object
opus_packet: 单个opus数据包 opus_packet: single opus data packet
pre_buffer: 快速发送音频 pre_buffer: Send audio quickly
frame_duration: 帧时长(毫秒),匹配 Opus 编码 frame_duration: frame duration (milliseconds), matching Opus encoding
""" """
if audios is None or len(audios) == 0: if audios is None or len(audios) == 0:
return return
@ -96,18 +96,18 @@ async def sendAudio(conn, audios, frame_duration=60):
conn.last_activity_time = time.time() * 1000 conn.last_activity_time = time.time() * 1000
# 获取或初始化流控状态 # Get or initialize flow control status
if not hasattr(conn, "audio_flow_control"): if not hasattr(conn, "audio_flow_control"):
conn.audio_flow_control = { conn.audio_flow_control = {
"last_send_time": 0, "last_send_time": 0,
"packet_count": 0, "packet_count": 0,
"start_time": time.perf_counter(), "start_time": time.perf_counter(),
"sequence": 0, # 添加序列号 "sequence": 0, # Add serial number
} }
flow_control = conn.audio_flow_control flow_control = conn.audio_flow_control
current_time = time.perf_counter() current_time = time.perf_counter()
# 计算预期发送时间 # Calculate expected delivery time
expected_time = flow_control["start_time"] + ( expected_time = flow_control["start_time"] + (
flow_control["packet_count"] * frame_duration / 1000 flow_control["packet_count"] * frame_duration / 1000
) )
@ -115,56 +115,56 @@ async def sendAudio(conn, audios, frame_duration=60):
if delay > 0: if delay > 0:
await asyncio.sleep(delay) await asyncio.sleep(delay)
else: else:
# 纠正误差 # correct errors
flow_control["start_time"] += abs(delay) flow_control["start_time"] += abs(delay)
if conn.conn_from_mqtt_gateway: if conn.conn_from_mqtt_gateway:
# 计算时间戳和序列号 # Calculate timestamps and sequence numbers
timestamp, sequence = calculate_timestamp_and_sequence( timestamp, sequence = calculate_timestamp_and_sequence(
conn, conn,
flow_control["start_time"], flow_control["start_time"],
flow_control["packet_count"], flow_control["packet_count"],
frame_duration, frame_duration,
) )
# 调用通用函数发送带头部的数据包 # Call a common function to send a packet with header
await _send_to_mqtt_gateway(conn, audios, timestamp, sequence) await _send_to_mqtt_gateway(conn, audios, timestamp, sequence)
else: else:
# 直接发送opus数据包,不添加头部 # Send opus packets directly without adding headers
await conn.websocket.send(audios) await conn.websocket.send(audios)
# 更新流控状态 # Update flow control status
flow_control["packet_count"] += 1 flow_control["packet_count"] += 1
flow_control["sequence"] += 1 flow_control["sequence"] += 1
flow_control["last_send_time"] = time.perf_counter() flow_control["last_send_time"] = time.perf_counter()
else: else:
# 文件型音频走普通播放 # File-type audio is played normally
start_time = time.perf_counter() start_time = time.perf_counter()
play_position = 0 play_position = 0
# 执行预缓冲 # Perform prebuffering
pre_buffer_frames = min(3, len(audios)) pre_buffer_frames = min(3, len(audios))
for i in range(pre_buffer_frames): for i in range(pre_buffer_frames):
if conn.conn_from_mqtt_gateway: if conn.conn_from_mqtt_gateway:
# 计算时间戳和序列号 # Calculate timestamps and sequence numbers
timestamp, sequence = calculate_timestamp_and_sequence( timestamp, sequence = calculate_timestamp_and_sequence(
conn, start_time, i, frame_duration conn, start_time, i, frame_duration
) )
# 调用通用函数发送带头部的数据包 # Call a common function to send a packet with header
await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence) await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence)
else: else:
# 直接发送预缓冲包,不添加头部 # Send the pre-buffered packet directly without adding headers
await conn.websocket.send(audios[i]) await conn.websocket.send(audios[i])
remaining_audios = audios[pre_buffer_frames:] remaining_audios = audios[pre_buffer_frames:]
# 播放剩余音频帧 # Play remaining audio frames
for i, opus_packet in enumerate(remaining_audios): for i, opus_packet in enumerate(remaining_audios):
if conn.client_abort: if conn.client_abort:
break break
# 重置没有声音的状态 # Reset no sound status
conn.last_activity_time = time.time() * 1000 conn.last_activity_time = time.time() * 1000
# 计算预期发送时间 # Calculate expected delivery time
expected_time = start_time + (play_position / 1000) expected_time = start_time + (play_position / 1000)
current_time = time.perf_counter() current_time = time.perf_counter()
delay = expected_time - current_time delay = expected_time - current_time
@ -172,31 +172,31 @@ async def sendAudio(conn, audios, frame_duration=60):
await asyncio.sleep(delay) await asyncio.sleep(delay)
if conn.conn_from_mqtt_gateway: if conn.conn_from_mqtt_gateway:
# 计算时间戳和序列号(使用当前的数据包索引确保连续性) # Calculate timestamps and sequence numbers (using current packet index to ensure continuity)
packet_index = pre_buffer_frames + i packet_index = pre_buffer_frames + i
timestamp, sequence = calculate_timestamp_and_sequence( timestamp, sequence = calculate_timestamp_and_sequence(
conn, start_time, packet_index, frame_duration conn, start_time, packet_index, frame_duration
) )
# 调用通用函数发送带头部的数据包 # Call a common function to send a packet with header
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence) await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
else: else:
# 直接发送opus数据包,不添加头部 # Send opus packets directly without adding headers
await conn.websocket.send(opus_packet) await conn.websocket.send(opus_packet)
play_position += frame_duration play_position += frame_duration
async def send_tts_message(conn, state, text=None): async def send_tts_message(conn, state, text=None):
"""发送 TTS 状态消息""" """Send TTS status message"""
if text is None and state == "sentence_start": if text is None and state == "sentence_start":
return return
message = {"type": "tts", "state": state, "session_id": conn.session_id} message = {"type": "tts", "state": state, "session_id": conn.session_id}
if text is not None: if text is not None:
message["text"] = textUtils.check_emoji(text) message["text"] = textUtils.check_emoji(text)
# TTS播放结束 # Tts play ends
if state == "stop": if state == "stop":
# 播放提示音 # Play tone
tts_notify = conn.config.get("enable_stop_tts_notify", False) tts_notify = conn.config.get("enable_stop_tts_notify", False)
if tts_notify: if tts_notify:
stop_tts_notify_voice = conn.config.get( stop_tts_notify_voice = conn.config.get(
@ -204,34 +204,34 @@ async def send_tts_message(conn, state, text=None):
) )
audios = audio_to_data(stop_tts_notify_voice, is_opus=True) audios = audio_to_data(stop_tts_notify_voice, is_opus=True)
await sendAudio(conn, audios) await sendAudio(conn, audios)
# 清除服务端讲话状态 # Clear server talk status
conn.clearSpeakStatus() conn.clearSpeakStatus()
# 发送消息到客户端 # Send message to client
await conn.websocket.send(json.dumps(message)) await conn.websocket.send(json.dumps(message))
async def send_stt_message(conn, text): async def send_stt_message(conn, text):
"""发送 STT 状态消息""" """Send STT status message"""
end_prompt_str = conn.config.get("end_prompt", {}).get("prompt") end_prompt_str = conn.config.get("end_prompt", {}).get("prompt")
if end_prompt_str and end_prompt_str == text: if end_prompt_str and end_prompt_str == text:
await send_tts_message(conn, "start") await send_tts_message(conn, "start")
return return
# 解析JSON格式,提取实际的用户说话内容 # Parse the json format and extract the actual user speech content
display_text = text display_text = text
try: try:
# 尝试解析JSON格式 # Try to parse json format
if text.strip().startswith("{") and text.strip().endswith("}"): if text.strip().startswith("{") and text.strip().endswith("}"):
parsed_data = json.loads(text) parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data: if isinstance(parsed_data, dict) and "content" in parsed_data:
# 如果是包含说话人信息的JSON格式,只显示content部分 # If it is in json format containing speaker information, only the content part will be displayed.
display_text = parsed_data["content"] display_text = parsed_data["content"]
# 保存说话人信息到conn对象 # Save speaker information to conn object
if "speaker" in parsed_data: if "speaker" in parsed_data:
conn.current_speaker = parsed_data["speaker"] conn.current_speaker = parsed_data["speaker"]
except (json.JSONDecodeError, TypeError): except (json.JSONDecodeError, TypeError):
# 如果不是JSON格式,直接使用原始文本 # If it is not in json format, use the original text directly.
display_text = text display_text = text
stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text) stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
await conn.websocket.send( await conn.websocket.send(

View file

@ -3,12 +3,12 @@ from core.handle.textMessageProcessor import TextMessageProcessor
TAG = __name__ TAG = __name__
# 全局处理器注册表 # Global Processor Registry
message_registry = TextMessageHandlerRegistry() message_registry = TextMessageHandlerRegistry()
# 创建全局消息处理器实例 # Create a global message handler instance
message_processor = TextMessageProcessor(message_registry) message_processor = TextMessageProcessor(message_registry)
async def handleTextMessage(conn, message): async def handleTextMessage(conn, message):
"""处理文本消息""" """Process text messages"""
await message_processor.process_message(conn, message) await message_processor.process_message(conn, message)

View file

@ -6,7 +6,7 @@ from core.handle.textMessageType import TextMessageType
class AbortTextMessageHandler(TextMessageHandler): class AbortTextMessageHandler(TextMessageHandler):
"""Abort消息处理器""" """Abort message handler"""
@property @property
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:

View file

@ -6,7 +6,7 @@ from core.handle.textMessageType import TextMessageType
class HelloTextMessageHandler(TextMessageHandler): class HelloTextMessageHandler(TextMessageHandler):
"""Hello消息处理器""" """Hello message handler"""
@property @property
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:

View file

@ -7,7 +7,7 @@ from core.providers.tools.device_iot import handleIotStatus, handleIotDescriptor
class IotTextMessageHandler(TextMessageHandler): class IotTextMessageHandler(TextMessageHandler):
"""IOT消息处理器""" """IoT message processor"""
@property @property
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:

View file

@ -11,7 +11,7 @@ from core.utils.util import remove_punctuation_and_length
TAG = __name__ TAG = __name__
class ListenTextMessageHandler(TextMessageHandler): class ListenTextMessageHandler(TextMessageHandler):
"""Listen消息处理器""" """Listen message handler"""
@property @property
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
@ -21,7 +21,7 @@ class ListenTextMessageHandler(TextMessageHandler):
if "mode" in msg_json: if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"] conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"客户端拾音模式:{conn.client_listen_mode}" f"Client pickup mode:{conn.client_listen_mode}"
) )
if msg_json["state"] == "start": if msg_json["state"] == "start":
conn.client_have_voice = True conn.client_have_voice = True
@ -36,28 +36,28 @@ class ListenTextMessageHandler(TextMessageHandler):
conn.asr_audio.clear() conn.asr_audio.clear()
if "text" in msg_json: if "text" in msg_json:
conn.last_activity_time = time.time() * 1000 conn.last_activity_time = time.time() * 1000
original_text = msg_json["text"] # 保留原始文本 original_text = msg_json["text"] # Keep original text
filtered_len, filtered_text = remove_punctuation_and_length( filtered_len, filtered_text = remove_punctuation_and_length(
original_text original_text
) )
# 识别是否是唤醒词 # Identify whether it is a wake word
is_wakeup_words = filtered_text in conn.config.get("wakeup_words") is_wakeup_words = filtered_text in conn.config.get("wakeup_words")
# 是否开启唤醒词回复 # Whether to enable wake word reply
enable_greeting = conn.config.get("enable_greeting", True) enable_greeting = conn.config.get("enable_greeting", True)
if is_wakeup_words and not enable_greeting: if is_wakeup_words and not enable_greeting:
# 如果是唤醒词,且关闭了唤醒词回复,就不用回答 # If it is a wake word and wake word reply is turned off, there is no need to answer.
await send_stt_message(conn, original_text) await send_stt_message(conn, original_text)
await send_tts_message(conn, "stop", None) await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False conn.client_is_speaking = False
elif is_wakeup_words: elif is_wakeup_words:
conn.just_woken_up = True conn.just_woken_up = True
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据) # Report pure text data (reuse the asr reporting function, but do not provide audio data)
enqueue_asr_report(conn, "嘿,你好呀", []) enqueue_asr_report(conn, "Hey, how are you?", [])
await startToChat(conn, "嘿,你好呀") await startToChat(conn, "Hey, how are you?")
else: else:
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据) # Report pure text data (reuse the asr reporting function, but do not provide audio data)
enqueue_asr_report(conn, original_text, []) enqueue_asr_report(conn, original_text, [])
# 否则需要LLM对文字内容进行答复 # Otherwise, llm is required to reply to the text content.
await startToChat(conn, original_text) await startToChat(conn, original_text)

View file

@ -7,7 +7,7 @@ from core.providers.tools.device_mcp import handle_mcp_message
class McpTextMessageHandler(TextMessageHandler): class McpTextMessageHandler(TextMessageHandler):
"""MCP消息处理器""" """Mcp message processor"""
@property @property
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:

View file

@ -9,42 +9,42 @@ from core.providers.tools.device_mcp import handle_mcp_message
TAG = __name__ TAG = __name__
class ServerTextMessageHandler(TextMessageHandler): class ServerTextMessageHandler(TextMessageHandler):
"""MCP消息处理器""" """Mcp message processor"""
@property @property
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
return TextMessageType.SERVER return TextMessageType.SERVER
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
# 如果配置是从API读取的,则需要验证secret # If the configuration is read from the api, the secret needs to be verified
if not conn.read_config_from_api: if not conn.read_config_from_api:
return return
# 获取post请求的secret # Get the secret of the post request
post_secret = msg_json.get("content", {}).get("secret", "") post_secret = msg_json.get("content", {}).get("secret", "")
secret = conn.config["manager-api"].get("secret", "") secret = conn.config["manager-api"].get("secret", "")
# 如果secret不匹配,则返回 # If secret does not match, return
if post_secret != secret: if post_secret != secret:
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": "服务器密钥验证失败", "message": "Server key verification failed",
} }
) )
) )
return return
# 动态更新配置 # Dynamically update configuration
if msg_json["action"] == "update_config": if msg_json["action"] == "update_config":
try: try:
# 更新WebSocketServer的配置 # Update web socket server configuration
if not conn.server: if not conn.server:
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": "无法获取服务器实例", "message": "Unable to get server instance",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
@ -57,36 +57,36 @@ class ServerTextMessageHandler(TextMessageHandler):
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": "更新服务器配置失败", "message": "Failed to update server configuration",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
) )
return return
# 发送成功响应 # Send successful response
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "success", "status": "success",
"message": "配置更新成功", "message": "Configuration update successful",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}") conn.logger.bind(tag=TAG).error(f"Failed to update configuration: {str(e)}")
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": f"更新配置失败: {str(e)}", "message": f"Failed to update configuration: {str(e)}",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
) )
# 重启服务器 # Restart the server
elif msg_json["action"] == "restart": elif msg_json["action"] == "restart":
await conn.handle_restart(msg_json) await conn.handle_restart(msg_json)

View file

@ -7,15 +7,15 @@ TAG = __name__
class TextMessageHandler(ABC): class TextMessageHandler(ABC):
"""消息处理器抽象基类""" """Message processor abstract base class"""
@abstractmethod @abstractmethod
async def handle(self, conn, msg_json: Dict[str, Any]) -> None: async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
"""处理消息的抽象方法""" """Abstract methods for processing messages"""
pass pass
@property @property
@abstractmethod @abstractmethod
def message_type(self) -> TextMessageType: def message_type(self) -> TextMessageType:
"""返回处理的消息类型""" """Returns the message type processed"""
pass pass

View file

@ -12,14 +12,14 @@ TAG = __name__
class TextMessageHandlerRegistry: class TextMessageHandlerRegistry:
"""消息处理器注册表""" """Message handler registry"""
def __init__(self): def __init__(self):
self._handlers: Dict[str, TextMessageHandler] = {} self._handlers: Dict[str, TextMessageHandler] = {}
self._register_default_handlers() self._register_default_handlers()
def _register_default_handlers(self) -> None: def _register_default_handlers(self) -> None:
"""注册默认的消息处理器""" """Register default message handler"""
handlers = [ handlers = [
HelloTextMessageHandler(), HelloTextMessageHandler(),
AbortTextMessageHandler(), AbortTextMessageHandler(),
@ -33,13 +33,13 @@ class TextMessageHandlerRegistry:
self.register_handler(handler) self.register_handler(handler)
def register_handler(self, handler: TextMessageHandler) -> None: def register_handler(self, handler: TextMessageHandler) -> None:
"""注册消息处理器""" """Register message handler"""
self._handlers[handler.message_type.value] = handler self._handlers[handler.message_type.value] = handler
def get_handler(self, message_type: str) -> Optional[TextMessageHandler]: def get_handler(self, message_type: str) -> Optional[TextMessageHandler]:
"""获取消息处理器""" """Get message handler"""
return self._handlers.get(message_type) return self._handlers.get(message_type)
def get_supported_types(self) -> list: def get_supported_types(self) -> list:
"""获取支持的消息类型""" """Get supported message types"""
return list(self._handlers.keys()) return list(self._handlers.keys())

View file

@ -6,36 +6,36 @@ TAG = __name__
class TextMessageProcessor: class TextMessageProcessor:
"""消息处理器主类""" """Message processor main class"""
def __init__(self, registry: TextMessageHandlerRegistry): def __init__(self, registry: TextMessageHandlerRegistry):
self.registry = registry self.registry = registry
async def process_message(self, conn, message: str) -> None: async def process_message(self, conn, message: str) -> None:
"""处理消息的主入口""" """Main entry point for processing messages"""
try: try:
# 解析JSON消息 # Parse json message
msg_json = json.loads(message) msg_json = json.loads(message)
# 处理JSON消息 # Process json messages
if isinstance(msg_json, dict): if isinstance(msg_json, dict):
message_type = msg_json.get("type") message_type = msg_json.get("type")
# 记录日志 # logging
conn.logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}") conn.logger.bind(tag=TAG).info(f"receive{message_type}information:{message}")
# 获取并执行处理器 # Get and execute the processor
handler = self.registry.get_handler(message_type) handler = self.registry.get_handler(message_type)
if handler: if handler:
await handler.handle(conn, msg_json) await handler.handle(conn, msg_json)
else: else:
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}") conn.logger.bind(tag=TAG).error(f"Unknown type message received:{message}")
# 处理纯数字消息 # Handle purely digital messages
elif isinstance(msg_json, int): elif isinstance(msg_json, int):
conn.logger.bind(tag=TAG).info(f"收到数字消息:{message}") conn.logger.bind(tag=TAG).info(f"Receive digital message:{message}")
await conn.websocket.send(message) await conn.websocket.send(message)
except json.JSONDecodeError: except json.JSONDecodeError:
# 非JSON消息直接转发 # Non-json messages are forwarded directly
conn.logger.bind(tag=TAG).error(f"解析到错误的消息:{message}") conn.logger.bind(tag=TAG).error(f"Parsed to error message:{message}")
await conn.websocket.send(message) await conn.websocket.send(message)

View file

@ -2,7 +2,7 @@ from enum import Enum
class TextMessageType(Enum): class TextMessageType(Enum):
"""消息类型枚举""" """Message type enum"""
HELLO = "hello" HELLO = "hello"
ABORT = "abort" ABORT = "abort"
LISTEN = "listen" LISTEN = "listen"