fix ws connection

This commit is contained in:
xiehao.0527 2025-07-10 13:32:29 +08:00
parent 908de0c24a
commit a646cf4b52
3 changed files with 58 additions and 61 deletions

View file

@ -190,7 +190,7 @@ class ASRProvider(ASRProviderBase):
self.text = "" # Reset for next utterance. self.text = "" # Reset for next utterance.
break # End the receiving task. break # End the receiving task.
elif message_type == "error": elif message_type == "error":
error_msg = event.get("message", "Unknown ASR error") error_msg = event.get("error", {})
logger.bind(tag=TAG).error(f"ASR service error: {error_msg}") logger.bind(tag=TAG).error(f"ASR service error: {error_msg}")
await self.stop_ws_connection() await self.stop_ws_connection()
break break
@ -329,32 +329,29 @@ class ASRProvider(ASRProviderBase):
Raises: Raises:
Exception: If the connection cannot be established. Exception: If the connection cannot be established.
""" """
if self.ws is not None: # 检查连接是否存在且处于 open 状态
try: # websockets 库的自动 ping/pong 机制会处理连接健康检查
if self.ws: if self.ws:
logger.bind(tag=TAG).info(f"Checking WebSocket connection health: {self.ws_url}") logger.bind(tag=TAG).debug("WebSocket connection is active.")
# 发送ping并设置200ms超时 return
await asyncio.wait_for(self.ws.ping(), timeout=0.2)
logger.bind(tag=TAG).debug("WebSocket ping successful") # 如果连接不存在或已关闭,则重新连接
return True try:
logger.bind(tag=TAG).warning("WebSocket connection not open") logger.bind(tag=TAG).info(f"Connecting to {self.ws_url}")
except asyncio.TimeoutError: headers = {"Authorization": f"Bearer {self.api_key}"}
logger.bind(tag=TAG).error("WebSocket ping timed out after 0.2 seconds") # 使用内置的 ping/pong 机制来维持连接和检查健康状况
except websockets.exceptions.ConnectionClosed: # 每 20 秒发送一次 ping,等待 10 秒超时
logger.bind(tag=TAG).error("WebSocket connection already closed") self.ws = await websockets.connect(
except Exception as e: self.ws_url,
logger.bind(tag=TAG).error(f"Failed to ping WebSocket: {e}") additional_headers=headers,
await self.stop_ws_connection() ping_interval=20,
if self.ws is None: ping_timeout=10
try: )
logger.bind(tag=TAG).info(f"Connecting to {self.ws_url}") logger.bind(tag=TAG).info("WebSocket connection established.")
headers = {"Authorization": f"Bearer {self.api_key}"} except Exception as e:
self.ws = await websockets.connect(self.ws_url, additional_headers=headers) logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}")
logger.bind(tag=TAG).info("WebSocket connection established.") self.ws = None
except Exception as e: raise
logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}")
self.ws = None
raise
async def stop_ws_connection(self): async def stop_ws_connection(self):
""" """

View file

@ -139,12 +139,7 @@ class TTSProvider(TTSProviderBase):
break # End of stream for this request break # End of stream for this request
elif event_type == "error": elif event_type == "error":
logger.bind(tag=TAG).error(f"Received error from server: {data}") logger.bind(tag=TAG).error(f"Received error from server: {data}")
if self.ws: await self.stop_ws_connection()
try:
await self.ws.close()
except Exception:
pass
self.ws = None
break break
except websockets.exceptions.ConnectionClosed as e: except websockets.exceptions.ConnectionClosed as e:
await self.stop_ws_connection() await self.stop_ws_connection()
@ -298,33 +293,38 @@ class TTSProvider(TTSProviderBase):
self._monitor_task = None self._monitor_task = None
async def _ensure_connection(self): async def _ensure_connection(self):
"""Ensures the WebSocket connection is active. Tries to reconnect if it's disconnected.""" """
if self.ws is not None: Ensures that the WebSocket connection to the ASR service is active.
try:
if self.ws: If the connection is down, it attempts to reconnect.
logger.bind(tag=TAG).info(f"Checking WebSocket connection health: {self.ws_url}")
# 发送ping并设置200ms超时 Raises:
await asyncio.wait_for(self.ws.ping(), timeout=0.2) Exception: If the connection cannot be established.
logger.bind(tag=TAG).debug("WebSocket ping successful") """
return True # 检查连接是否存在且处于 open 状态
logger.bind(tag=TAG).warning("WebSocket connection not open") # websockets 库的自动 ping/pong 机制会处理连接健康检查
except asyncio.TimeoutError: if self.ws:
logger.bind(tag=TAG).error("WebSocket ping timed out after 0.2 seconds") logger.bind(tag=TAG).debug("WebSocket connection is active.")
except websockets.exceptions.ConnectionClosed: return
logger.bind(tag=TAG).error("WebSocket connection already closed")
except Exception as e: # 如果连接不存在或已关闭,则重新连接
logger.bind(tag=TAG).error(f"Failed to ping WebSocket: {e}") try:
await self.stop_ws_connection() logger.bind(tag=TAG).info(f"Connecting to {self.ws_url}")
if self.ws is None: headers = {"Authorization": f"Bearer {self.api_key}"}
try: # 使用内置的 ping/pong 机制来维持连接和检查健康状况
logger.bind(tag=TAG).info(f"Connecting to {self.ws_url}") # 每 20 秒发送一次 ping,等待 10 秒超时
headers = {"Authorization": f"Bearer {self.api_key}"} self.ws = await websockets.connect(
self.ws = await websockets.connect(self.ws_url, additional_headers=headers) self.ws_url,
logger.bind(tag=TAG).info("WebSocket connection established.") additional_headers=headers,
except Exception as e: ping_interval=20,
logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}") ping_timeout=10
self.ws = None )
raise logger.bind(tag=TAG).info("WebSocket connection established.")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to connect to WebSocket: {e}")
self.ws = None
raise

View file

@ -94,7 +94,7 @@ class VADProvider(VADProviderBase):
# For semantic checks, we need the embedding. # For semantic checks, we need the embedding.
embedding, is_cached = self._get_embedding(text) embedding, is_cached = self._get_embedding(text)
is_stop = embedding[1] > 0.5 is_stop = embedding[1] > 0.5
if not is_cached or is_stop or silence_duration >= self.max_silence_threshold_ms: if not is_cached or silence_duration >= self.max_silence_threshold_ms:
logger.bind(tag=TAG).info(f"EOU Result: text:{text} embedding:{embedding} semantic_stop:{is_stop} silence_duration:{silence_duration} cache:{is_cached}") logger.bind(tag=TAG).info(f"EOU Result: text:{text} embedding:{embedding} semantic_stop:{is_stop} silence_duration:{silence_duration} cache:{is_cached}")
if self.semantic_only: if self.semantic_only:
return is_stop return is_stop