import asyncio from typing import Set, Tuple from utils.logger import session_logger class TTSErrorManager: """管理TTS错误状态,确保TTS_START和TTS_END之间最多只发送一次TTS_ERROR""" def __init__(self): self.error_sent_sessions: Set[Tuple[str, str]] = set() self.active_tts_sessions: Set[Tuple[str, str]] = set() self.lock = asyncio.Lock() async def start_tts_session(self, device_id: str, session_id: str): """标记TTS会话开始,重置错误状态""" session_key = (device_id, session_id) async with self.lock: self.active_tts_sessions.add(session_key) if session_key in self.error_sent_sessions: self.error_sent_sessions.remove(session_key) async def end_tts_session(self, device_id: str, session_id: str): """标记TTS会话结束,清理状态""" session_key = (device_id, session_id) async with self.lock: if session_key in self.active_tts_sessions: self.active_tts_sessions.remove(session_key) if session_key in self.error_sent_sessions: self.error_sent_sessions.remove(session_key) async def can_send_error(self, device_id: str, session_id: str) -> bool: """检查是否可以发送错误通知""" session_key = (device_id, session_id) async with self.lock: if session_key in self.active_tts_sessions and session_key not in self.error_sent_sessions: self.error_sent_sessions.add(session_key) return True return False tts_error_manager = TTSErrorManager()