Files
xiaozhi-esp32-server/main/xiaozhi-server/core/handle/helloHandle.py
T

157 lines
5.1 KiB
Python
Raw Normal View History

2025-09-02 11:18:04 +08:00
import time
2025-02-02 23:01:14 +08:00
import json
import uuid
2025-09-02 11:18:04 +08:00
import random
2025-03-23 22:02:13 +08:00
import asyncio
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from core.connection import ConnectionHandler
2025-09-02 11:18:04 +08:00
from core.utils.dialogue import Message
2025-09-02 14:34:26 +08:00
from core.utils.util import audio_to_data
2025-09-02 11:18:04 +08:00
from core.providers.tts.dto.dto import SentenceType
from core.utils.wakeup_word import WakeupWordsConfig
2025-10-13 16:47:05 +08:00
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
2025-09-02 11:18:04 +08:00
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
from core.providers.tools.device_mcp import MCPClient, send_mcp_initialize_message
2025-02-02 23:01:14 +08:00
2025-04-12 17:36:04 +08:00
TAG = __name__
2025-02-02 23:01:14 +08:00
2025-09-02 11:18:04 +08:00
WAKEUP_CONFIG = {
2025-10-12 23:24:43 +08:00
"refresh_time": 10,
2025-10-11 15:48:27 +08:00
"responses": [
2025-10-12 23:24:43 +08:00
"我一直都在呢,您请说。",
"在的呢,请随时吩咐我。",
"来啦来啦,请告诉我吧。",
"您请说,我正听着。",
"请您讲话,我准备好了。",
"请您说出指令吧。",
"我认真听着呢,请讲。",
"请问您需要什么帮助?",
"我在这里,等候您的指令。",
2025-10-11 15:48:27 +08:00
],
2025-09-02 11:18:04 +08:00
}
# 创建全局的唤醒词配置管理器
wakeup_words_config = WakeupWordsConfig()
# 用于防止并发调用wakeupWordsResponse的锁
_wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn: "ConnectionHandler", msg_json):
2025-05-06 14:57:29 +08:00
"""处理hello消息"""
audio_params = msg_json.get("audio_params")
if audio_params:
format = audio_params.get("format")
conn.logger.bind(tag=TAG).debug(f"客户端音频格式: {format}")
2025-05-06 14:57:29 +08:00
conn.audio_format = format
2025-05-08 11:11:28 +08:00
conn.welcome_msg["audio_params"] = audio_params
2025-05-28 11:49:18 +08:00
features = msg_json.get("features")
if features:
conn.logger.bind(tag=TAG).debug(f"客户端特性: {features}")
2025-05-28 11:49:18 +08:00
conn.features = features
2025-05-28 18:32:15 +08:00
if features.get("mcp"):
conn.logger.bind(tag=TAG).debug("客户端支持MCP")
2025-05-29 13:42:31 +08:00
conn.mcp_client = MCPClient()
2025-05-28 18:32:15 +08:00
# 发送初始化
2025-05-29 13:42:31 +08:00
asyncio.create_task(send_mcp_initialize_message(conn))
2025-05-06 14:57:29 +08:00
2025-09-02 11:18:04 +08:00
await conn.websocket.send(json.dumps(conn.welcome_msg))
async def checkWakeupWords(conn: "ConnectionHandler", text):
2025-09-02 11:18:04 +08:00
enable_wakeup_words_response_cache = conn.config[
"enable_wakeup_words_response_cache"
]
# 等待tts初始化,最多等待3秒
start_time = time.time()
while time.time() - start_time < 3:
if conn.tts:
break
await asyncio.sleep(0.1)
else:
return False
if not enable_wakeup_words_response_cache:
2025-09-02 11:18:04 +08:00
return False
_, filtered_text = remove_punctuation_and_length(text)
if filtered_text not in conn.config.get("wakeup_words"):
return False
conn.just_woken_up = True
2025-10-13 16:47:05 +08:00
await send_tts_message(conn, "start")
2025-09-02 11:18:04 +08:00
# 获取当前音色
voice = getattr(conn.tts, "voice", "default")
if not voice:
voice = "default"
# 获取唤醒词回复配置
response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"):
response = {
"voice": "default",
2025-10-11 15:48:27 +08:00
"file_path": "config/assets/wakeup_words_short.wav",
2025-09-02 11:18:04 +08:00
"time": 0,
2025-10-11 15:48:27 +08:00
"text": "我在这里哦!",
2025-09-02 11:18:04 +08:00
}
# 获取音频数据
opus_packets = await audio_to_data(response.get("file_path"), use_cache=False)
2025-09-02 11:18:04 +08:00
# 播放唤醒词回复
conn.client_abort = False
# 将唤醒词回复视为新会话,生成新的 sentence_id,确保流控器重置
conn.sentence_id = str(uuid.uuid4().hex)
2025-09-02 11:18:04 +08:00
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None)
# 补充对话
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
# 检查是否需要更新唤醒词回复
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn))
return True
async def wakeupWordsResponse(conn: "ConnectionHandler"):
2025-10-11 15:48:27 +08:00
if not conn.tts:
2025-09-02 11:18:04 +08:00
return
try:
# 尝试获取锁,如果获取不到就返回
if not await _wakeup_response_lock.acquire():
return
2025-10-11 15:48:27 +08:00
# 从预定义回复列表中随机选择一个回复
result = random.choice(WAKEUP_CONFIG["responses"])
2025-09-02 11:18:04 +08:00
if not result or len(result) == 0:
return
# 生成TTS音频
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result:
return
# 获取当前音色
voice = getattr(conn.tts, "voice", "default")
# 使用链接的sample_rate
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=conn.sample_rate)
2025-09-02 11:18:04 +08:00
file_path = wakeup_words_config.generate_file_path(voice)
with open(file_path, "wb") as f:
f.write(wav_bytes)
# 更新配置
wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally:
# 确保在任何情况下都释放锁
if _wakeup_response_lock.locked():
2025-10-12 23:24:43 +08:00
_wakeup_response_lock.release()