2025-02-02 23:01:14 +08:00
|
|
|
import asyncio
|
|
|
|
|
import websockets
|
2025-02-18 00:07:19 +08:00
|
|
|
from config.logger import setup_logging
|
2025-02-02 23:01:14 +08:00
|
|
|
from core.connection import ConnectionHandler
|
2025-04-12 17:36:04 +08:00
|
|
|
from core.utils.util import get_local_ip, initialize_modules
|
2025-02-02 23:01:14 +08:00
|
|
|
|
2025-02-18 00:07:19 +08:00
|
|
|
TAG = __name__
|
2025-02-02 23:01:14 +08:00
|
|
|
|
2025-02-23 14:38:21 +08:00
|
|
|
|
2025-02-02 23:01:14 +08:00
|
|
|
class WebSocketServer:
|
|
|
|
|
def __init__(self, config: dict):
|
|
|
|
|
self.config = config
|
2025-02-18 00:07:19 +08:00
|
|
|
self.logger = setup_logging()
|
2025-04-12 17:36:04 +08:00
|
|
|
modules = initialize_modules(
|
|
|
|
|
self.logger, self.config, True, True, True, True, True, True
|
2025-02-02 23:01:14 +08:00
|
|
|
)
|
2025-04-12 17:36:04 +08:00
|
|
|
self._vad = modules["vad"]
|
|
|
|
|
self._asr = modules["asr"]
|
|
|
|
|
self._tts = modules["tts"]
|
|
|
|
|
self._llm = modules["llm"]
|
|
|
|
|
self._intent = modules["intent"]
|
|
|
|
|
self._memory = modules["memory"]
|
|
|
|
|
self.active_connections = set()
|
2025-02-02 23:01:14 +08:00
|
|
|
|
|
|
|
|
async def start(self):
|
|
|
|
|
server_config = self.config["server"]
|
|
|
|
|
host = server_config["ip"]
|
2025-04-15 00:44:34 +08:00
|
|
|
port = int(server_config.get("port", 8000))
|
2025-02-02 23:01:14 +08:00
|
|
|
|
2025-04-01 00:03:05 +08:00
|
|
|
self.logger.bind(tag=TAG).info(
|
|
|
|
|
"Server is running at ws://{}:{}/xiaozhi/v1/", get_local_ip(), port
|
|
|
|
|
)
|
|
|
|
|
self.logger.bind(tag=TAG).info(
|
|
|
|
|
"=======上面的地址是websocket协议地址,请勿用浏览器访问======="
|
|
|
|
|
)
|
|
|
|
|
self.logger.bind(tag=TAG).info(
|
|
|
|
|
"如想测试websocket请用谷歌浏览器打开test目录下的test_page.html"
|
|
|
|
|
)
|
|
|
|
|
self.logger.bind(tag=TAG).info(
|
|
|
|
|
"=============================================================\n"
|
|
|
|
|
)
|
|
|
|
|
async with websockets.serve(self._handle_connection, host, port):
|
2025-02-02 23:01:14 +08:00
|
|
|
await asyncio.Future()
|
|
|
|
|
|
|
|
|
|
async def _handle_connection(self, websocket):
|
|
|
|
|
"""处理新连接,每次创建独立的ConnectionHandler"""
|
2025-02-26 01:33:05 +08:00
|
|
|
# 创建ConnectionHandler时传入当前server实例
|
2025-04-01 00:03:05 +08:00
|
|
|
handler = ConnectionHandler(
|
|
|
|
|
self.config,
|
|
|
|
|
self._vad,
|
|
|
|
|
self._asr,
|
|
|
|
|
self._llm,
|
|
|
|
|
self._tts,
|
|
|
|
|
self._memory,
|
2025-04-12 17:36:04 +08:00
|
|
|
self._intent,
|
2025-04-01 00:03:05 +08:00
|
|
|
)
|
2025-02-26 01:33:05 +08:00
|
|
|
self.active_connections.add(handler)
|
|
|
|
|
try:
|
|
|
|
|
await handler.handle_connection(websocket)
|
|
|
|
|
finally:
|
|
|
|
|
self.active_connections.discard(handler)
|