child-psycho-companion/test_xiaozhi_client.py

66 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""
小智设备连接测试客户端
连接到 xiaozhi-server模拟设备握手触发 MCP 工具初始化
"""
import asyncio
import json
import uuid
import websockets
import sys
XIAOZHI_WS = "ws://localhost:8000/xiaozhi/v1/"
DEVICE_ID = str(uuid.uuid4())
TOPIC = str(uuid.uuid4())
async def main():
print(f"连接 xiaozhi-server: {XIAOZHI_WS}")
print(f"Device ID: {DEVICE_ID}")
async with websockets.connect(XIAOZHI_WS, ping_interval=None) as ws:
# 发送设备 hello
hello = {
"type": "hello",
"deviceId": DEVICE_ID,
"deviceName": "测试设备",
"clientType": "py-websocket-test",
"protocolVersion": "1.0.0",
"featureSet": {"mcp": True},
}
await ws.send(json.dumps(hello))
print(f"发送 hello: {hello}")
# 接收消息(最多等 30 秒)
for i in range(20):
try:
msg = await asyncio.wait_for(ws.recv(), timeout=5.0)
data = json.loads(msg)
msg_type = data.get("type", "unknown")
print(f"收到 [{msg_type}]: {json.dumps(data, ensure_ascii=False)[:200]}")
if msg_type == "welcome":
print("\n✅ 连接成功!")
if "tools" in data:
print(f"MCP 工具列表: {[t.get('name') for t in data.get('tools', [])]}")
if "mcpTools" in data:
print(f"MCP 工具: {data.get('mcpTools')}")
break
except asyncio.TimeoutError:
print(f" ... 等待中 ({i+1}/20)")
continue
print("\n测试完成5秒后关闭...")
await asyncio.sleep(5)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n已退出")
except Exception as e:
print(f"错误: {e}")
sys.exit(1)