mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
调通远程服务器功能,但是语音卡顿
This commit is contained in:
parent
a85fca3055
commit
066015164b
10 changed files with 1791 additions and 920 deletions
3
.vscode/settings.json
vendored
Normal file
3
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
{
|
||||||
|
"java.compile.nullAnalysis.mode": "automatic"
|
||||||
|
}
|
||||||
177
README.md
177
README.md
|
|
@ -11,6 +11,177 @@
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
# Xiaozhi ESP32 服务端系统
|
||||||
|
|
||||||
|
本系统是一个完整的ESP32设备管理平台,包含三个主要组件:
|
||||||
|
- **manager-api**:基于Spring Boot的后端API服务
|
||||||
|
- **manager-web**:前端界面
|
||||||
|
- **xiaozhi-server**:WebSocket服务器
|
||||||
|
|
||||||
|
## 系统要求
|
||||||
|
|
||||||
|
### 软件要求
|
||||||
|
- JDK 21+
|
||||||
|
- Maven 3.8+
|
||||||
|
- MySQL 8.0+
|
||||||
|
- Node.js 16+ (用于前端)
|
||||||
|
- npm 8+ (用于前端)
|
||||||
|
|
||||||
|
## 数据库配置
|
||||||
|
|
||||||
|
1. 安装MySQL数据库
|
||||||
|
```bash
|
||||||
|
# Ubuntu/Debian系统
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install mysql-server
|
||||||
|
|
||||||
|
# 或者使用Docker
|
||||||
|
docker pull mysql:8.0
|
||||||
|
docker run --name xiaozhi-mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql:8.0
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 创建数据库和用户
|
||||||
|
```bash
|
||||||
|
mysql -u root -p
|
||||||
|
|
||||||
|
# 在MySQL控制台中执行
|
||||||
|
CREATE DATABASE xiaozhi_esp32_server CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
|
||||||
|
# 确保root用户拥有正确的权限
|
||||||
|
ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';
|
||||||
|
GRANT ALL PRIVILEGES ON xiaozhi_esp32_server.* TO 'root'@'localhost';
|
||||||
|
FLUSH PRIVILEGES;
|
||||||
|
```
|
||||||
|
|
||||||
|
## 启动后端API服务 (manager-api)
|
||||||
|
|
||||||
|
1. 进入manager-api目录
|
||||||
|
```bash
|
||||||
|
cd main/manager-api
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 使用Maven编译项目
|
||||||
|
```bash
|
||||||
|
mvn clean compile
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 启动Spring Boot应用程序
|
||||||
|
```bash
|
||||||
|
mvn spring-boot:run -Dmaven.test.skip=true
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 启动成功后,可以通过以下地址访问API文档:
|
||||||
|
```
|
||||||
|
http://localhost:8002/xiaozhi-esp32-api/doc.html
|
||||||
|
```
|
||||||
|
|
||||||
|
### 配置说明
|
||||||
|
|
||||||
|
数据库连接配置位于 `main/manager-api/src/main/resources/application-dev.yml` 文件中:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
druid:
|
||||||
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
|
url: jdbc:mysql://localhost:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
|
||||||
|
username: root
|
||||||
|
password: 123456
|
||||||
|
```
|
||||||
|
|
||||||
|
如需修改数据库连接信息,请更新此文件。
|
||||||
|
|
||||||
|
## 启动前端服务 (manager-web)
|
||||||
|
|
||||||
|
1. 进入manager-web目录
|
||||||
|
```bash
|
||||||
|
cd main/manager-web
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 安装依赖
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 启动开发服务器
|
||||||
|
```bash
|
||||||
|
npm run serve
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 构建生产版本
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
5. 访问前端界面
|
||||||
|
```
|
||||||
|
http://localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
## 启动WebSocket服务器 (xiaozhi-server)
|
||||||
|
|
||||||
|
1. 进入xiaozhi-server目录
|
||||||
|
```bash
|
||||||
|
cd main/xiaozhi-server
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 使用Maven编译项目
|
||||||
|
```bash
|
||||||
|
mvn clean package
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 启动WebSocket服务器
|
||||||
|
```bash
|
||||||
|
java -jar target/xiaozhi-server-0.0.1.jar
|
||||||
|
```
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 数据库连接问题
|
||||||
|
|
||||||
|
如果遇到数据库连接问题,请检查:
|
||||||
|
|
||||||
|
1. MySQL服务是否正在运行
|
||||||
|
```bash
|
||||||
|
systemctl status mysql
|
||||||
|
```
|
||||||
|
|
||||||
|
2. 用户名和密码是否正确
|
||||||
|
3. 数据库名称是否正确
|
||||||
|
4. MySQL是否允许本地连接
|
||||||
|
|
||||||
|
### 端口冲突
|
||||||
|
|
||||||
|
如果端口被占用,可以在相应的配置文件中修改端口:
|
||||||
|
|
||||||
|
- manager-api: 修改 `application-dev.yml` 中的 `server.port` 属性
|
||||||
|
- manager-web: 修改 `vue.config.js` 中的 `devServer.port` 属性
|
||||||
|
- xiaozhi-server: 修改配置文件中的端口设置
|
||||||
|
|
||||||
|
## 开发与调试
|
||||||
|
|
||||||
|
### API开发
|
||||||
|
后端API基于Spring Boot框架,可以在 `main/manager-api/src/main/java/xiaozhi` 目录下修改或添加代码。
|
||||||
|
|
||||||
|
### 前端开发
|
||||||
|
前端基于Vue.js框架,可以在 `main/manager-web/src` 目录下修改或添加代码。
|
||||||
|
|
||||||
|
### WebSocket服务器
|
||||||
|
WebSocket服务器处理与ESP32设备的实时通信,代码位于 `main/xiaozhi-server/src` 目录。
|
||||||
|
|
||||||
|
## 贡献指南
|
||||||
|
|
||||||
|
欢迎贡献代码或提出建议。请遵循以下步骤:
|
||||||
|
|
||||||
|
1. Fork本仓库
|
||||||
|
2. 创建特性分支 (`git checkout -b feature/amazing-feature`)
|
||||||
|
3. 提交更改 (`git commit -m 'Add some amazing feature'`)
|
||||||
|
4. 推送到分支 (`git push origin feature/amazing-feature`)
|
||||||
|
5. 创建Pull Request
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
ws://192.168.8.198:8000
|
||||||
|
[添加许可证信息]
|
||||||
|
|
||||||
# 小智 ESP-32 后端服务(xiaozhi-esp32-server)
|
# 小智 ESP-32 后端服务(xiaozhi-esp32-server)
|
||||||
|
|
||||||
(中文 | [English](README_en.md))
|
(中文 | [English](README_en.md))
|
||||||
|
|
@ -263,7 +434,7 @@ VAD:
|
||||||
建议:检查一下`models/SenseVoiceSmall`是否已经有`model.pt`
|
建议:检查一下`models/SenseVoiceSmall`是否已经有`model.pt`
|
||||||
文件,如果没有就要下载,查看这里[下载语音识别模型文件](docs/Deployment.md#模型文件)
|
文件,如果没有就要下载,查看这里[下载语音识别模型文件](docs/Deployment.md#模型文件)
|
||||||
|
|
||||||
### 5、为什么会出现“TTS 任务出错 文件不存在”?📁
|
### 5、为什么会出现"TTS 任务出错 文件不存在"?📁
|
||||||
|
|
||||||
建议:检查一下是否正确使用`conda` 安装了`libopus`和`ffmpeg`库。
|
建议:检查一下是否正确使用`conda` 安装了`libopus`和`ffmpeg`库。
|
||||||
|
|
||||||
|
|
@ -276,7 +447,7 @@ conda install conda-forge::ffmpeg
|
||||||
|
|
||||||
### 6、如何提高小智对话响应速度? ⚡
|
### 6、如何提高小智对话响应速度? ⚡
|
||||||
|
|
||||||
本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决“跑得动”的问题,再优化“跑得快”。
|
本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决"跑得动"的问题,再优化"跑得快"。
|
||||||
如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺):
|
如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺):
|
||||||
|
|
||||||
| 影响因素 | 因素值 |
|
| 影响因素 | 因素值 |
|
||||||
|
|
@ -336,7 +507,7 @@ TTS 性能排行:
|
||||||
|
|
||||||
我们的联系方式放在[百度网盘中,点击前往](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),提取码是`223y`。
|
我们的联系方式放在[百度网盘中,点击前往](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),提取码是`223y`。
|
||||||
|
|
||||||
网盘里有“硬件烧录QQ群”、“开源服务端交流群”、“产品建议联系人” 三张图片,请根据需要选择加入。
|
网盘里有"硬件烧录QQ群"、"开源服务端交流群"、"产品建议联系人" 三张图片,请根据需要选择加入。
|
||||||
|
|
||||||
- 硬件烧录QQ群:适用于硬件烧录问题
|
- 硬件烧录QQ群:适用于硬件烧录问题
|
||||||
- 开源服务端交流群:适用于服务端问题
|
- 开源服务端交流群:适用于服务端问题
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ CREATE DATABASE xiaozhi_esp32_server CHARACTER SET utf8mb4 COLLATE utf8mb4_unico
|
||||||
如果还没有MySQL,你可以通过docker安装mysql
|
如果还没有MySQL,你可以通过docker安装mysql
|
||||||
|
|
||||||
```
|
```
|
||||||
docker run --name xiaozhi-esp32-server-db \
|
sudo docker run --name xiaozhi-esp32-server-db \
|
||||||
-e MYSQL_ROOT_PASSWORD=123456 \
|
-e MYSQL_ROOT_PASSWORD=123456 \
|
||||||
-p 3306:3306 \
|
-p 3306:3306 \
|
||||||
-e MYSQL_DATABASE=xiaozhi_esp32_server \
|
-e MYSQL_DATABASE=xiaozhi_esp32_server \
|
||||||
|
|
|
||||||
|
|
@ -35,4 +35,9 @@ public interface ErrorCode {
|
||||||
int REDIS_ERROR = 10027;
|
int REDIS_ERROR = 10027;
|
||||||
int JOB_ERROR = 10028;
|
int JOB_ERROR = 10028;
|
||||||
int INVALID_SYMBOL = 10029;
|
int INVALID_SYMBOL = 10029;
|
||||||
|
|
||||||
|
// 添加缺失的错误代码
|
||||||
|
int PASSWORD_LENGTH_ERROR = 10030;
|
||||||
|
int PASSWORD_WEAK_ERROR = 10031;
|
||||||
|
int DEL_MYSELF_ERROR = 10032;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -23,4 +23,14 @@ public interface SysDictTypeService extends BaseService<SysDictTypeEntity> {
|
||||||
void update(SysDictTypeDTO dto);
|
void update(SysDictTypeDTO dto);
|
||||||
|
|
||||||
void delete(Long[] ids);
|
void delete(Long[] ids);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有字典类型及其数据
|
||||||
|
*/
|
||||||
|
List<DictType> getAllList();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有字典类型
|
||||||
|
*/
|
||||||
|
List<DictType> getDictTypeList();
|
||||||
}
|
}
|
||||||
1665
main/manager-web/package-lock.json
generated
1665
main/manager-web/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -20,8 +20,6 @@ def load_config():
|
||||||
"""加载配置文件"""
|
"""加载配置文件"""
|
||||||
parser = argparse.ArgumentParser(description="Server configuration")
|
parser = argparse.ArgumentParser(description="Server configuration")
|
||||||
config_file = get_config_file()
|
config_file = get_config_file()
|
||||||
# 打印绝对路径
|
|
||||||
# print(f"config_file: {os.path.abspath(config_file)}")
|
|
||||||
parser.add_argument("--config_path", type=str, default=config_file)
|
parser.add_argument("--config_path", type=str, default=config_file)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
return read_config(args.config_path)
|
return read_config(args.config_path)
|
||||||
|
|
|
||||||
631
test_api.py
Normal file
631
test_api.py
Normal file
|
|
@ -0,0 +1,631 @@
|
||||||
|
import asyncio
|
||||||
|
import aiohttp
|
||||||
|
import requests
|
||||||
|
import time
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
import logging
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import concurrent.futures
|
||||||
|
import emoji
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
|
||||||
|
# 配置日志
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format='%(asctime)s - %(levelname)s - %(message)s',
|
||||||
|
datefmt='%Y-%m-%d %H:%M:%S'
|
||||||
|
)
|
||||||
|
|
||||||
|
# 测试配置
|
||||||
|
class TestConfig:
|
||||||
|
def __init__(self, base_url: str = "http://localhost:9881"):
|
||||||
|
self.base_url = base_url
|
||||||
|
self.output_dir = Path("test_results")
|
||||||
|
self.output_dir.mkdir(exist_ok=True)
|
||||||
|
|
||||||
|
# 测试强度配置
|
||||||
|
self.concurrent_requests = 10 # 并发请求数
|
||||||
|
self.stress_test_duration = 60 # 压力测试持续时间(秒)
|
||||||
|
self.request_timeout = 30 # 请求超时时间(秒)
|
||||||
|
|
||||||
|
# 批量测试配置
|
||||||
|
self.batch_size = 5 # 批处理大小
|
||||||
|
|
||||||
|
# 缓存测试结果
|
||||||
|
self.test_results = []
|
||||||
|
|
||||||
|
# 已缓存的speaker列表
|
||||||
|
self.speakers = None
|
||||||
|
|
||||||
|
# 异常输入生成器
|
||||||
|
class AbnormalInputGenerator:
|
||||||
|
@staticmethod
|
||||||
|
def get_emoji_text(count: int = 5) -> str:
|
||||||
|
"""生成包含表情符号的文本"""
|
||||||
|
emojis = list(emoji.EMOJI_DATA.keys())
|
||||||
|
sample = random.sample(emojis, min(count, len(emojis)))
|
||||||
|
return "这是一段" + "".join(sample) + "包含表情符号的测试文本"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_long_text(length: int = 2000) -> str:
|
||||||
|
"""生成超长文本"""
|
||||||
|
return "这是一段非常长的测试文本。" * (length // 10)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_special_chars() -> str:
|
||||||
|
"""生成包含特殊字符的文本"""
|
||||||
|
special_chars = "!@#$%^&*()_+-=[]{}|;':\",./<>?\\`~"
|
||||||
|
return f"包含特殊字符的文本:{special_chars}"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_control_chars() -> str:
|
||||||
|
"""生成包含控制字符的文本"""
|
||||||
|
control_chars = ''.join(chr(i) for i in range(32) if i not in (9, 10, 13))
|
||||||
|
return f"正常文本{control_chars}包含控制字符"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_mixed_language() -> str:
|
||||||
|
"""生成混合语言文本"""
|
||||||
|
return "这是中文 This is English こんにちは 안녕하세요 Привет"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_repeated_chars() -> str:
|
||||||
|
"""生成重复字符文本"""
|
||||||
|
return "啊" * 50 + "测试重复字符"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_html_injection() -> str:
|
||||||
|
"""生成包含HTML注入的文本"""
|
||||||
|
return "正常文本<script>alert('XSS')</script><img src=x onerror=alert('XSS')>"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_sql_injection() -> str:
|
||||||
|
"""生成包含SQL注入的文本"""
|
||||||
|
return "正常文本'; DROP TABLE users; --"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_zero_width_chars() -> str:
|
||||||
|
"""生成包含零宽字符的文本"""
|
||||||
|
zero_width_chars = '\u200b\u200c\u200d\ufeff'
|
||||||
|
return f"包含零宽字符的文本:{''.join(c + z for c, z in zip('测试文本', zero_width_chars))}"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_abnormal_inputs() -> List[Dict[str, str]]:
|
||||||
|
"""获取所有异常输入及其描述"""
|
||||||
|
return [
|
||||||
|
{"description": "表情符号文本", "text": AbnormalInputGenerator.get_emoji_text()},
|
||||||
|
{"description": "超长文本", "text": AbnormalInputGenerator.get_long_text()},
|
||||||
|
{"description": "特殊字符", "text": AbnormalInputGenerator.get_special_chars()},
|
||||||
|
{"description": "控制字符", "text": AbnormalInputGenerator.get_control_chars()},
|
||||||
|
{"description": "混合语言", "text": AbnormalInputGenerator.get_mixed_language()},
|
||||||
|
{"description": "重复字符", "text": AbnormalInputGenerator.get_repeated_chars()},
|
||||||
|
{"description": "HTML注入", "text": AbnormalInputGenerator.get_html_injection()},
|
||||||
|
{"description": "SQL注入", "text": AbnormalInputGenerator.get_sql_injection()},
|
||||||
|
{"description": "零宽字符", "text": AbnormalInputGenerator.get_zero_width_chars()},
|
||||||
|
{"description": "空文本", "text": ""},
|
||||||
|
{"description": "单个字符", "text": "我"},
|
||||||
|
]
|
||||||
|
|
||||||
|
# API测试类
|
||||||
|
class CosyVoiceAPITester:
|
||||||
|
def __init__(self, config: TestConfig):
|
||||||
|
self.config = config
|
||||||
|
self.session = requests.Session()
|
||||||
|
|
||||||
|
def get_speakers(self) -> List[str]:
|
||||||
|
"""获取可用的音色列表"""
|
||||||
|
if self.config.speakers is not None:
|
||||||
|
return self.config.speakers
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = self.session.get(f"{self.config.base_url}/speakers", timeout=self.config.request_timeout)
|
||||||
|
response.raise_for_status()
|
||||||
|
speakers = response.json().get("speakers", [])
|
||||||
|
self.config.speakers = speakers
|
||||||
|
return speakers
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"获取音色列表失败: {str(e)}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def get_random_speaker(self) -> Optional[str]:
|
||||||
|
"""获取随机音色"""
|
||||||
|
speakers = self.get_speakers()
|
||||||
|
if not speakers:
|
||||||
|
return None
|
||||||
|
return random.choice(speakers)
|
||||||
|
|
||||||
|
def test_root_endpoint(self) -> Dict[str, Any]:
|
||||||
|
"""测试根端点"""
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
response = self.session.get(f"{self.config.base_url}/", timeout=self.config.request_timeout)
|
||||||
|
response.raise_for_status()
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"data": response.json()
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e),
|
||||||
|
"response_time": time.time() - start_time
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_status_endpoint(self) -> Dict[str, Any]:
|
||||||
|
"""测试状态端点"""
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
response = self.session.get(f"{self.config.base_url}/status", timeout=self.config.request_timeout)
|
||||||
|
response.raise_for_status()
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"data": response.json()
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e),
|
||||||
|
"response_time": time.time() - start_time
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_tts_endpoint(self, text: str, description: str = "正常测试") -> Dict[str, Any]:
|
||||||
|
"""测试TTS端点"""
|
||||||
|
speaker = self.get_random_speaker()
|
||||||
|
if not speaker:
|
||||||
|
return {"success": False, "error": "没有可用的音色"}
|
||||||
|
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
data = {
|
||||||
|
"text": text,
|
||||||
|
"mode": "预训练音色",
|
||||||
|
"speaker": speaker,
|
||||||
|
"seed": random.randint(0, 10000),
|
||||||
|
"stream": False,
|
||||||
|
"speed": random.uniform(0.8, 1.2)
|
||||||
|
}
|
||||||
|
|
||||||
|
response = self.session.post(
|
||||||
|
f"{self.config.base_url}/tts",
|
||||||
|
data=data,
|
||||||
|
timeout=self.config.request_timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
# 检查响应类型
|
||||||
|
if response.headers.get("Content-Type") == "application/json":
|
||||||
|
# 发生错误,API返回了JSON错误信息
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": description,
|
||||||
|
"text": text,
|
||||||
|
"error": response.json()
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# 成功获取音频
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": description,
|
||||||
|
"text": text,
|
||||||
|
"content_type": response.headers.get("Content-Type"),
|
||||||
|
"content_length": len(response.content)
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e),
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": description,
|
||||||
|
"text": text
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_stream_tts_endpoint(self, text: str, description: str = "流式测试") -> Dict[str, Any]:
|
||||||
|
"""测试流式TTS端点"""
|
||||||
|
speaker = self.get_random_speaker()
|
||||||
|
if not speaker:
|
||||||
|
return {"success": False, "error": "没有可用的音色"}
|
||||||
|
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
params = {
|
||||||
|
"text": text,
|
||||||
|
"mode": "预训练音色",
|
||||||
|
"speaker": speaker,
|
||||||
|
"seed": random.randint(0, 10000),
|
||||||
|
"speed": random.uniform(0.8, 1.2)
|
||||||
|
}
|
||||||
|
|
||||||
|
response = self.session.get(
|
||||||
|
f"{self.config.base_url}/stream_tts",
|
||||||
|
params=params,
|
||||||
|
stream=True,
|
||||||
|
timeout=self.config.request_timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
# 检查响应类型
|
||||||
|
if response.headers.get("Content-Type") == "application/json":
|
||||||
|
# 发生错误,API返回了JSON错误信息
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": description,
|
||||||
|
"text": text,
|
||||||
|
"error": response.json()
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# 成功获取流式音频
|
||||||
|
content_size = 0
|
||||||
|
for chunk in response.iter_content(chunk_size=8192):
|
||||||
|
content_size += len(chunk)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": description,
|
||||||
|
"text": text,
|
||||||
|
"content_type": response.headers.get("Content-Type"),
|
||||||
|
"content_length": content_size
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e),
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": description,
|
||||||
|
"text": text
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_invalid_speaker(self) -> Dict[str, Any]:
|
||||||
|
"""测试无效的音色"""
|
||||||
|
invalid_speaker = "不存在的音色" + str(random.randint(1000, 9999))
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
data = {
|
||||||
|
"text": "测试无效音色",
|
||||||
|
"mode": "预训练音色",
|
||||||
|
"speaker": invalid_speaker,
|
||||||
|
"seed": random.randint(0, 10000),
|
||||||
|
"stream": False
|
||||||
|
}
|
||||||
|
|
||||||
|
response = self.session.post(
|
||||||
|
f"{self.config.base_url}/tts",
|
||||||
|
data=data,
|
||||||
|
timeout=self.config.request_timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": response.status_code == 400, # 期望返回400
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": "无效音色测试",
|
||||||
|
"data": response.json() if response.headers.get("Content-Type") == "application/json" else None
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e),
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": "无效音色测试"
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_abnormal_inputs(self) -> List[Dict[str, Any]]:
|
||||||
|
"""测试各种异常输入"""
|
||||||
|
results = []
|
||||||
|
abnormal_inputs = AbnormalInputGenerator.get_abnormal_inputs()
|
||||||
|
|
||||||
|
for input_data in abnormal_inputs:
|
||||||
|
result = self.test_tts_endpoint(
|
||||||
|
text=input_data["text"],
|
||||||
|
description=input_data["description"]
|
||||||
|
)
|
||||||
|
results.append(result)
|
||||||
|
time.sleep(0.5) # 避免过快请求
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
def test_invalid_mode(self) -> Dict[str, Any]:
|
||||||
|
"""测试无效的模式"""
|
||||||
|
invalid_mode = "不存在的模式" + str(random.randint(1000, 9999))
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
data = {
|
||||||
|
"text": "测试无效模式",
|
||||||
|
"mode": invalid_mode,
|
||||||
|
"speaker": self.get_random_speaker(),
|
||||||
|
"seed": random.randint(0, 10000),
|
||||||
|
"stream": False
|
||||||
|
}
|
||||||
|
|
||||||
|
response = self.session.post(
|
||||||
|
f"{self.config.base_url}/tts",
|
||||||
|
data=data,
|
||||||
|
timeout=self.config.request_timeout
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": response.status_code in (400, 422), # 期望返回错误
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": "无效模式测试",
|
||||||
|
"data": response.json() if response.headers.get("Content-Type") == "application/json" else None
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e),
|
||||||
|
"response_time": time.time() - start_time,
|
||||||
|
"description": "无效模式测试"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 异步压力测试工具
|
||||||
|
class StressTestTool:
|
||||||
|
def __init__(self, config: TestConfig):
|
||||||
|
self.config = config
|
||||||
|
|
||||||
|
async def fetch(self, session, url, data=None, method="GET", params=None):
|
||||||
|
"""发送异步HTTP请求"""
|
||||||
|
start_time = time.time()
|
||||||
|
try:
|
||||||
|
if method.upper() == "POST":
|
||||||
|
async with session.post(url, data=data, timeout=self.config.request_timeout) as response:
|
||||||
|
await response.read()
|
||||||
|
return {
|
||||||
|
"success": response.status == 200,
|
||||||
|
"status_code": response.status,
|
||||||
|
"response_time": time.time() - start_time
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
async with session.get(url, params=params, timeout=self.config.request_timeout) as response:
|
||||||
|
await response.read()
|
||||||
|
return {
|
||||||
|
"success": response.status == 200,
|
||||||
|
"status_code": response.status,
|
||||||
|
"response_time": time.time() - start_time
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e),
|
||||||
|
"response_time": time.time() - start_time
|
||||||
|
}
|
||||||
|
|
||||||
|
async def run_stress_test(self, endpoint: str, duration: int, concurrency: int, method="GET", data_generator=None):
|
||||||
|
"""运行压力测试"""
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
start_time = time.time()
|
||||||
|
end_time = start_time + duration
|
||||||
|
tasks = []
|
||||||
|
results = []
|
||||||
|
|
||||||
|
while time.time() < end_time:
|
||||||
|
# 创建并发任务
|
||||||
|
for _ in range(concurrency):
|
||||||
|
if method.upper() == "POST":
|
||||||
|
data = data_generator() if data_generator else None
|
||||||
|
task = asyncio.create_task(
|
||||||
|
self.fetch(session, f"{self.config.base_url}{endpoint}", data=data, method="POST")
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
task = asyncio.create_task(
|
||||||
|
self.fetch(session, f"{self.config.base_url}{endpoint}", method="GET")
|
||||||
|
)
|
||||||
|
tasks.append(task)
|
||||||
|
|
||||||
|
# 等待所有任务完成
|
||||||
|
for task in tasks:
|
||||||
|
result = await task
|
||||||
|
results.append(result)
|
||||||
|
|
||||||
|
tasks = []
|
||||||
|
await asyncio.sleep(0.1) # 稍微暂停以避免过载
|
||||||
|
|
||||||
|
# 计算统计信息
|
||||||
|
success_count = sum(1 for r in results if r.get("success", False))
|
||||||
|
success_rate = success_count / len(results) if results else 0
|
||||||
|
response_times = [r.get("response_time", 0) for r in results if "response_time" in r]
|
||||||
|
avg_response_time = sum(response_times) / len(response_times) if response_times else 0
|
||||||
|
|
||||||
|
return {
|
||||||
|
"endpoint": endpoint,
|
||||||
|
"method": method,
|
||||||
|
"duration": duration,
|
||||||
|
"concurrency": concurrency,
|
||||||
|
"total_requests": len(results),
|
||||||
|
"success_requests": success_count,
|
||||||
|
"success_rate": success_rate,
|
||||||
|
"avg_response_time": avg_response_time,
|
||||||
|
"min_response_time": min(response_times) if response_times else 0,
|
||||||
|
"max_response_time": max(response_times) if response_times else 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# 测试函数
|
||||||
|
async def run_tests(config: TestConfig):
|
||||||
|
"""运行所有测试"""
|
||||||
|
tester = CosyVoiceAPITester(config)
|
||||||
|
stress_tool = StressTestTool(config)
|
||||||
|
|
||||||
|
logging.info("开始测试CosyVoice API...")
|
||||||
|
|
||||||
|
# 1. 基本端点测试
|
||||||
|
logging.info("测试基本端点...")
|
||||||
|
root_result = tester.test_root_endpoint()
|
||||||
|
status_result = tester.test_status_endpoint()
|
||||||
|
|
||||||
|
# 2. 异常输入测试
|
||||||
|
logging.info("测试异常输入...")
|
||||||
|
abnormal_results = tester.test_abnormal_inputs()
|
||||||
|
|
||||||
|
# 3. 无效参数测试
|
||||||
|
logging.info("测试无效参数...")
|
||||||
|
invalid_speaker_result = tester.test_invalid_speaker()
|
||||||
|
invalid_mode_result = tester.test_invalid_mode()
|
||||||
|
|
||||||
|
# 4. 压力测试
|
||||||
|
logging.info(f"开始压力测试,持续{config.stress_test_duration}秒...")
|
||||||
|
|
||||||
|
# TTS端点压力测试
|
||||||
|
def generate_tts_data():
|
||||||
|
speaker = tester.get_random_speaker()
|
||||||
|
return {
|
||||||
|
"text": f"这是一个压力测试用例 {random.randint(1, 1000)}",
|
||||||
|
"mode": "预训练音色",
|
||||||
|
"speaker": speaker,
|
||||||
|
"seed": random.randint(0, 10000),
|
||||||
|
"stream": random.choice([True, False]),
|
||||||
|
"speed": random.uniform(0.8, 1.2)
|
||||||
|
}
|
||||||
|
|
||||||
|
tts_stress_result = await stress_tool.run_stress_test(
|
||||||
|
endpoint="/tts",
|
||||||
|
duration=config.stress_test_duration,
|
||||||
|
concurrency=config.concurrent_requests,
|
||||||
|
method="POST",
|
||||||
|
data_generator=generate_tts_data
|
||||||
|
)
|
||||||
|
|
||||||
|
# 状态端点压力测试
|
||||||
|
status_stress_result = await stress_tool.run_stress_test(
|
||||||
|
endpoint="/status",
|
||||||
|
duration=min(10, config.stress_test_duration), # 状态端点压力测试时间较短
|
||||||
|
concurrency=config.concurrent_requests,
|
||||||
|
method="GET"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 汇总结果
|
||||||
|
results = {
|
||||||
|
"basic_endpoints": {
|
||||||
|
"root": root_result,
|
||||||
|
"status": status_result
|
||||||
|
},
|
||||||
|
"abnormal_inputs": abnormal_results,
|
||||||
|
"invalid_parameters": {
|
||||||
|
"invalid_speaker": invalid_speaker_result,
|
||||||
|
"invalid_mode": invalid_mode_result
|
||||||
|
},
|
||||||
|
"stress_tests": {
|
||||||
|
"tts": tts_stress_result,
|
||||||
|
"status": status_stress_result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 保存结果
|
||||||
|
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
||||||
|
result_file = config.output_dir / f"test_results_{timestamp}.json"
|
||||||
|
with open(result_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
logging.info(f"测试完成,结果已保存至 {result_file}")
|
||||||
|
|
||||||
|
# 打印摘要
|
||||||
|
logging.info("测试摘要:")
|
||||||
|
logging.info(f"基本端点测试: root {'成功' if root_result.get('success') else '失败'}, status {'成功' if status_result.get('success') else '失败'}")
|
||||||
|
logging.info(f"异常输入测试: {sum(1 for r in abnormal_results if r.get('success'))} 成功, {sum(1 for r in abnormal_results if not r.get('success'))} 失败")
|
||||||
|
logging.info(f"TTS压力测试: 总请求 {tts_stress_result['total_requests']}, 成功率 {tts_stress_result['success_rate']*100:.2f}%, 平均响应时间 {tts_stress_result['avg_response_time']:.2f}s")
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
# 添加一个更激进的高压力测试函数
|
||||||
|
async def run_aggressive_stress_test(config: TestConfig):
|
||||||
|
"""运行更激进的压力测试,尝试找出API服务的极限"""
|
||||||
|
stress_tool = StressTestTool(config)
|
||||||
|
tester = CosyVoiceAPITester(config)
|
||||||
|
|
||||||
|
logging.info("开始进行极限压力测试...")
|
||||||
|
|
||||||
|
# 准备一些短文本以减少处理时间
|
||||||
|
short_texts = [
|
||||||
|
"这是一个简短的测试文本。",
|
||||||
|
"测试语音合成系统。",
|
||||||
|
"快速压力测试用例。",
|
||||||
|
"简短句子测试。",
|
||||||
|
]
|
||||||
|
|
||||||
|
def generate_quick_tts_data():
|
||||||
|
"""生成简短文本的TTS请求数据"""
|
||||||
|
speaker = tester.get_random_speaker()
|
||||||
|
return {
|
||||||
|
"text": random.choice(short_texts),
|
||||||
|
"mode": "预训练音色",
|
||||||
|
"speaker": speaker,
|
||||||
|
"seed": random.randint(0, 10000),
|
||||||
|
"stream": True, # 使用流式处理可能更快
|
||||||
|
"speed": 1.2 # 稍微加快语速
|
||||||
|
}
|
||||||
|
|
||||||
|
# 测试不同并发级别下的性能
|
||||||
|
concurrency_levels = [5, 10, 20, 30, 50]
|
||||||
|
duration = 15 # 每个级别测试15秒
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for concurrency in concurrency_levels:
|
||||||
|
logging.info(f"测试并发级别: {concurrency}")
|
||||||
|
|
||||||
|
result = await stress_tool.run_stress_test(
|
||||||
|
endpoint="/tts",
|
||||||
|
duration=duration,
|
||||||
|
concurrency=concurrency,
|
||||||
|
method="POST",
|
||||||
|
data_generator=generate_quick_tts_data
|
||||||
|
)
|
||||||
|
|
||||||
|
results.append({
|
||||||
|
"concurrency": concurrency,
|
||||||
|
**result
|
||||||
|
})
|
||||||
|
|
||||||
|
# 暂停一段时间让服务器恢复
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
|
||||||
|
# 保存结果
|
||||||
|
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
||||||
|
result_file = config.output_dir / f"extreme_stress_test_{timestamp}.json"
|
||||||
|
with open(result_file, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
logging.info(f"极限压力测试完成,结果已保存至 {result_file}")
|
||||||
|
|
||||||
|
# 打印摘要
|
||||||
|
logging.info("极限压力测试摘要:")
|
||||||
|
for r in results:
|
||||||
|
logging.info(f"并发数: {r['concurrency']}, 总请求: {r['total_requests']}, "
|
||||||
|
f"成功率: {r['success_rate']*100:.2f}%, "
|
||||||
|
f"平均响应时间: {r['avg_response_time']:.2f}s")
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
# 主函数
|
||||||
|
async def main():
|
||||||
|
parser = argparse.ArgumentParser(description="CosyVoice API测试工具")
|
||||||
|
parser.add_argument("--base-url", default="http://localhost:9881", help="API服务基础URL")
|
||||||
|
parser.add_argument("--duration", type=int, default=60, help="压力测试持续时间(秒)")
|
||||||
|
parser.add_argument("--concurrency", type=int, default=10, help="并发请求数")
|
||||||
|
parser.add_argument("--timeout", type=int, default=30, help="请求超时时间(秒)")
|
||||||
|
parser.add_argument("--extreme-test", action="store_true",
|
||||||
|
help="运行极限压力测试")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
config = TestConfig(base_url=args.base_url)
|
||||||
|
config.stress_test_duration = args.duration
|
||||||
|
config.concurrent_requests = args.concurrency
|
||||||
|
config.request_timeout = args.timeout
|
||||||
|
|
||||||
|
if args.extreme_test:
|
||||||
|
await run_aggressive_stress_test(config)
|
||||||
|
else:
|
||||||
|
await run_tests(config)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
40
test_cosyvoice_v2.py
Normal file
40
test_cosyvoice_v2.py
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
from core.providers.tts.cosyvoice import TTSProvider
|
||||||
|
|
||||||
|
async def test_cosyvoice_tts():
|
||||||
|
# 配置参数
|
||||||
|
config = {
|
||||||
|
"api_url": "http://127.0.0.1:9881/tts",
|
||||||
|
"mode": "3s极速复刻", # 预训练音色, 3s极速复刻, 跨语种复刻, 自然语言控制
|
||||||
|
"speaker": "anna",
|
||||||
|
"prompt_audio": "data/voice/佩奇-孩子们听到没有快点下来不然你们就吃不到蛋糕咯.mp3",
|
||||||
|
"prompt_text": "孩子们听到没有快点下来不然你们就吃不到蛋糕咯",
|
||||||
|
"instruct_text": "请用开心的语气说话",
|
||||||
|
"seed": 0,
|
||||||
|
"speed": 1.0,
|
||||||
|
"stream": False,
|
||||||
|
"timeout": 30,
|
||||||
|
"output_file": "tmp/",
|
||||||
|
"response_format": "wav"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 确保输出目录存在
|
||||||
|
os.makedirs(config["output_file"], exist_ok=True)
|
||||||
|
|
||||||
|
# 创建TTS提供者实例
|
||||||
|
tts_provider = TTSProvider(config, delete_audio_file=False)
|
||||||
|
|
||||||
|
# 测试文本
|
||||||
|
text = "你好呀,小睿睿,我是你的好朋友佩奇,我有个小弟弟叫做乔治,她最喜欢恐龙,嗷呜!"
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 生成TTS
|
||||||
|
output_file = await tts_provider.text_to_speak(text, os.path.join(config["output_file"], "test_output.wav"))
|
||||||
|
print(f"TTS生成成功,输出文件: {output_file}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"TTS生成失败: {str(e)}")
|
||||||
|
|
||||||
|
# 运行测试
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(test_cosyvoice_tts())
|
||||||
126
websocket_test.py
Normal file
126
websocket_test.py
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
import asyncio
|
||||||
|
import websockets
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
import logging
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
# 配置日志
|
||||||
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# 命令行参数
|
||||||
|
parser = argparse.ArgumentParser(description='测试WebSocket服务器连接')
|
||||||
|
parser.add_argument('--url', type=str, default='ws://frp-bar.com:28103', help='WebSocket服务器URL')
|
||||||
|
parser.add_argument('--token', type=str, default='xZ8$kL2@qT9mW5#', help='访问令牌')
|
||||||
|
parser.add_argument('--mac', type=str, default='24:0A:C4:1D:3B:F0', help='设备MAC地址')
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
async def test_connection():
|
||||||
|
# 生成随机UUID作为客户端ID
|
||||||
|
client_id = str(uuid.uuid4())
|
||||||
|
device_mac = args.mac
|
||||||
|
token = args.token
|
||||||
|
ws_url = args.url
|
||||||
|
|
||||||
|
# 准备连接头信息
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'Bearer {token}',
|
||||||
|
'Protocol-Version': '1',
|
||||||
|
'Device-Id': device_mac,
|
||||||
|
'Client-Id': client_id
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
logger.info(f"尝试连接到 {ws_url}")
|
||||||
|
logger.info(f"使用设备ID: {device_mac}, 客户端ID: {client_id}")
|
||||||
|
|
||||||
|
# 建立WebSocket连接
|
||||||
|
async with websockets.connect(ws_url, extra_headers=headers) as websocket:
|
||||||
|
logger.info("连接已建立,发送hello消息")
|
||||||
|
|
||||||
|
# 发送hello消息
|
||||||
|
hello_message = {
|
||||||
|
"type": "hello",
|
||||||
|
"version": 1,
|
||||||
|
"transport": "websocket",
|
||||||
|
"audio_params": {
|
||||||
|
"format": "opus",
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"channels": 1,
|
||||||
|
"frame_duration": 60
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await websocket.send(json.dumps(hello_message))
|
||||||
|
logger.info(f"已发送: {json.dumps(hello_message, ensure_ascii=False)}")
|
||||||
|
|
||||||
|
# 接收服务器响应
|
||||||
|
response = await websocket.recv()
|
||||||
|
try:
|
||||||
|
response_json = json.loads(response)
|
||||||
|
logger.info(f"服务器响应: {json.dumps(response_json, indent=2, ensure_ascii=False)}")
|
||||||
|
|
||||||
|
# 如果收到hello响应,发送一个listen消息进行进一步测试
|
||||||
|
if response_json.get("type") == "hello":
|
||||||
|
logger.info("握手成功,发送listen消息测试...")
|
||||||
|
|
||||||
|
# 发送开始监听消息
|
||||||
|
listen_message = {
|
||||||
|
"session_id": "", # WebSocket协议不需要session_id
|
||||||
|
"type": "listen",
|
||||||
|
"state": "start",
|
||||||
|
"mode": "manual" # 使用手动模式
|
||||||
|
}
|
||||||
|
|
||||||
|
await websocket.send(json.dumps(listen_message))
|
||||||
|
logger.info(f"已发送: {json.dumps(listen_message, ensure_ascii=False)}")
|
||||||
|
|
||||||
|
# 等待服务器响应(可能是任何类型的消息)
|
||||||
|
response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
|
||||||
|
try:
|
||||||
|
response_json = json.loads(response)
|
||||||
|
logger.info(f"服务器响应: {json.dumps(response_json, indent=2, ensure_ascii=False)}")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
# 可能是二进制数据
|
||||||
|
logger.info(f"接收到非JSON响应,可能是二进制数据,长度: {len(response)} 字节")
|
||||||
|
|
||||||
|
# 发送停止监听消息
|
||||||
|
stop_message = {
|
||||||
|
"session_id": "",
|
||||||
|
"type": "listen",
|
||||||
|
"state": "stop"
|
||||||
|
}
|
||||||
|
|
||||||
|
await websocket.send(json.dumps(stop_message))
|
||||||
|
logger.info(f"已发送: {json.dumps(stop_message, ensure_ascii=False)}")
|
||||||
|
|
||||||
|
# 再等待一个响应
|
||||||
|
try:
|
||||||
|
response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
|
||||||
|
try:
|
||||||
|
response_json = json.loads(response)
|
||||||
|
logger.info(f"服务器响应: {json.dumps(response_json, indent=2, ensure_ascii=False)}")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.info(f"接收到非JSON响应,可能是二进制数据,长度: {len(response)} 字节")
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
logger.info("等待响应超时,这可能是正常的")
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
# 如果响应不是JSON格式
|
||||||
|
logger.warning(f"接收到非JSON响应: {response[:100]}...")
|
||||||
|
|
||||||
|
logger.info("测试完成,连接正常工作")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"连接测试失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
result = asyncio.run(test_connection())
|
||||||
|
if result:
|
||||||
|
logger.info("✅ 公网连接测试成功!WebSocket服务器可以通过公网访问。")
|
||||||
|
else:
|
||||||
|
logger.error("❌ 公网连接测试失败!请检查内网穿透和服务器配置。")
|
||||||
Loading…
Reference in a new issue