diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 68174a38c..42a58dbe6 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -4,6 +4,7 @@ on: push: tags: - 'v*.*.*' # 只在以 v 开头的标签推送时触发,例如 v1.0.0 + workflow_dispatch: jobs: release: @@ -41,7 +42,13 @@ jobs: - name: Extract version from tag id: get_version run: | - echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV + if [[ "$GITHUB_REF" =~ ^refs/tags/v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then + echo "VERSION=${BASH_REMATCH[1]}" >> $GITHUB_ENV + echo "IS_VERSION=true" >> $GITHUB_ENV + else + echo "VERSION=latest" >> $GITHUB_ENV + echo "IS_VERSION=false" >> $GITHUB_ENV + fi # 构建 xiaozhi-server 镜像 - name: Build and push xiaozhi-server @@ -51,8 +58,7 @@ jobs: file: Dockerfile-server push: true tags: | - ghcr.io/${{ github.repository }}:server_${{ env.VERSION }} - ghcr.io/${{ github.repository }}:server_latest + ${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:server_{1}\nghcr.io/{0}:server_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:server_latest', github.repository) }} platforms: linux/amd64,linux/arm64 # 构建 manager-api 镜像 @@ -63,6 +69,5 @@ jobs: file: Dockerfile-web push: true tags: | - ghcr.io/${{ github.repository }}:web_${{ env.VERSION }} - ghcr.io/${{ github.repository }}:web_latest + ${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:web_{1}\nghcr.io/{0}:web_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:web_latest', github.repository) }} platforms: linux/amd64,linux/arm64 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 985ec651d..0a684e6ac 100644 --- a/.gitignore +++ b/.gitignore @@ -75,6 +75,7 @@ docs/_build/ # PyBuilder .pybuilder/ target/ +*.pid # Jupyter Notebook .ipynb_checkpoints diff --git a/README.md b/README.md index 191790bcf..810ce5144 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,28 @@ -[![SVG Banners](https://svg-banners.vercel.app/api?type=origin&text1=你好😃,小智📟&text2=开源小智ESP-32后端服务&width=830&height=210)](https://github.com/xinnan-tech/xiaozhi-esp32-server) +[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) + + +

小智后端服务xiaozhi-esp32-server

+

+本项目为开源智能硬件项目 +xiaozhi-esp32提供后端服务
+根据小智通信协议使用Python实现
+帮助您快速搭建小智服务器 +

+ +

+English +· 简体中文 +· 更新日志 +· 部署文档 +· 反馈问题 +

+

+ + GitHub Contributors + - GitHub Contributors + GitHub Contributors Issues @@ -9,15 +30,14 @@ GitHub pull requests + + GitHub pull requests + + + stars +

-# 小智 ESP-32 后端服务(xiaozhi-esp32-server) - -(中文 | [English](README_en.md)) - -本项目为开源智能硬件项目 [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) -提供后端服务。根据 [小智通信协议](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh) 使用 `Python` 实现。 - --- ## 适用人群 👥 @@ -108,20 +128,7 @@ ## 系统要求与部署前提 🖥️ -- **硬件**:一套兼容 `xiaozhi-esp32` - 的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。 - -- **电脑或服务器**:建议 4 核 CPU、8G 内存的电脑。如果开启ASR也使用API,可运行在2核CPU、2G内存的服务器中。 -- **固件编译**:请将本后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译`xiaozhi-esp32`固件并烧录到设备上。 - -![图片](docs/images/deploy.png) - -如果你没有esp32相关的硬件设备,但是非常想体验该项目,可以使用以下的项目让你的电脑、手机模拟成esp32设备。 - -- [小智安卓端](https://github.com/TOM88812/xiaozhi-android-client) -- [小智电脑端](https://github.com/Huang-junsen/py-xiaozhi) - -如果你是一名软件开发者,这里有一份[《致开发者的公开信》](docs/contributor_open_letter.md),欢迎加入! +建议 4 核 CPU、8G 内存的电脑。如果开启ASR也使用API,可运行在2核CPU、2G内存的服务器中。[请参考部署架构图](./docs/images/deploy.png) --- @@ -144,115 +151,9 @@ server: --- -## 功能清单 ✨ +## 部署方式 🚀 -### 已实现 ✅ - -- **通信协议** - 基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。 -- **对话交互** - 支持唤醒对话、手动对话及实时打断。长时间无对话时自动休眠 -- **意图识别** - 支持使用LLM意图识别、function call函数调用,减少硬编码意图判断 -- **多语言识别** - 支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。 -- **LLM 模块** - 支持灵活切换 LLM 模块,默认使用 ChatGLMLLM,也可选用阿里百炼、DeepSeek、Ollama 等接口。 -- **TTS 模块** - 支持 EdgeTTS(默认)、火山引擎豆包 TTS 等多种 TTS 接口,满足语音合成需求。 -- **记忆功能** - 支持超长记忆、本地总结记忆、无记忆三种模式,满足不同场景需求。 -- **IOT功能** - 支持管理注册设备IOT功能,支持基于对话上下文语境下的智能物联网控制。 - -### 正在开发 🚧 - -- 多种心情模式 -- 智控台webui - -想了解具体开发进度,[请点击这里](https://github.com/users/xinnan-tech/projects/3) - -![图片](docs/images/webui.png) ---- - -## 本项目支持的平台/组件列表 📋 - -### LLM 语言模型 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:------------------:|:---------------------:|:-----------:|:-----------------------------------------------------------------------------------------------------------------------:| -| LLM | 阿里百炼 (AliLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://bailian.console.aliyun.com/?apiKey=1#/api-key) | -| LLM | DoubaoLLM | openai 接口调用 | 消耗 token | [点击申请密钥](https://console.volcengine.com/ark/region:ark+cn-beijing/model/detail?Id=doubao-pro-32k&projectName=undefined) | -| LLM | 深度求索 (DeepSeekLLM) | openai 接口调用 | 消耗 token | [点击申请密钥](https://platform.deepseek.com/) | -| LLM | 智谱(ChatGLMLLM) | openai 接口调用 | 免费 | 虽然免费,仍需[点击申请密钥](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| LLM | OllamaLLM | ollama 接口调用 | 免费/消耗 token | 需预先下载模型(`ollama pull`),服务地址:`http://localhost:11434` | -| LLM | DifyLLM | dify 接口调用 | 免费/消耗 token | 本地化部署,注意配置提示词需在 Dify 控制台设置 | -| LLM | FastgptLLM | fastgpt 接口调用 | 免费/消耗 token | 本地化部署,注意配置提示词需在 Fastgpt 控制台设置 | -| LLM | GeminiLLM | gemini 接口调用 | 免费 | [点击申请密钥](https://aistudio.google.com/apikey) | -| LLM | CozeLLM | coze 接口调用 | 消耗 token | 需提供 bot_id、user_id 及个人令牌 | - -实际上,任何支持 openai 接口调用的 LLM 均可接入使用。 - ---- - -### TTS 语音合成 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:----------------------:|:----:|:--------:|:-------------------------------------------------------------------------:| -| TTS | EdgeTTS | 接口调用 | 免费 | 默认 TTS,基于微软语音合成技术 | -| TTS | 火山引擎豆包 TTS (DoubaoTTS) | 接口调用 | 消耗 token | [点击创建密钥](https://console.volcengine.com/speech/service/8);建议使用付费版本以获得更高并发 | -| TTS | AliyunTTS | 接口调用 | 消耗 token | [点击创建密钥](https://nls-portal.console.aliyun.com/applist) | -| TTS | CosyVoiceSiliconflow | 接口调用 | 消耗 token | 需申请硅基流动 API 密钥;输出格式为 wav | -| TTS | TTS302AI | 接口调用 | 消耗 token | [点击创建密钥](https://dash.302.ai/apis/list) | -| TTS | CozeCnTTS | 接口调用 | 消耗 token | 需提供 Coze API key;输出格式为 wav | -| TTS | GizwitsTTS | 接口调用 | 消耗 token | [点击创建密钥](https://agentrouter.gizwitsapi.com) | -| TTS | ACGNTTS | 接口调用 | 消耗 token | [联系网站管理员购买密钥](www.ttson.cn) | -| TTS | OpenAITTS | 接口调用 | 消耗 token | 境外使用,境外购买 | -| TTS | FishSpeech | 接口调用 | 免费/自定义 | 本地启动 TTS 服务;启动方法见配置文件内说明 | -| TTS | GPT_SOVITS_V2 | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 | -| TTS | GPT_SOVITS_V3 | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 | -| TTS | MinimaxTTS | 接口调用 | 免费/自定义 | 本地启动 TTS 服务,适用于个性化语音合成场景 | - ---- - -### VAD 语音活动检测 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:---------:|:----:|:----:|:--:| -| VAD | SileroVAD | 本地使用 | 免费 | | - ---- - -### ASR 语音识别 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:---:|:---------:|:----:|:----:|:--:| -| ASR | FunASR | 本地使用 | 免费 | | -| ASR | SherpaASR | 本地使用 | 免费 | | -| ASR | DoubaoASR | 接口调用 | 收费 | | - - ---- - -### Memory 记忆存储 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:------:|:---------------:|:----:|:---------:|:--:| -| Memory | mem0ai | 接口调用 | 1000次/月额度 | | -| Memory | mem_local_short | 本地总结 | 免费 | | - ---- - -### Intent 意图识别 - -| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | -|:------:|:-------------:|:----:|:-------:|:---------------------:| -| Intent | intent_llm | 接口调用 | 根据LLM收费 | 通过大模型识别意图,通用性强 | -| Intent | function_call | 接口调用 | 根据LLM收费 | 通过大模型函数调用完成意图,速度快,效果好 | - ---- - -## 使用方式 🚀 +[![Banners](docs/images/banner2.png)](./docs/Deployment.md) ### 一、[部署文档](./docs/Deployment.md) @@ -282,143 +183,112 @@ server: ## 常见问题 ❓ -### 1、为什么我说的话,小智识别出来很多韩文、日文、英文?🇰🇷 +如遇到问题或产品建议反馈[点这里](docs/FAQ.md)。 -建议:检查一下`models/SenseVoiceSmall`是否已经有`model.pt` -文件,如果没有就要下载,查看这里[下载语音识别模型文件](docs/Deployment.md#模型文件) +--- -### 2、为什么会出现“TTS 任务出错 文件不存在”?📁 +## 产品生态 👬 +小智是一个生态,当你使用这个产品时,也可以看看其他在这个生态圈的优秀项目 -建议:检查一下是否正确使用`conda` 安装了`libopus`和`ffmpeg`库。 +- [小智安卓客户端](https://github.com/TOM88812/xiaozhi-android-client) -如果没有安装,就安装 + 一个基于xiaozhi-server的Android、IOS语音对话应用,支持实时语音交互和文字对话。现在是flutter版本,打通IOS、Android端。 +- [小智电脑客户端](https://github.com/Huang-junsen/py-xiaozhi) -``` -conda install conda-forge::libopus -conda install conda-forge::ffmpeg -``` + 该项目提供了一个基于 Python 实现的小白 AI 客户端,使得在不具备实体硬件条件的情况下,依然能够体过代码体验小智 AI 的功能。主要功能包括 AI 语音交互、视觉多模态识别、IoT 设备集成、联网音乐播放、语音唤醒、自动对话模式、图形化界面、命令行模式、跨平台支持、音量控制、会话管理、加密音频传输、自动验证码处理等。 +- [小智Java服务端](https://github.com/joey-zhou/xiaozhi-esp32-server-java) -### 3、TTS 经常失败,经常超时 ⏰ + 小智开源后端服务 Java 版本是一个基于 Java 的开源项目,它包括前后端的服务,旨在为用户提供一个完整的后端服务解决方案。 +--- +## 功能清单 ✨ -建议:如果 `EdgeTTS` 经常失败,请先检查是否使用了代理(梯子)。如果使用了,请尝试关闭代理后再试; -如果用的是火山引擎的豆包 TTS,经常失败时建议使用付费版本,因为测试版本仅支持 2 个并发。 +### 已实现 ✅ -### 4、如何提高小智对话响应速度? ⚡ +- **通信协议** + 基于 `xiaozhi-esp32` 协议,通过 WebSocket 实现数据交互。 +- **对话交互** + 支持唤醒对话、手动对话及实时打断。长时间无对话时自动休眠 +- **意图识别** + 支持使用LLM意图识别、function call函数调用,减少硬编码意图判断 +- **多语言识别** + 支持国语、粤语、英语、日语、韩语(默认使用 FunASR)。 +- **LLM 模块** + 支持灵活切换 LLM 模块,默认使用 ChatGLMLLM,也可选用阿里百炼、DeepSeek、Ollama 等接口。 +- **TTS 模块** + 支持 EdgeTTS(默认)、火山引擎豆包 TTS 等多种 TTS 接口,满足语音合成需求。 +- **记忆功能** + 支持超长记忆、本地总结记忆、无记忆三种模式,满足不同场景需求。 +- **IOT功能** + 支持管理注册设备IOT功能,支持基于对话上下文语境下的智能物联网控制。 -本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决“跑得动”的问题,再优化“跑得快”。 -如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺): +### 正在开发 🚧 -| 影响因素 | 因素值 | -|:-----:|:----------------:| -| 测试地点 | 广东省广州市海珠区 | -| 测试时间 | 2025年2月19日 12:52 | -| 宽带运营商 | 中国联通 | +- 多种心情模式 +- 智控台webui -测试方法: +想了解具体开发进度,[请点击这里](https://github.com/users/xinnan-tech/projects/3) -1、把各组件的密钥配置上去,只有配置了密钥的组件才参与测试。 +如果你是一名软件开发者,这里有一份[《致开发者的公开信》](docs/contributor_open_letter.md),欢迎加入! -2、配置完密钥后,执行以下方法 +--- -``` -# 进入项目根目录,执行以下命令: -conda activate xiaozhi-esp32-server -python performance_tester.py -``` +## 本项目支持的平台/组件列表 📋 -生成报告如下 +### LLM 语言模型 -LLM 性能排行: +| 使用方式 | 支持平台 | 免费平台 | +|:---:|:---:|:---:| +| openai 接口调用 | 阿里百炼、火山引擎豆包、深度求索、智谱ChatGLM、Gemini | 智谱ChatGLM、Gemini | +| ollama 接口调用 | Ollama | - | +| dify 接口调用 | Dify | - | +| fastgpt 接口调用 | Fastgpt | - | +| coze 接口调用 | Coze | - | -| 模块名称 | 平均首Token时间 | 平均总响应时间 | -|:-----------|:-----------|:--------| -| AliLLM | 0.547s | 1.485s | -| ChatGLMLLM | 0.677s | 3.057s | +实际上,任何支持 openai 接口调用的 LLM 均可接入使用。 -TTS 性能排行: +--- -| 模块名称 | 平均合成时间 | -|----------------------|--------| -| EdgeTTS | 1.019s | -| DoubaoTTS | 0.503s | -| CosyVoiceSiliconflow | 3.732s | +### TTS 语音合成 -推荐配置组合 (综合响应速度): +| 使用方式 | 支持平台 | 免费平台 | +|:---:|:---:|:---:| +| 接口调用 | EdgeTTS、火山引擎豆包TTS、腾讯云、阿里云TTS、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS | EdgeTTS、CosyVoiceSiliconflow(部分) | +| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、MinimaxTTS | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、MinimaxTTS | -| 组合方案 | 综合得分 | LLM首Token | TTS合成 | -|-------------------------------|-------|-----------|--------| -| AliLLM + DoubaoTTS | 0.539 | 0.547s | 0.503s | -| AliLLM + EdgeTTS | 0.642 | 0.547s | 1.019s | -| ChatGLMLLM + DoubaoTTS | 0.642 | 0.677s | 0.503s | -| ChatGLMLLM + EdgeTTS | 0.745 | 0.677s | 1.019s | -| AliLLM + CosyVoiceSiliconflow | 1.184 | 0.547s | 3.732s | +--- -### 结论 🔍 +### VAD 语音活动检测 -`2025年2月19日`,如果我的电脑在`广东省广州市海珠区`,且使用的是`中国联通`网络,我会优先使用: +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:---:|:---------:|:----:|:----:|:--:| +| VAD | SileroVAD | 本地使用 | 免费 | | -- LLM:`AliLLM` -- TTS:`DoubaoTTS` +--- -### 5、我说话很慢,停顿时小智老是抢话 🗣️ +### ASR 语音识别 -建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`): +| 使用方式 | 支持平台 | 免费平台 | +|:---:|:---:|:---:| +| 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR | +| 接口调用 | DoubaoASR | - | -```yaml -VAD: - SileroVAD: - threshold: 0.5 - model_dir: models/snakers4_silero-vad - min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大 -``` +--- -### 6、我想通过小智控制电灯、空调、远程开关机等操作 💡 +### Memory 记忆存储 -本项目,支持以工具调用的方式控制HomeAssistant设备 +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:------:|:---------------:|:----:|:---------:|:--:| +| Memory | mem0ai | 接口调用 | 1000次/月额度 | | +| Memory | mem_local_short | 本地总结 | 免费 | | -1、首先选择一款支持function call支持的LLM,例如`ChatGLMLLM`。 +--- -2、在配置文件中,将 `selected_module.Intent` 设置为 `function_call`。 +### Intent 意图识别 -3、登录`HomeAssistant`,点击`左下角个人`,切换`安全`导航栏,划到底部`长期访问令牌`生成api_key。 - -在配置文件中,配置好你的home assistant的`devices`(被控制的设备)和`api_key`和`base_url`等信息。例如: - -``` yaml -plugins - home_assistant: - devices: - - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1 - - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1 - base_url: http://你的homeassistant地址:8123 - api_key: 你的home assistant api访问令牌 -``` - -最后,允许function_call 插件在配置文件中启用`hass_get_state`(必须)、`hass_set_state`(必须)、`hass_play_music`(不想用ha听音乐可以不启动),例如: - -``` yaml -Intent: - ... - function_call: - type: nointent - functions: - - change_role - - get_weather - - get_news - - hass_get_state - - hass_set_state - - hass_play_music -``` - -### 7、更多问题,可联系我们反馈 💬 - -我们的联系方式放在[百度网盘中,点击前往](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),提取码是`223y`。 - -网盘里有“硬件烧录QQ群”、“开源服务端交流群”、“产品建议联系人” 三张图片,请根据需要选择加入。 - -- 硬件烧录QQ群:适用于硬件烧录问题 -- 开源服务端交流群:适用于服务端问题 -- 产品建议联系人:适用于产品功能、产品设计等建议 +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:------:|:-------------:|:----:|:-------:|:---------------------:| +| Intent | intent_llm | 接口调用 | 根据LLM收费 | 通过大模型识别意图,通用性强 | +| Intent | function_call | 接口调用 | 根据LLM收费 | 通过大模型函数调用完成意图,速度快,效果好 | --- @@ -433,4 +303,4 @@ Intent: Star History Chart - + \ No newline at end of file diff --git a/README_en.md b/README_en.md index 883066752..1dd705549 100644 --- a/README_en.md +++ b/README_en.md @@ -1,8 +1,29 @@ +[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) + +
+

Xiaozhi Backend Server xiaozhi-esp32-server

+
-[![SVG Banners](https://svg-banners.vercel.app/api?type=origin&text1=Hello😃,%20XiaoZhi📟&text2=Open%20Source%20XiaoZhi%20ESP-32%20Backend%20Service&width=830&height=210)](https://github.com/xinnan-tech/xiaozhi-esp32-server)

+This project provides backend services for the open-source smart hardware project +xiaozhi-esp32
+Implemented in Python according to the Xiaozhi Communication Protocol
+Helping you quickly set up your Xiaozhi server +

+ +

+简体中文 +· English +· Changelog +· Deployment Guide +· Report Issues +

+

+ + GitHub Contributors + - GitHub Contributors + GitHub Contributors Issues @@ -10,79 +31,114 @@ GitHub pull requests + + GitHub pull requests + + + GitHub pull requests +

-# XiaoZhi ESP-32 Backend Service (xiaozhi-esp32-server) - -([中文](README.md) | English) - -This project provides the backend service for the open source smart hardware project [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32). It is implemented in `Python` based on the [XiaoZhi Communication Protocol](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh). - --- -## Target Audience 👥 +## Target Users 👥 -This project is designed to be used in conjunction with ESP32 hardware devices. If you have already purchased an ESP32 device, successfully connected to the backend service deployed by XieGe, and now wish to set up your own `xiaozhi-esp32` backend service, then this project is perfect for you. +This project requires ESP32 hardware devices. If you have purchased ESP32-related hardware, successfully connected to Brother Xia's backend service, and wish to set up your own `xiaozhi-esp32` backend service, then this project is perfect for you. -Want to see it in action? Check out the videos 🎥 +Want to see it in action? Check out these videos 🎥 + + + + + +
- - - XiaoZhi ESP32 connecting to a custom backend model - - + + + Xiaozhi esp32 connecting to your own backend model + + - - - Custom Voice - - + + + Custom voice + + - - - Conversing in Cantonese - - + + + Communicating in Cantonese + + - - - Control Home Appliances - - + + + Control home appliances + + - - - Lowest Cost Configuration - - + + + Lowest cost configuration + + +
+ + + Custom voice + + + + + Play music + + + + + + Weather plugin + + + + + + IOT command control device + + + + + + News broadcast + +
--- -## System Requirements and Deployment Prerequisites 🖥️ +## System Requirements and Prerequisites 🖥️ -- **Hardware**: A set of devices compatible with `xiaozhi-esp32` (for specific models, please refer to [this link](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf)). -- **Server**: A computer with at least a 4-core CPU and 8GB of memory. -- **Firmware Compilation**: Please update the backend service API endpoint in the `xiaozhi-esp32` project, then recompile the firmware and flash it to your device. +- **Computer or Server**: Recommended 4-core CPU, 8GB RAM computer. If using ASR with API, can run on a 2-core CPU, 2GB RAM server. +- **Update Client Interface**: Please update the backend service interface address in the client. --- ## Warning ⚠️ -This project is relatively new and has not yet undergone network security evaluations. **Do not use it in a production environment.** +1. This is open-source software. This software and any third-party API service providers it interfaces with (including but not limited to speech recognition, large language models, speech synthesis, and other platforms) have no commercial partnership. We do not provide any form of guarantee for their service quality or financial security. +We recommend users prioritize service providers with relevant business licenses and carefully read their service agreements and privacy policies. This software does not host any account keys, does not participate in fund transfers, and does not bear the risk of recharge fund losses. -If you deploy this project on a public network for learning purposes, be sure to enable protection in the configuration file `config.yaml`: +2. This project is relatively new and has not yet passed network security testing. Please do not use it in production environments. If you deploy this project for learning purposes in a public network environment, please make sure to enable protection in the `config.yaml` configuration file: ```yaml server: @@ -91,202 +147,151 @@ server: enabled: true ``` -Once protection is enabled, you will need to validate the machine's token or MAC address based on your actual situation. Please refer to the configuration documentation for details. +After enabling protection, you need to verify the machine's token or MAC address according to actual circumstances. Please refer to the configuration documentation for details. --- +## Deployment Methods 🚀 + +### I. [Deployment Guide](./docs/Deployment.md) + +This project supports three deployment methods. You can choose based on your actual needs. + +1. [Quick Docker Deployment](./docs/Deployment.md) + +Suitable for regular users who want to quickly experience without much environment configuration. The downside is that pulling the image can be slow. Video tutorial available: [Beautiful expert teaches Docker deployment](https://www.bilibili.com/video/BV1RNQnYDE5t) + +2. [Deploy Using Docker Environment](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2) + +For software engineers who have Docker installed and want to make custom code modifications. + +3. [Local Source Code Run](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%89%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C) + +Suitable for users familiar with `Conda` environment or who want to build the running environment from scratch. + +For scenarios requiring higher response speed, we recommend using the local source code run method to reduce additional overhead. Video tutorial available: [Handsome expert teaches source code deployment](https://www.bilibili.com/video/BV1GvQWYZEd2) + +### II. [Firmware Compilation](./docs/firmware-build.md) + +Click here to view the detailed process of [firmware compilation](./docs/firmware-build.md). + +After successful flashing and network connection, wake up Xiaozhi using the wake word and pay attention to the console output on the server side. + +--- + +## Common Questions ❓ + +For issues or product suggestions, please [click here](docs/FAQ.md). + +--- + +## Product Ecosystem 👬 +Xiaozhi is an ecosystem. When using this product, you might want to check out other excellent projects in this ecosystem: + +- [Xiaozhi Android Client](https://github.com/TOM88812/xiaozhi-android-client) + A voice dialogue application based on xiaozhi-server for Android and iOS, supporting real-time voice interaction and text dialogue. Now in Flutter version, supporting both iOS and Android. +- [Xiaozhi PC Client](https://github.com/Huang-junsen/py-xiaozhi) + This project provides a Python-based Xiaobai AI client, allowing you to experience Xiaozhi AI features through code even without physical hardware. Main features include AI voice interaction, visual multimodal recognition, IoT device integration, online music playback, voice wake-up, automatic dialogue mode, graphical interface, command-line mode, cross-platform support, volume control, session management, encrypted audio transmission, automatic verification code processing, etc. +- [Xiaozhi Java Server](https://github.com/joey-zhou/xiaozhi-esp32-server-java) + + The Xiaozhi open-source backend service Java version is a Java-based open-source project that includes both frontend and backend services, aiming to provide users with a complete backend service solution. +--- ## Feature List ✨ ### Implemented ✅ - **Communication Protocol** - Based on the `xiaozhi-esp32` protocol, data exchange is implemented via WebSocket. + Based on `xiaozhi-esp32` protocol, implementing data interaction through WebSocket. - **Dialogue Interaction** - Supports wake-up dialogues, manual conversations, and real-time interruptions. Automatically enters sleep mode after long periods of inactivity. -- **Multilingual Recognition** - Supports Mandarin, Cantonese, English, Japanese, and Korean (default using FunASR). + Supports wake-up dialogue, manual dialogue, and real-time interruption. Automatically sleeps after long periods without dialogue +- **Intent Recognition** + Supports LLM intent recognition and function call, reducing hard-coded intent judgment +- **Multi-language Recognition** + Supports Mandarin, Cantonese, English, Japanese, Korean (default using FunASR). - **LLM Module** - Allows flexible switching of LLM modules. The default is ChatGLMLLM, with options to use AliLLM, DeepSeek, Ollama, and others. + Supports flexible switching of LLM modules, default using ChatGLMLLM, can also use Alibaba Bailian, DeepSeek, Ollama, and other interfaces. - **TTS Module** - Supports multiple TTS interfaces including EdgeTTS (default) and Volcano Engine Doubao TTS to meet speech synthesis requirements. + Supports EdgeTTS (default), Volcano Engine Doubao TTS, and other TTS interfaces to meet speech synthesis needs. +- **Memory Function** + Supports ultra-long memory, local summary memory, and no memory modes to meet different scenario needs. +- **IOT Function** + Supports managing registered device IOT functions, supporting intelligent IoT control based on dialogue context. -### In Development 🚧 +### Under Development 🚧 -- Conversation Memory Feature -- Multiple Mood Modes -- Smart Control Panel Web UI +- Multiple mood modes +- Smart control panel webui -![Screenshot](docs/images/webui.png) +To learn about specific development progress, [click here](https://github.com/users/xinnan-tech/projects/3) + +If you are a software developer, here's an [Open Letter to Developers](docs/contributor_open_letter.md), welcome to join! --- -## Supported Platforms/Components 📋 +## Supported Platforms/Components List 📋 -### LLM +### LLM Language Models -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:-----------------------------:|:-----------------------------:|:-----------------:|:-------------------------------------------------------------------------:| -| LLM | AliLLM (阿里百炼) | OpenAI API call | Token consumption | [Click to apply for API key](https://bailian.console.aliyun.com/?apiKey=1#/api-key) | -| LLM | DeepSeekLLM (深度求索) | OpenAI API call | Token consumption | [Click to apply for API key](https://platform.deepseek.com/) | -| LLM | ChatGLMLLM (智谱) | OpenAI API call | Free | Although free, you still need to [click to apply for an API key](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) | -| LLM | OllamaLLM | Ollama API call | Free/Custom | Requires pre-downloading the model (`ollama pull`); service URL: `http://localhost:11434` | -| LLM | DifyLLM | Dify API call | Token consumption | For local deployment. Note that prompt configuration must be set in the Dify console. | -| LLM | GeminiLLM | Gemini API call | Free | [Click to apply for API key](https://aistudio.google.com/apikey) | -| LLM | CozeLLM | Coze API call | Token consumption | Requires providing bot_id, user_id, and personal token. | -| LLM | Home Assistant | Home Assistant voice assistant API call | Free | Requires providing a Home Assistant token. | +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| openai interface call | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini | +| ollama interface call | Ollama | - | +| dify interface call | Dify | - | +| fastgpt interface call | Fastgpt | - | +| coze interface call | Coze | - | -In fact, any LLM that supports OpenAI API calls can be integrated. +In fact, any LLM supporting openai interface calls can be integrated. --- -### TTS +### TTS Speech Synthesis -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:--------------------------------------:|:------------:|:-----------------:|:--------------------------------------------------------------------------------------:| -| TTS | EdgeTTS | API call | Free | Default TTS based on Microsoft's speech synthesis technology. | -| TTS | DoubaoTTS (火山引擎豆包 TTS) | API call | Token consumption | [Click to create an API key](https://console.volcengine.com/speech/service/8); it is recommended to use the paid version for higher concurrency. | -| TTS | CosyVoiceSiliconflow | API call | Token consumption | Requires application for the Siliconflow API key; output format is WAV. | -| TTS | CozeCnTTS | API call | Token consumption | Requires providing a Coze API key; output format is WAV. | -| TTS | FishSpeech | API call | Free/Custom | Starts a local TTS service; see the configuration file for startup instructions. | -| TTS | GPT_SOVITS_V2 | API call | Free/Custom | Starts a local TTS service, suitable for personalized speech synthesis scenarios. | +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| Interface Call | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS | EdgeTTS, CosyVoiceSiliconflow(partial) | +| Local Service | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS | --- -### VAD +### VAD Voice Activity Detection -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:-------------------:|:------------:|:-------------:|:-------:| -| VAD | SileroVAD | Local | Free | | +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:---:|:---------:|:----:|:----:|:--:| +| VAD | SileroVAD | Local Use | Free | | --- -### ASR +### ASR Speech Recognition -| Type | Platform Name | Usage Method | Pricing Model | Remarks | -|:----:|:-------------------:|:------------:|:-------------:|:-------:| -| ASR | FunASR | Local | Free | | -| ASR | SherpaASR | Local | Free | | -| ASR | DoubaoASR | API call | Paid | | +| Usage Method | Supported Platforms | Free Platforms | +|:---:|:---:|:---:| +| Local Use | FunASR, SherpaASR | FunASR, SherpaASR | +| Interface Call | DoubaoASR | - | --- -## Usage 🚀 +### Memory Storage -### 1. [Deployment Documentation](./docs/Deployment.md) - -This project supports three deployment methods. Choose the one that best fits your needs. - -The documentation provided here is a **written tutorial**. If you prefer a **video tutorial**, you can refer to [this expert's hands-on guide](https://www.bilibili.com/video/BV1gePuejEvT). - -Combining both the written and video tutorials can help you get started more quickly. - -1. [Docker Quick Deployment](./docs/Deployment.md) - Suitable for general users who want a quick experience without extensive environment configuration. The only downside is that pulling the image can be a bit slow. - -2. [Deployment Using Docker Environment](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E5%80%9F%E5%8A%A9docker%E7%8E%AF%E5%A2%83%E8%BF%90%E8%A1%8C%E9%83%A8%E7%BD%B2) - Ideal for software engineers who already have Docker installed and wish to customize the code. - -3. [Running from Local Source Code](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%89%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C) - Suitable for users familiar with the `Conda` environment or those who wish to build the runtime environment from scratch. - -For scenarios requiring higher response speeds, running from the local source code is recommended to reduce additional overhead. - -### 2. [Firmware Compilation](./docs/firmware-build.md) - -Click [here](./docs/firmware-build.md) for a detailed guide on firmware compilation. - -After successful compilation and network connection, wake up XiaoZhi using the wake-up word and monitor the server console for output. +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:------:|:---------------:|:----:|:---------:|:--:| +| Memory | mem0ai | Interface Call | 1000 times/month quota | | +| Memory | mem_local_short | Local Summary | Free | | --- -## Frequently Asked Questions ❓ +### Intent Recognition -### 1. TTS often fails and times out ⏰ - -**Suggestion:** -If `EdgeTTS` frequently fails, please first check whether you are using a proxy (VPN). If so, try disabling the proxy and try again. If you are using Volcano Engine Doubao TTS and it often fails, it is recommended to use the paid version since the trial only supports 2 concurrent requests. - -### 2. I want to control lights, air conditioners, remote power on/off, etc. with XiaoZhi 💡 - -**Suggestion:** -Set the `LLM` to `HomeAssistant` in the configuration file and use the `HomeAssistant` API to perform the relevant controls. - -### 3. I speak slowly, and XiaoZhi always interrupts during pauses 🗣️ - -**Suggestion:** -Locate the following section in the configuration file and increase the value of `min_silence_duration_ms` (for example, change it to `1000`): - -```yaml -VAD: - SileroVAD: - threshold: 0.5 - model_dir: models/snakers4_silero-vad - min_silence_duration_ms: 700 # If your pauses are longer, increase this value -``` - -### 4. Why does XiaoZhi recognize a lot of Korean, Japanese, and English in what I say? 🇰🇷 - -**Suggestion:** -Check whether the `model.pt` file exists in the `models/SenseVoiceSmall` directory. If it does not, please download it. See [Download ASR Model Files](docs/Deployment.md#模型文件) for details. - -### 5. Why does the error “TTS task error: file does not exist” occur? 📁 - -**Suggestion:** -Verify that you have correctly installed the `libopus` and `ffmpeg` libraries using `conda`. If not, install them using: - -``` -conda install conda-forge::libopus -conda install conda-forge::ffmpeg -``` - -### 6. How can I improve XiaoZhi's dialogue response speed? ⚡ - -The default configuration of this project is designed to be cost-effective. It is recommended that beginners first use the default free models to ensure that the system runs smoothly, then optimize for faster response times. -To improve response speed, you can try replacing individual components. Below are the response time test results for each component (for reference only, not a guarantee): - -**LLM Performance Ranking:** - -| Module Name | Average First Token Time | Average Total Response Time | -|--------------|--------------------------|-----------------------------| -| AliLLM | 0.547s | 1.485s | -| ChatGLMLLM | 0.677s | 3.057s | -| OllamaLLM | 0.003s | 0.003s | - -**TTS Performance Ranking:** - -| Module Name | Average Synthesis Time | -|----------------------------|------------------------| -| EdgeTTS | 1.019s | -| DoubaoTTS | 0.503s | -| CosyVoiceSiliconflow | 3.732s | - -**Recommended Configuration Combination (Overall Response Speed):** - -| Combination Scheme | Overall Score | LLM First Token | TTS Synthesis | -|-----------------------------------|---------------|-----------------|---------------| -| AliLLM + DoubaoTTS | 0.539 | 0.547s | 0.503s | -| AliLLM + EdgeTTS | 0.642 | 0.547s | 1.019s | -| ChatGLMLLM + DoubaoTTS | 0.642 | 0.677s | 0.503s | -| ChatGLMLLM + EdgeTTS | 0.745 | 0.677s | 1.019s | -| AliLLM + CosyVoiceSiliconflow | 1.184 | 0.547s | 3.732s | - -**Conclusion 🔍** - -_As of February 19, 2025, if my computer were located in Haizhu District, Guangzhou, Guangdong Province, and connected via China Unicom, I would prioritize using:_ - -- **LLM:** `AliLLM` -- **TTS:** `DoubaoTTS` - -### 7. For more questions, feel free to contact us for feedback 💬 - -Our contact information is in [Baidu Netdisk](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),The extraction code is`223y`。 +| Type | Platform Name | Usage Method | Pricing Model | Notes | +|:------:|:-------------:|:----:|:-------:|:---------------------:| +| Intent | intent_llm | Interface Call | Based on LLM pricing | Intent recognition through large models, highly generalizable | +| Intent | function_call | Interface Call | Based on LLM pricing | Intent completion through large model function calls, fast and effective | --- -## Acknowledgements 🙏 +## Acknowledgments 🙏 -- This project was inspired by the [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) and implemented based on it. -- Many thanks to [Tenclass](https://www.tenclass.com/) for providing detailed documentation support for the XiaoZhi communication protocol. +- This project was inspired by [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) and implemented based on it. +- Thanks to [Tenclass](https://www.tenclass.com/) for providing detailed documentation support for the Xiaozhi communication protocol. @@ -294,4 +299,4 @@ Our contact information is in [Baidu Netdisk](https://pan.baidu.com/s/1x6USjvP1n Star History Chart - \ No newline at end of file + \ No newline at end of file diff --git a/docs/Deployment.md b/docs/Deployment.md index cb64e604b..dfac9dcde 100644 --- a/docs/Deployment.md +++ b/docs/Deployment.md @@ -311,15 +311,17 @@ LLM: 如果你能看到,类似以下日志,则是本项目服务启动成功的标志。 ``` -25-02-23 12:01:09[core.websocket_server] - INFO - Server is running at ws://xxx.xx.xx.xx:8000 +25-02-23 12:01:09[core.websocket_server] - INFO - Server is running at ws://xxx.xx.xx.xx:8000/xiaozhi/v1/ 25-02-23 12:01:09[core.websocket_server] - INFO - =======上面的地址是websocket协议地址,请勿用浏览器访问======= +25-02-23 12:01:09[core.websocket_server] - INFO - 如想测试websocket请用谷歌浏览器打开test目录下的test_page.html +25-02-23 12:01:09[core.websocket_server] - INFO - ======================================================= ``` 正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。 但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。 最正确的方法,是根据电脑的局域网IP来确定你的接口地址。 -如果你的电脑的局域网IP比如是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000`。 +如果你的电脑的局域网IP比如是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000/xiaozhi/v1/`。 这个信息很有用的,后面`编译esp32固件`需要用到。 @@ -328,14 +330,16 @@ LLM: 以下是一些常见问题,供参考: -[1、为什么我说的话,小智识别出来很多韩文、日文、英文](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[1、为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md) -[2、为什么会出现“TTS 任务出错 文件不存在”?](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[2、为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md) -[3、TTS 经常失败,经常超时](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[3、TTS 经常失败,经常超时](./FAQ.md) -[4、如何提高小智对话响应速度?](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[4、使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md) -[5、我说话很慢,停顿时小智老是抢话](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[5、如何提高小智对话响应速度?](./FAQ.md) -[6、我想通过小智控制电灯、空调、远程开关机等操作](../README.md#1%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E8%AF%B4%E7%9A%84%E8%AF%9D%E5%B0%8F%E6%99%BA%E8%AF%86%E5%88%AB%E5%87%BA%E6%9D%A5%E5%BE%88%E5%A4%9A%E9%9F%A9%E6%96%87%E6%97%A5%E6%96%87%E8%8B%B1%E6%96%87) +[6、我说话很慢,停顿时小智老是抢话](./FAQ.md) + +[7、我想通过小智控制电灯、空调、远程开关机等操作](./FAQ.md) diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 000000000..9be27089d --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,149 @@ +# 常见问题 ❓ + +### 1、为什么我说的话,小智识别出来很多韩文、日文、英文?🇰🇷 + +建议:检查一下`models/SenseVoiceSmall`是否已经有`model.pt` +文件,如果没有就要下载,查看这里[下载语音识别模型文件](Deployment.md#模型文件) + +### 2、为什么会出现"TTS 任务出错 文件不存在"?📁 + +建议:检查一下是否正确使用`conda` 安装了`libopus`和`ffmpeg`库。 + +如果没有安装,就安装 + +``` +conda install conda-forge::libopus +conda install conda-forge::ffmpeg +``` + +### 3、TTS 经常失败,经常超时 ⏰ + +建议:如果 `EdgeTTS` 经常失败,请先检查是否使用了代理(梯子)。如果使用了,请尝试关闭代理后再试; +如果用的是火山引擎的豆包 TTS,经常失败时建议使用付费版本,因为测试版本仅支持 2 个并发。 + +### 4、使用Wifi能连接自建服务器,但是4G模式却接不上 🔐 + +原因:虾哥的固件,4G模式需要使用安全连接。 + +解决方法:目前有两种方法可以解决。任选一种: + +1、改代码。参考这个视频解决 https://www.bilibili.com/video/BV18MfTYoE85 + +2、使用nginx配置ssl证书。参考教程 https://icnt94i5ctj4.feishu.cn/docx/GnYOdMNJOoRCljx1ctecsj9cnRe + +### 5、如何提高小智对话响应速度? ⚡ + +本项目默认配置为低成本方案,建议初学者先使用默认免费模型,解决"跑得动"的问题,再优化"跑得快"。 +如需提升响应速度,可尝试更换各组件。以下为各组件的响应速度测试数据(仅供参考,不构成承诺): + +| 影响因素 | 因素值 | +|:-----:|:----------------:| +| 测试地点 | 广东省广州市海珠区 | +| 测试时间 | 2025年2月19日 12:52 | +| 宽带运营商 | 中国联通 | + +测试方法: + +1、把各组件的密钥配置上去,只有配置了密钥的组件才参与测试。 + +2、配置完密钥后,执行以下方法 + +``` +# 进入项目根目录,执行以下命令: +conda activate xiaozhi-esp32-server +python performance_tester.py +``` + +生成报告如下 + +LLM 性能排行: + +| 模块名称 | 平均首Token时间 | 平均总响应时间 | +|:-----------|:-----------|:--------| +| AliLLM | 0.547s | 1.485s | +| ChatGLMLLM | 0.677s | 3.057s | + +TTS 性能排行: + +| 模块名称 | 平均合成时间 | +|----------------------|--------| +| EdgeTTS | 1.019s | +| DoubaoTTS | 0.503s | +| CosyVoiceSiliconflow | 3.732s | + +推荐配置组合 (综合响应速度): + +| 组合方案 | 综合得分 | LLM首Token | TTS合成 | +|-------------------------------|-------|-----------|--------| +| AliLLM + DoubaoTTS | 0.539 | 0.547s | 0.503s | +| AliLLM + EdgeTTS | 0.642 | 0.547s | 1.019s | +| ChatGLMLLM + DoubaoTTS | 0.642 | 0.677s | 0.503s | +| ChatGLMLLM + EdgeTTS | 0.745 | 0.677s | 1.019s | +| AliLLM + CosyVoiceSiliconflow | 1.184 | 0.547s | 3.732s | + +### 结论 🔍 + +`2025年2月19日`,如果我的电脑在`广东省广州市海珠区`,且使用的是`中国联通`网络,我会优先使用: + +- LLM:`AliLLM` +- TTS:`DoubaoTTS` + +### 6、我说话很慢,停顿时小智老是抢话 🗣️ + +建议:在配置文件中找到如下部分,将 `min_silence_duration_ms` 的值调大(例如改为 `1000`): + +```yaml +VAD: + SileroVAD: + threshold: 0.5 + model_dir: models/snakers4_silero-vad + min_silence_duration_ms: 700 # 如果说话停顿较长,可将此值调大 +``` + +### 7、我想通过小智控制电灯、空调、远程开关机等操作 💡 + +本项目,支持以工具调用的方式控制HomeAssistant设备 + +1、首先选择一款支持function call支持的LLM,例如`ChatGLMLLM`。 + +2、在配置文件中,将 `selected_module.Intent` 设置为 `function_call`。 + +3、登录`HomeAssistant`,点击`左下角个人`,切换`安全`导航栏,划到底部`长期访问令牌`生成api_key。 + +在配置文件中,配置好你的home assistant的`devices`(被控制的设备)和`api_key`和`base_url`等信息。例如: + +``` yaml +plugins + home_assistant: + devices: + - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1 + - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1 + base_url: http://你的homeassistant地址:8123 + api_key: 你的home assistant api访问令牌 +``` + +最后,允许function_call 插件在配置文件中启用`hass_get_state`(必须)、`hass_set_state`(必须)、`hass_play_music`(不想用ha听音乐可以不启动),例如: + +``` yaml +Intent: + ... + function_call: + type: nointent + functions: + - change_role + - get_weather + - get_news + - hass_get_state + - hass_set_state + - hass_play_music +``` + +### 8、更多问题,可联系我们反馈 💬 + +我们的联系方式放在[百度网盘中,点击前往](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),提取码是`223y`。 + +网盘里有"硬件烧录QQ群"、"开源服务端交流群"、"产品建议联系人" 三张图片,请根据需要选择加入。 + +- 硬件烧录QQ群:适用于硬件烧录问题 +- 开源服务端交流群:适用于服务端问题 +- 产品建议联系人:适用于产品功能、产品设计等建议 \ No newline at end of file diff --git a/docs/docker/nginx.conf b/docs/docker/nginx.conf index 820fda23c..6a746260b 100644 --- a/docs/docker/nginx.conf +++ b/docs/docker/nginx.conf @@ -9,7 +9,7 @@ server { } # API反向代理(Java项目) - location /xiaozhi-esp32-api/ { + location /xiaozhi/ { proxy_pass http://127.0.0.1:8003; proxy_set_header Host $host; proxy_cookie_path /api/ /; diff --git a/docs/firmware-build.md b/docs/firmware-build.md index b726826c9..9187681e4 100644 --- a/docs/firmware-build.md +++ b/docs/firmware-build.md @@ -1,10 +1,9 @@ # 编译esp32固件 -1. 下载`xiaozhi-esp32` - 项目,按照这个教程配置项目环境[《Windows搭建 ESP IDF 5.3.2开发环境以及编译小智》](https://icnynnzcwou8.feishu.cn/wiki/JEYDwTTALi5s2zkGlFGcDiRknXf) +1. 先按照这个教程配置项目环境[《Windows搭建 ESP IDF 5.3.2开发环境以及编译小智》](https://icnynnzcwou8.feishu.cn/wiki/JEYDwTTALi5s2zkGlFGcDiRknXf) -2. 打开`xiaozhi-esp32/main/Kconfig.projbuild`文件,找到`WEBSOCKET_URL`的`default`的内容,把`wss://api.tenclass.net` - 改成你自己的地址,例如,我的接口地址是`ws://192.168.1.25:8000`,就把内容改成这个。 +2. 配置好编译环境后,下载虾哥[xiaozhi-esp32](https://github.com/78/xiaozhi-esp32)项目源码,进入虾哥项目,打开`xiaozhi-esp32/main/Kconfig.projbuild`文件,找到`WEBSOCKET_URL`的`default`的内容,把`wss://api.tenclass.net` + 改成你自己的地址,例如,我的接口地址是`ws://192.168.1.25:8000/xiaozhi/v1/`,就把内容改成这个。 修改前: @@ -92,14 +91,16 @@ https://espressif.github.io/esp-launchpad/ 以下是一些常见问题,供参考: -[1、为什么我说的话,小智识别出来很多韩文、日文、英文](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[1、为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md) -[2、为什么会出现“TTS 任务出错 文件不存在”?](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[2、为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md) -[3、TTS 经常失败,经常超时](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[3、TTS 经常失败,经常超时](./FAQ.md) -[4、如何提高小智对话响应速度?](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[4、使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md) -[5、我说话很慢,停顿时小智老是抢话](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[5、如何提高小智对话响应速度?](./FAQ.md) -[6、我想通过小智控制电灯、空调、远程开关机等操作](../README.md#1tts-%E7%BB%8F%E5%B8%B8%E5%A4%B1%E8%B4%A5%E7%BB%8F%E5%B8%B8%E8%B6%85%E6%97%B6-) +[6、我说话很慢,停顿时小智老是抢话](./FAQ.md) + +[7、我想通过小智控制电灯、空调、远程开关机等操作](./FAQ.md) diff --git a/docs/images/banner1.png b/docs/images/banner1.png new file mode 100644 index 000000000..974ddaf35 Binary files /dev/null and b/docs/images/banner1.png differ diff --git a/docs/images/banner2.png b/docs/images/banner2.png new file mode 100644 index 000000000..4d54073e1 Binary files /dev/null and b/docs/images/banner2.png differ diff --git a/docs/images/webui.png b/docs/images/webui.png deleted file mode 100644 index 4d4ae599c..000000000 Binary files a/docs/images/webui.png and /dev/null differ diff --git a/main/README.md b/main/README.md index 741a626b3..ba3a499be 100644 --- a/main/README.md +++ b/main/README.md @@ -1,4 +1,4 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../README.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) +本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](./FAQ.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) # 项目目录介绍 当你看到这份文件的时候,这个这个项目还没完善好。我们还有很多东西要做。 @@ -18,4 +18,4 @@ xiaozhi-esp32-server # manager-web 、manager-api接口协议 -https://2662r3426b.vicp.fun/xiaozhi-esp32-api/api/v1/doc.html +https://2662r3426b.vicp.fun/xiaozhi/v1/doc.html diff --git a/main/manager-api/README.md b/main/manager-api/README.md index 0491632b5..bef06b68e 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,4 +1,4 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-) +本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../../docs/Deployment.md) # 项目介绍 manager-api 该项目基于SpringBoot框架开发。 @@ -23,12 +23,7 @@ CREATE DATABASE xiaozhi_esp32_server CHARACTER SET utf8mb4 COLLATE utf8mb4_unico 如果还没有MySQL,你可以通过docker安装mysql ``` -docker run --name xiaozhi-esp32-server-db \ --e MYSQL_ROOT_PASSWORD=123456 \ --p 3306:3306 \ --e MYSQL_DATABASE=xiaozhi_esp32_server \ --e MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci" \ --d mysql:latest +docker run --name xiaozhi-esp32-server-db -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -e MYSQL_DATABASE=xiaozhi_esp32_server -e MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci" -d mysql:latest ``` # 确认项目数据库连接信息 @@ -81,15 +76,16 @@ src/main/java/xiaozhi/AdminApplication.java 执行以下命令生产jar包 ``` -mvn install +mvn clean install ``` 把jar包放在服务器上,执行 ``` -nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.active=dev >/dev/null & +nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.activate=dev ``` -# 接口文档 -启动后打开:http://localhost:8002/xiaozhi-esp32-api/doc.html + +# 接口文档 +启动后打开:http://localhost:8002/xiaozhi/doc.html diff --git a/main/manager-api/src/main/java/xiaozhi/AdminApplication.java b/main/manager-api/src/main/java/xiaozhi/AdminApplication.java index 8a96edb2a..84e30123d 100644 --- a/main/manager-api/src/main/java/xiaozhi/AdminApplication.java +++ b/main/manager-api/src/main/java/xiaozhi/AdminApplication.java @@ -8,6 +8,6 @@ public class AdminApplication { public static void main(String[] args) { SpringApplication.run(AdminApplication.class, args); - System.out.println("http://localhost:8002/xiaozhi-esp32-api/api/v1/doc.html"); + System.out.println("http://localhost:8002/xiaozhi/doc.html"); } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java index da23a233b..0def65894 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java @@ -51,7 +51,7 @@ public class SwaggerConfig { public GroupedOpenApi timbreApi() { return GroupedOpenApi.builder() .group("timbre") - .pathsToMatch("/timbre/**") + .pathsToMatch("/ttsVoice/**") .build(); } diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java index 21121fd73..53aa08dc2 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java @@ -26,4 +26,32 @@ public class RedisKeys { public static String getDeviceCaptchaKey(String captcha) { return "sys:device:captcha:" + captcha; } + + /** + * 用户id的Key + */ + public static String getUserIdKey(Long userid) { + return "sys:username:id:" + userid; + } + + /** + * 模型名称的Key + */ + public static String getModelNameById(String id) { + return "sys:model:name:" + id; + } + + /** + * 获取音色名称缓存key + */ + public static String getTimbreNameById(String id) { + return "timbre:name:" + id; + } + + /** + * 获取设备数量缓存key + */ + public static String getAgentDeviceCountById(String id) { + return "agent:device:count:" + id; + } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java index 9e5ef3e1c..bfa7afed6 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java @@ -2,6 +2,9 @@ package xiaozhi.common.utils; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; import java.util.Date; /** @@ -60,4 +63,39 @@ public class DateUtils { return null; } + /** + * 获取简短的时间字符串:10秒前返回刚刚,多少秒前,几小时前,超过一周返回年月日时分秒 + * @param date + * @return + */ + public static String getShortTime(Date date) { + if (date == null) { + return null; + } + // 将 Date 转换为 Instant + LocalDateTime localDateTime = date.toInstant() + // 获取系统默认时区 + .atZone(ZoneId.systemDefault()) + // 转换为 LocalDateTime + .toLocalDateTime(); + // 当前时间 + LocalDateTime now = LocalDateTime.now(); + // 时间差,单位为秒 + long secondsBetween = ChronoUnit.SECONDS.between(localDateTime, now); + + if (secondsBetween <= 10) { + return "刚刚"; + } else if (secondsBetween < 60) { + return secondsBetween + "秒前"; + } else if (secondsBetween < 60 * 60) { + return secondsBetween / 60 + "分钟前"; + } else if (secondsBetween < 86400) { + return secondsBetween / 3600 + "小时前"; + } else if (secondsBetween < 604800) { + return secondsBetween / 86400 + "天前"; + } else { + // 超过一周,显示完整日期时间 + return format(date,DATE_TIME_PATTERN); + } + } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 93a741dff..eea2d7fe4 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -29,11 +29,13 @@ import xiaozhi.common.user.UserDetail; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.Result; import xiaozhi.modules.agent.dto.AgentCreateDTO; +import xiaozhi.modules.agent.dto.AgentDTO; import xiaozhi.modules.agent.dto.AgentUpdateDTO; import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.agent.entity.AgentTemplateEntity; import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.agent.service.AgentTemplateService; +import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.security.user.SecurityUser; @Tag(name = "智能体管理") @@ -43,14 +45,15 @@ import xiaozhi.modules.security.user.SecurityUser; public class AgentController { private final AgentService agentService; private final AgentTemplateService agentTemplateService; + private final DeviceService deviceService; @GetMapping("/list") @Operation(summary = "获取用户智能体列表") @RequiresPermissions("sys:role:normal") - public Result> getUserAgents() { + public Result> getUserAgents() { UserDetail user = SecurityUser.getUser(); - List agents = agentService.getUserAgents(user.getId()); - return new Result>().ok(agents); + List agents = agentService.getUserAgents(user.getId()); + return new Result>().ok(agents); } @GetMapping("/all") @@ -80,6 +83,22 @@ public class AgentController { public Result save(@RequestBody @Valid AgentCreateDTO dto) { AgentEntity entity = ConvertUtils.sourceToTarget(dto, AgentEntity.class); + // 获取默认模板 + AgentTemplateEntity template = agentTemplateService.getDefaultTemplate(); + if (template != null) { + // 设置模板中的默认值 + entity.setAsrModelId(template.getAsrModelId()); + entity.setVadModelId(template.getVadModelId()); + entity.setLlmModelId(template.getLlmModelId()); + entity.setTtsModelId(template.getTtsModelId()); + entity.setTtsVoiceId(template.getTtsVoiceId()); + entity.setMemModelId(template.getMemModelId()); + entity.setIntentModelId(template.getIntentModelId()); + entity.setSystemPrompt(template.getSystemPrompt()); + entity.setLangCode(template.getLangCode()); + entity.setLanguage(template.getLanguage()); + } + // 设置用户ID和创建者信息 UserDetail user = SecurityUser.getUser(); entity.setUserId(user.getId()); @@ -157,6 +176,9 @@ public class AgentController { @Operation(summary = "删除智能体") @RequiresPermissions("sys:role:normal") public Result delete(@PathVariable String id) { + // 先删除关联的设备 + deviceService.deleteByAgentId(id); + // 再删除智能体 agentService.deleteById(id); return new Result<>(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java index d9aec7d7d..8c80d6cc9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java @@ -1,11 +1,18 @@ package xiaozhi.modules.agent.dao; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.agent.entity.AgentEntity; @Mapper public interface AgentDao extends BaseDao { - + /** + * 获取智能体的设备数量 + * + * @param agentId 智能体ID + * @return 设备数量 + */ + Integer getDeviceCountByAgentId(@Param("agentId") String agentId); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java new file mode 100644 index 000000000..a63c96e7d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java @@ -0,0 +1,38 @@ +package xiaozhi.modules.agent.dto; + +import java.util.Date; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * 智能体数据传输对象 + * 用于在服务层和控制器层之间传递智能体相关的数据 + */ +@Data +@Schema(description = "智能体对象") +public class AgentDTO { + @Schema(description = "智能体编码", example = "AGT_1234567890") + private String id; + + @Schema(description = "智能体名称", example = "客服助手") + private String agentName; + + @Schema(description = "语音合成模型名称", example = "tts_model_01") + private String ttsModelName; + + @Schema(description = "音色名称", example = "voice_01") + private String ttsVoiceName; + + @Schema(description = "大语言模型名称", example = "llm_model_01") + private String llmModelName; + + @Schema(description = "角色设定参数", example = "你是一个专业的客服助手,负责回答用户问题并提供帮助") + private String systemPrompt; + + @Schema(description = "最后连接时间", example = "2024-03-20 10:00:00") + private Date lastConnectedAt; + + @Schema(description = "设备数量", example = "10") + private Integer deviceCount; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java index da958e4c7..8d0b29593 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java @@ -5,13 +5,10 @@ import java.util.Map; import xiaozhi.common.page.PageData; import xiaozhi.common.service.BaseService; +import xiaozhi.modules.agent.dto.AgentDTO; import xiaozhi.modules.agent.entity.AgentEntity; public interface AgentService extends BaseService { - /** - * 根据用户ID获取智能体列表 - */ - List getUserAgents(Long userId); /** * 管理员获取所有智能体列表(分页) @@ -22,4 +19,27 @@ public interface AgentService extends BaseService { * 获取智能体详情 */ AgentEntity getAgentById(String id); + + /** + * 删除这个用户的所有 + * + * @param userId + */ + void deleteAgentByUserId(Long userId); + + /** + * 获取用户智能体列表 + * + * @param userId + * @return + */ + List getUserAgents(Long userId); + + /** + * 获取智能体的设备数量 + * + * @param agentId 智能体ID + * @return 设备数量 + */ + Integer getDeviceCountByAgentId(String agentId); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java index 9c27bdb5f..197c860eb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentTemplateService.java @@ -11,4 +11,10 @@ import xiaozhi.modules.agent.entity.AgentTemplateEntity; */ public interface AgentTemplateService extends IService { + /** + * 获取默认模板 + * + * @return 默认模板实体 + */ + AgentTemplateEntity getDefaultTemplate(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index 8e73c003b..bb2a3ed0f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -3,33 +3,44 @@ package xiaozhi.modules.agent.service.impl; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import xiaozhi.common.page.PageData; +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.modules.agent.dao.AgentDao; +import xiaozhi.modules.agent.dto.AgentDTO; import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.agent.service.AgentService; +import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.modules.timbre.service.TimbreService; @Service public class AgentServiceImpl extends BaseServiceImpl implements AgentService { private final AgentDao agentDao; + @Autowired + private TimbreService timbreModelService; + + @Autowired + private ModelConfigService modelConfigService; + + @Autowired + private RedisUtils redisUtils; + public AgentServiceImpl(AgentDao agentDao) { this.agentDao = agentDao; } - @Override - public List getUserAgents(Long userId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("user_id", userId); - return agentDao.selectList(wrapper); - } - @Override public PageData adminAgentList(Map params) { IPage page = agentDao.selectPage( @@ -62,4 +73,61 @@ public class AgentServiceImpl extends BaseServiceImpl imp return super.insert(entity); } + + @Override + public void deleteAgentByUserId(Long userId) { + UpdateWrapper wrapper = new UpdateWrapper<>(); + wrapper.eq("user_id", userId); + baseDao.delete(wrapper); + } + + @Override + public List getUserAgents(Long userId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("user_id", userId); + List agents = agentDao.selectList(wrapper); + return agents.stream().map(agent -> { + AgentDTO dto = new AgentDTO(); + dto.setId(agent.getId()); + dto.setAgentName(agent.getAgentName()); + dto.setSystemPrompt(agent.getSystemPrompt()); + + // 获取 TTS 模型名称 + dto.setTtsModelName(modelConfigService.getModelNameById(agent.getTtsModelId())); + + // 获取 LLM 模型名称 + dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId())); + + // 获取 TTS 音色名称 + dto.setTtsVoiceName(timbreModelService.getTimbreNameById(agent.getTtsVoiceId())); + + // 获取设备数量 + dto.setDeviceCount(getDeviceCountByAgentId(agent.getId())); + + return dto; + }).collect(Collectors.toList()); + } + + @Override + public Integer getDeviceCountByAgentId(String agentId) { + if (StringUtils.isBlank(agentId)) { + return 0; + } + + // 先从Redis中获取 + Integer cachedCount = (Integer) redisUtils.get(RedisKeys.getAgentDeviceCountById(agentId)); + if (cachedCount != null) { + return cachedCount; + } + + // 如果Redis中没有,则从数据库查询 + Integer deviceCount = agentDao.getDeviceCountByAgentId(agentId); + + // 将结果存入Redis + if (deviceCount != null) { + redisUtils.set(RedisKeys.getAgentDeviceCountById(agentId), deviceCount, 60); + } + + return deviceCount != null ? deviceCount : 0; + } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java index 62338fadf..949a2f2d1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java @@ -2,6 +2,7 @@ package xiaozhi.modules.agent.service.impl; import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import xiaozhi.modules.agent.dao.AgentTemplateDao; @@ -15,6 +16,17 @@ import xiaozhi.modules.agent.service.AgentTemplateService; */ @Service public class AgentTemplateServiceImpl extends ServiceImpl - implements AgentTemplateService { + implements AgentTemplateService { + /** + * 获取默认模板 + * + * @return 默认模板实体 + */ + public AgentTemplateEntity getDefaultTemplate() { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.orderByAsc(AgentTemplateEntity::getSort) + .last("LIMIT 1"); + return this.getOne(wrapper); + } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java index 2ae9e0234..1c68a7565 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -19,7 +19,7 @@ import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.user.UserDetail; import xiaozhi.common.utils.Result; -import xiaozhi.modules.device.dto.DeviceBindDTO; +import xiaozhi.modules.device.dto.DeviceRegisterDTO; import xiaozhi.modules.device.dto.DeviceUnBindDTO; import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; @@ -38,16 +38,29 @@ public class DeviceController { @Operation(summary = "绑定设备") @RequiresPermissions("sys:role:normal") public Result bindDevice(@PathVariable String agentId, @PathVariable String deviceCode) { - String macAddress = (String) redisUtils.get(RedisKeys.getDeviceCaptchaKey(deviceCode)); - if (StringUtils.isBlank(macAddress)) { - return new Result().error(ErrorCode.DEVICE_CAPTCHA_ERROR); - } - Long user = SecurityUser.getUser().getId(); - DeviceBindDTO deviceBindDTO = new DeviceBindDTO(macAddress, user, agentId); - deviceService.bindDevice(deviceBindDTO); + deviceService.deviceActivation(agentId, deviceCode); return new Result<>(); } + @PostMapping("/register") + @Operation(summary = "注册设备") + public Result registerDevice(@RequestBody DeviceRegisterDTO deviceRegisterDTO) { + String macAddress = deviceRegisterDTO.getMacAddress(); + if (StringUtils.isBlank(macAddress)) { + return new Result().error(ErrorCode.NOT_NULL, "mac地址不能为空"); + } + // 生成六位验证码 + String code = String.valueOf(Math.random()).substring(2, 8); + String key = RedisKeys.getDeviceCaptchaKey(code); + String existsMac = null; + do { + existsMac = (String) redisUtils.get(key); + } while (StringUtils.isNotBlank(existsMac)); + + redisUtils.set(key, macAddress); + return new Result().ok(code); + } + @GetMapping("/bind/{agentId}") @Operation(summary = "获取已绑定设备") @RequiresPermissions("sys:role:normal") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java index 16f532565..dab84082b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java @@ -5,12 +5,10 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.lang3.StringUtils; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.annotation.JsonInclude; @@ -22,7 +20,6 @@ import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; -import xiaozhi.common.utils.Result; import xiaozhi.modules.device.dto.DeviceReportReqDTO; import xiaozhi.modules.device.dto.DeviceReportRespDTO; import xiaozhi.modules.device.service.DeviceService; @@ -31,7 +28,7 @@ import xiaozhi.modules.device.utils.NetworkUtil; @Tag(name = "设备管理", description = "OTA 相关接口") @RestController @RequiredArgsConstructor -@RequestMapping("/ota") +@RequestMapping("/ota/") public class OTAController { private final DeviceService deviceService; @@ -55,12 +52,6 @@ public class OTAController { return createResponse(deviceService.checkDeviceActive(macAddress, deviceId, clientId, deviceReportReqDTO)); } - @Operation(summary = "设备激活") - @GetMapping("/activation") - public Result deviceActivation(@RequestParam String code) { - return new Result().ok(deviceService.deviceActivation(code)); - } - @SneakyThrows private ResponseEntity createResponse(DeviceReportRespDTO deviceReportRespDTO) { ObjectMapper objectMapper = new ObjectMapper(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DevicePageUserDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DevicePageUserDTO.java new file mode 100644 index 000000000..26bccbfd1 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DevicePageUserDTO.java @@ -0,0 +1,27 @@ +package xiaozhi.modules.device.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Min; +import lombok.Data; + +/** + * 查询所有设备的DTO + * + * @author zjy + * @since 2025-3-21 + */ +@Data +@Schema(description = "查询所有设备的DTO") +public class DevicePageUserDTO { + + @Schema(description = "设备关键词") + private String keywords; + + @Schema(description = "页数") + @Min(value = 0, message = "{page.number}") + private String page; + + @Schema(description = "显示列数") + @Min(value = 0, message = "{limit.number}") + private String limit; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java new file mode 100644 index 000000000..ce37c517a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceRegisterDTO.java @@ -0,0 +1,23 @@ +package xiaozhi.modules.device.dto; + +import java.io.Serializable; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +/** + * 设备注册头信息 + * + * @author zjy + * @since 2025-3-28 + */ +@Setter +@Getter +@Schema(description = "设备注册头信息") +public class DeviceRegisterDTO implements Serializable { + + @Schema(description = "mac地址") + private String macAddress; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java index 6226378d5..9f93a9b76 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java @@ -9,7 +9,7 @@ import lombok.Setter; @Schema(description = "设备OTA检测版本返回体,包含激活码要求") public class DeviceReportRespDTO { @Schema(description = "服务器时间") - private ServerTime serverTime; + private ServerTime server_time; @Schema(description = "激活码") private Activation activation; @@ -56,6 +56,6 @@ public class DeviceReportRespDTO { private String timeZone; @Schema(description = "时区偏移量,单位为分钟") - private Integer timezoneOffset; + private Integer timezone_offset; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java index bc26f649d..37ff8d490 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -2,10 +2,12 @@ package xiaozhi.modules.device.service; import java.util.List; -import xiaozhi.modules.device.dto.DeviceBindDTO; +import xiaozhi.common.page.PageData; +import xiaozhi.modules.device.dto.DevicePageUserDTO; import xiaozhi.modules.device.dto.DeviceReportReqDTO; import xiaozhi.modules.device.dto.DeviceReportRespDTO; import xiaozhi.modules.device.entity.DeviceEntity; +import xiaozhi.modules.device.vo.UserShowDeviceListVO; public interface DeviceService { @@ -21,12 +23,7 @@ public interface DeviceService { DeviceReportReqDTO deviceReport); /** - * 绑定设备 - */ - DeviceEntity bindDevice(DeviceBindDTO deviceHeader); - - /** - * 获取用户设备列表 + * 获取用户指定智能体的设备列表, */ List getUserDevices(Long userId, String agentId); @@ -38,5 +35,35 @@ public interface DeviceService { /** * 设备激活 */ - Boolean deviceActivation(String activationCode); + Boolean deviceActivation(String agentId, String activationCode); + + /** + * 删除此用户的所有设备 + * + * @param userId 用户id + */ + void deleteByUserId(Long userId); + + /** + * 删除指定智能体关联的所有设备 + * + * @param agentId 智能体id + */ + void deleteByAgentId(String agentId); + + /** + * 获取指定用户的设备数量 + * + * @param userId 用户id + * @return 设备数量 + */ + Long selectCountByUserId(Long userId); + + /** + * 分页获取全部设备信息 + * + * @param dto 分页查找参数 + * @return 用户列表分页数据 + */ + PageData page(DevicePageUserDTO dto); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 4fd638260..a9797f42c 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -16,34 +16,43 @@ import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; import cn.hutool.core.util.RandomUtil; +import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.user.UserDetail; import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.DateUtils; import xiaozhi.modules.device.dao.DeviceDao; -import xiaozhi.modules.device.dto.DeviceBindDTO; +import xiaozhi.modules.device.dto.DevicePageUserDTO; import xiaozhi.modules.device.dto.DeviceReportReqDTO; import xiaozhi.modules.device.dto.DeviceReportRespDTO; import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.device.vo.UserShowDeviceListVO; import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.service.SysUserUtilService; @Service public class DeviceServiceImpl extends BaseServiceImpl implements DeviceService { private final DeviceDao deviceDao; + private final SysUserUtilService sysUserUtilService; + private final String frontedUrl; private final RedisTemplate redisTemplate; // 添加构造函数来初始化 deviceMapper - public DeviceServiceImpl(DeviceDao deviceDao, + public DeviceServiceImpl(DeviceDao deviceDao, SysUserUtilService sysUserUtilService, @Value("${app.fronted-url:http://localhost:8001}") String frontedUrl, RedisTemplate redisTemplate) { this.deviceDao = deviceDao; + this.sysUserUtilService = sysUserUtilService; this.frontedUrl = frontedUrl; this.redisTemplate = redisTemplate; } @@ -56,7 +65,7 @@ public class DeviceServiceImpl extends BaseServiceImpl } @Override - public Boolean deviceActivation(String activationCode) { + public Boolean deviceActivation(String agentId, String activationCode) { if (StringUtils.isBlank(activationCode)) { throw new RenException("激活码不能为空"); } @@ -93,6 +102,7 @@ public class DeviceServiceImpl extends BaseServiceImpl DeviceEntity deviceEntity = new DeviceEntity(); deviceEntity.setId(deviceId); deviceEntity.setBoard(board); + deviceEntity.setAgentId(agentId); deviceEntity.setAppVersion(appVersion); deviceEntity.setMacAddress(macAddress); deviceEntity.setUserId(user.getId()); @@ -113,13 +123,13 @@ public class DeviceServiceImpl extends BaseServiceImpl public DeviceReportRespDTO checkDeviceActive(String macAddress, String deviceId, String clientId, DeviceReportReqDTO deviceReport) { DeviceReportRespDTO response = new DeviceReportRespDTO(); - response.setServerTime(buildServerTime()); + response.setServer_time(buildServerTime()); // todo: 此处是固件信息,目前是针对固件上传上来的版本号再返回回去 // 在未来开发了固件更新功能,需要更换此处代码, // 或写定时任务定期请求虾哥的OTA,获取最新的版本讯息保存到服务内 DeviceReportRespDTO.Firmware firmware = new DeviceReportRespDTO.Firmware(); firmware.setVersion(deviceReport.getApplication().getVersion()); - firmware.setUrl("http://localhost:8002/xiaozhi-esp32-api/api/v1/ota/download"); + firmware.setUrl("http://localhost:8002/xiaozhi/ota/download"); response.setFirmware(firmware); DeviceEntity deviceById = getDeviceById(deviceId); @@ -168,19 +178,6 @@ public class DeviceServiceImpl extends BaseServiceImpl return response; } - @Override - public DeviceEntity bindDevice(DeviceBindDTO dto) { - // 查看是否已经被绑定 - DeviceEntity deviceEntity = baseDao - .selectOne(new LambdaQueryWrapper().eq(DeviceEntity::getMacAddress, dto.getMacAddress())); - if (deviceEntity != null) { - throw new RenException("设备已绑定"); - } - deviceEntity = ConvertUtils.sourceToTarget(dto, DeviceEntity.class); - baseDao.insert(deviceEntity); - return deviceEntity; - } - @Override public List getUserDevices(Long userId, String agentId) { QueryWrapper wrapper = new QueryWrapper<>(); @@ -197,12 +194,58 @@ public class DeviceServiceImpl extends BaseServiceImpl baseDao.delete(wrapper); } + @Override + public void deleteByUserId(Long userId) { + UpdateWrapper wrapper = new UpdateWrapper<>(); + wrapper.eq("user_id", userId); + baseDao.delete(wrapper); + } + + @Override + public Long selectCountByUserId(Long userId) { + UpdateWrapper wrapper = new UpdateWrapper<>(); + wrapper.eq("user_id", userId); + return baseDao.selectCount(wrapper); + } + + @Override + public void deleteByAgentId(String agentId) { + UpdateWrapper wrapper = new UpdateWrapper<>(); + wrapper.eq("agent_id", agentId); + baseDao.delete(wrapper); + } + + @Override + public PageData page(DevicePageUserDTO dto) { + Map params = new HashMap(); + params.put(Constant.PAGE, dto.getPage()); + params.put(Constant.LIMIT, dto.getLimit()); + IPage page = baseDao.selectPage( + getPage(params, "sort", true), + // 定义查询条件 + new QueryWrapper() + // 必须设备关键词查找 + .like(StringUtils.isNotBlank(dto.getKeywords()), "alias", dto.getKeywords())); + // 循环处理page获取回来的数据,返回需要的字段 + List list = page.getRecords().stream().map(device -> { + UserShowDeviceListVO vo = ConvertUtils.sourceToTarget(device, UserShowDeviceListVO.class); + // 把最后修改的时间,改为简短描述的时间 + vo.setRecentChatTime(DateUtils.getShortTime(device.getUpdateDate())); + sysUserUtilService.assignUsername(device.getUserId(), + vo::setBindUserName); + vo.setDeviceType(device.getBoard()); + return vo; + }).toList(); + // 计算页数 + return new PageData<>(list, page.getTotal()); + } + private DeviceReportRespDTO.ServerTime buildServerTime() { DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime(); TimeZone tz = TimeZone.getDefault(); serverTime.setTimestamp(Instant.now().toEpochMilli()); serverTime.setTimeZone(tz.getID()); - serverTime.setTimezoneOffset(tz.getOffset(System.currentTimeMillis()) / (60 * 1000)); + serverTime.setTimezone_offset(tz.getOffset(System.currentTimeMillis()) / (60 * 1000)); return serverTime; } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java new file mode 100644 index 000000000..e3a5d8fd1 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/vo/UserShowDeviceListVO.java @@ -0,0 +1,31 @@ +package xiaozhi.modules.device.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "用户显示设备列表VO") +public class UserShowDeviceListVO { + + @Schema(description = "app版本") + private String appVersion; + + @Schema(description = "绑定用户名称") + private String bindUserName; + + @Schema(description = "设备型号") + private String deviceType; + + @Schema(description = "设备唯一标识符") + private String id; + + @Schema(description = "mac地址") + private String macAddress; + + @Schema(description = "开启OTA") + private Integer otaUpgrade; + + @Schema(description = "最近对话时间") + private String recentChatTime; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java index af1e772fc..0ce421572 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java @@ -17,13 +17,17 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; import xiaozhi.common.page.PageData; +import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.Result; +import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigDTO; import xiaozhi.modules.model.dto.ModelProviderDTO; -import xiaozhi.modules.model.dto.ModelProviderFieldDTO; +import xiaozhi.modules.model.dto.VoiceDTO; +import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; +import xiaozhi.modules.timbre.service.TimbreService; @AllArgsConstructor @RestController @@ -32,16 +36,16 @@ import xiaozhi.modules.model.service.ModelProviderService; public class ModelController { private final ModelProviderService modelProviderService; - + private final TimbreService timbreService; private final ModelConfigService modelConfigService; - @GetMapping("/models/names") + @GetMapping("/names") @Operation(summary = "获取所有模型名称") - @RequiresPermissions("sys:role:superAdmin") - public Result> getModelNames(@RequestParam String modelType, + @RequiresPermissions("sys:role:normal") + public Result> getModelNames(@RequestParam String modelType, @RequestParam(required = false) String modelName) { - List modelNameList = modelConfigService.getModelCodeList(modelType, modelName); - return new Result>().ok(modelNameList); + List modelList = modelConfigService.getModelCodeList(modelType, modelName); + return new Result>().ok(modelList); } @GetMapping("/{modelType}/provideTypes") @@ -52,16 +56,7 @@ public class ModelController { return new Result>().ok(modelProviderDTOS); } - @GetMapping("/{modelType}/{provideCode}/fields") - @Operation(summary = "获取模型供应器字段") - @RequiresPermissions("sys:role:superAdmin") - public Result> getModelProviderFields(@PathVariable String modelType, - @PathVariable String provideCode) { - List fieldList = modelProviderService.getFieldList(modelType, provideCode); - return new Result>().ok(fieldList); - } - - @GetMapping("/models/list") + @GetMapping("/list") @Operation(summary = "获取模型配置列表") @RequiresPermissions("sys:role:superAdmin") public Result> getModelConfigList( @@ -73,7 +68,7 @@ public class ModelController { return new Result>().ok(pageList); } - @PostMapping("/models/{modelType}/{provideCode}") + @PostMapping("/{modelType}/{provideCode}") @Operation(summary = "新增模型配置") @RequiresPermissions("sys:role:superAdmin") public Result addModelConfig(@PathVariable String modelType, @@ -83,7 +78,7 @@ public class ModelController { return new Result().ok(modelConfigDTO); } - @PutMapping("/models/{modelType}/{provideCode}/{id}") + @PutMapping("/{modelType}/{provideCode}/{id}") @Operation(summary = "编辑模型配置") @RequiresPermissions("sys:role:superAdmin") public Result editModelConfig(@PathVariable String modelType, @@ -94,22 +89,42 @@ public class ModelController { return new Result().ok(modelConfigDTO); } - @DeleteMapping("/models/{modelType}/{provideCode}/{id}") + @DeleteMapping("/{id}") @Operation(summary = "删除模型配置") @RequiresPermissions("sys:role:superAdmin") - public Result deleteModelConfig(@PathVariable String modelType, @PathVariable String provideCode, - @PathVariable String id) { - modelConfigService.delete(modelType, provideCode, id); + public Result deleteModelConfig(@PathVariable String id) { + modelConfigService.delete(id); return new Result<>(); } - @GetMapping("/models/{modelId}/voices") + @GetMapping("/{id}") + @Operation(summary = "获取模型配置") + @RequiresPermissions("sys:role:superAdmin") + public Result getModelConfig(@PathVariable String id) { + ModelConfigEntity item = modelConfigService.selectById(id); + ModelConfigDTO modelConfigDTO = ConvertUtils.sourceToTarget(item, ModelConfigDTO.class); + return new Result().ok(modelConfigDTO); + } + + @PutMapping("/enable/{id}/{status}") + @Operation(summary = "启用/关闭模型配置") + @RequiresPermissions("sys:role:superAdmin") + public Result enableModelConfig(@PathVariable String id, @PathVariable Integer status) { + ModelConfigEntity entity = modelConfigService.selectById(id); + if (entity == null) { + return new Result().error("模型配置不存在"); + } + entity.setIsEnabled(status); + modelConfigService.updateById(entity); + return new Result(); + } + + @GetMapping("/{modelId}/voices") @Operation(summary = "获取模型音色") @RequiresPermissions("sys:role:normal") - public Result> getVoiceList(@PathVariable String modelId, + public Result> getVoiceList(@PathVariable String modelId, @RequestParam(required = false) String voiceName) { - - List voiceList = modelConfigService.getVoiceList(modelId, voiceName); - return new Result>().ok(voiceList); + List voiceList = timbreService.getVoiceNames(modelId, voiceName); + return new Result>().ok(voiceList); } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelBasicInfoDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelBasicInfoDTO.java new file mode 100644 index 000000000..571c791ab --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelBasicInfoDTO.java @@ -0,0 +1,9 @@ +package xiaozhi.modules.model.dto; + +import lombok.Data; + +@Data +public class ModelBasicInfoDTO { + private String id; + private String modelName; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java index 3e335bf02..07758def1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java @@ -2,6 +2,7 @@ package xiaozhi.modules.model.dto; import java.io.Serial; +import cn.hutool.json.JSONObject; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @@ -28,7 +29,7 @@ public class ModelConfigBodyDTO { private Integer isEnabled; @Schema(description = "模型配置(JSON格式)") - private String configJson; + private JSONObject configJson; @Schema(description = "官方文档链接") private String docLink; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java index a7b1b4365..ed73e1ff8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigDTO.java @@ -3,6 +3,7 @@ package xiaozhi.modules.model.dto; import java.io.Serial; import java.io.Serializable; +import cn.hutool.json.JSONObject; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @@ -32,7 +33,7 @@ public class ModelConfigDTO implements Serializable { private Integer isEnabled; @Schema(description = "模型配置(JSON格式)") - private String configJson; + private JSONObject configJson; @Schema(description = "官方文档链接") private String docLink; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelProviderFieldDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelProviderFieldDTO.java deleted file mode 100644 index 8186b363e..000000000 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelProviderFieldDTO.java +++ /dev/null @@ -1,19 +0,0 @@ -package xiaozhi.modules.model.dto; - -import java.io.Serializable; - -import io.swagger.v3.oas.annotations.media.Schema; -import lombok.Data; - -@Data -@Schema(description = "模型供应器字段") -public class ModelProviderFieldDTO implements Serializable { - @Schema(description = "字段名") - private String key; - - @Schema(description = "字段标签") - private String label; - - @Schema(description = "字段类型") - private String type; -} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/VoiceDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/VoiceDTO.java new file mode 100644 index 000000000..25358eb05 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/VoiceDTO.java @@ -0,0 +1,22 @@ +package xiaozhi.modules.model.dto; + +import java.io.Serializable; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Schema(description = "音色信息") +public class VoiceDTO implements Serializable { + private static final long serialVersionUID = 1L; + + @Schema(description = "音色ID") + private String id; + + @Schema(description = "音色名称") + private String name; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java index 0111ea963..32ff911fb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java @@ -9,11 +9,12 @@ import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; +import cn.hutool.json.JSONObject; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@TableName("ai_model_config") +@TableName(value = "ai_model_config", autoResultMap = true) @Schema(description = "模型配置表") public class ModelConfigEntity { @@ -38,7 +39,7 @@ public class ModelConfigEntity { @TableField(typeHandler = JacksonTypeHandler.class) @Schema(description = "模型配置(JSON格式)") - private String configJson; + private JSONObject configJson; @Schema(description = "官方文档链接") private String docLink; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java index 78e9d0ceb..b8cc38b1b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java @@ -3,12 +3,15 @@ package xiaozhi.modules.model.service; import java.util.List; import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigDTO; +import xiaozhi.modules.model.entity.ModelConfigEntity; -public interface ModelConfigService { +public interface ModelConfigService extends BaseService { - List getModelCodeList(String modelType, String modelName); + List getModelCodeList(String modelType, String modelName); PageData getPageList(String modelType, String modelName, String page, String limit); @@ -16,7 +19,13 @@ public interface ModelConfigService { ModelConfigDTO edit(String modelType, String provideCode, String id, ModelConfigBodyDTO modelConfigBodyDTO); - void delete(String modelType, String provideCode, String id); + void delete(String id); - List getVoiceList(String modelName, String voiceName); + /** + * 根据ID获取模型名称 + * + * @param id 模型ID + * @return 模型名称 + */ + String getModelNameById(String id); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelProviderService.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelProviderService.java index cb92c953e..2ace101ea 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelProviderService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelProviderService.java @@ -3,7 +3,6 @@ package xiaozhi.modules.model.service; import java.util.List; import xiaozhi.modules.model.dto.ModelProviderDTO; -import xiaozhi.modules.model.dto.ModelProviderFieldDTO; import xiaozhi.modules.model.entity.ModelProviderEntity; public interface ModelProviderService { @@ -19,6 +18,4 @@ public interface ModelProviderService { void delete(); List getList(String modelType, String provideCode); - - List getFieldList(String modelType, String provideCode); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java index 6372dc0cd..de8cbd4f3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java @@ -5,8 +5,6 @@ import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; @@ -17,16 +15,18 @@ import lombok.AllArgsConstructor; import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.modules.model.dao.ModelConfigDao; +import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigDTO; import xiaozhi.modules.model.dto.ModelProviderDTO; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; -import xiaozhi.modules.timbre.service.TimbreService; @Service @AllArgsConstructor @@ -35,13 +35,16 @@ public class ModelConfigServiceImpl extends BaseServiceImpl getModelCodeList(String modelType, String modelName) { - return modelConfigDao.getModelCodeList(modelType, modelName); + public List getModelCodeList(String modelType, String modelName) { + List entities = modelConfigDao.selectList( + new QueryWrapper() + .eq("model_type", modelType) + .like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%") + .select("id", "model_name")); + return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class); } @Override @@ -95,21 +98,31 @@ public class ModelConfigServiceImpl extends BaseServiceImpl providerList = modelProviderService.getList(modelType, provideCode); - if (CollectionUtil.isEmpty(providerList)) { - throw new RenException("供应器不存在"); - } - + public void delete(String id) { modelConfigDao.deleteById(id); } @Override - public List getVoiceList(String modelId, String voiceName) { - return timbreService.getVoiceNames(modelId, voiceName); + public String getModelNameById(String id) { + if (StringUtils.isBlank(id)) { + return null; + } + + String cachedName = (String) redisUtils.get(RedisKeys.getModelNameById(id)); + + if (StringUtils.isNotBlank(cachedName)) { + return cachedName; + } + + ModelConfigEntity entity = modelConfigDao.selectById(id); + if (entity != null) { + String modelName = entity.getModelName(); + if (StringUtils.isNotBlank(modelName)) { + redisUtils.set(RedisKeys.getModelNameById(id), modelName); + } + return modelName; + } + + return null; } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelProviderServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelProviderServiceImpl.java index 7580d479c..fb06e4d5d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelProviderServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelProviderServiceImpl.java @@ -10,10 +10,8 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import lombok.AllArgsConstructor; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; -import xiaozhi.common.utils.JsonUtils; import xiaozhi.modules.model.dao.ModelProviderDao; import xiaozhi.modules.model.dto.ModelProviderDTO; -import xiaozhi.modules.model.dto.ModelProviderFieldDTO; import xiaozhi.modules.model.entity.ModelProviderEntity; import xiaozhi.modules.model.service.ModelProviderService; @@ -56,15 +54,4 @@ public class ModelProviderServiceImpl extends BaseServiceImpl providerEntities = modelProviderDao.selectList(queryWrapper); return ConvertUtils.sourceToTarget(providerEntities, ModelProviderDTO.class); } - - @Override - public List getFieldList(String modelType, String providerCode) { - List modelProviderEntities = modelProviderDao.getFieldList(modelType, providerCode); - if (modelProviderEntities == null || modelProviderEntities.isEmpty()) { - return null; - } - String fields = modelProviderEntities.getFirst(); - List fieldList = JsonUtils.parseArray(fields, ModelProviderFieldDTO.class); - return fieldList; - } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java index fc5db7050..e5b89c99f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -77,6 +77,7 @@ public class ShiroConfig { filterMap.put("/user/captcha", "anon"); filterMap.put("/user/login", "anon"); filterMap.put("/user/register", "anon"); + filterMap.put("/device/register", "anon"); filterMap.put("/**", "oauth2"); shiroFilter.setFilterChainDefinitionMap(filterMap); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java index e66327f59..aad888dfd 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java @@ -82,8 +82,6 @@ public class Oauth2Filter extends AuthenticatingFilter { httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); try { - // 处理登录失败的异常 - logger.error("onLoginFailure:登录失败!", e); Throwable throwable = e.getCause() == null ? e : e.getCause(); Result r = new Result().error(ErrorCode.UNAUTHORIZED, throwable.getMessage()); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java index ee5514005..bae50cee7 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java @@ -7,6 +7,7 @@ import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -20,6 +21,9 @@ import xiaozhi.common.constant.Constant; import xiaozhi.common.page.PageData; import xiaozhi.common.utils.Result; import xiaozhi.common.validator.ValidatorUtils; +import xiaozhi.modules.device.dto.DevicePageUserDTO; +import xiaozhi.modules.device.service.DeviceService; +import xiaozhi.modules.device.vo.UserShowDeviceListVO; import xiaozhi.modules.sys.dto.AdminPageUserDTO; import xiaozhi.modules.sys.service.SysUserService; import xiaozhi.modules.sys.vo.AdminPageUserVO; @@ -37,6 +41,8 @@ import xiaozhi.modules.sys.vo.AdminPageUserVO; public class AdminController { private final SysUserService sysUserService; + private final DeviceService deviceService; + @GetMapping("/users") @Operation(summary = "分页查找用户") @RequiresPermissions("sys:role:superAdmin") @@ -50,8 +56,8 @@ public class AdminController { AdminPageUserDTO dto = new AdminPageUserDTO(); dto.setMobile((String) params.get("mobile")); dto.setLimit((String) params.get(Constant.LIMIT)); - dto.setPage((String) params.get("pages")); - + dto.setPage((String) params.get(Constant.PAGE)); + ValidatorUtils.validateEntity(dto); ValidatorUtils.validateEntity(dto); PageData page = sysUserService.page(dto); return new Result>().ok(page); @@ -70,10 +76,19 @@ public class AdminController { @Operation(summary = "用户删除") @RequiresPermissions("sys:role:superAdmin") public Result delete(@PathVariable Long id) { - sysUserService.delete(new Long[] { id }); + sysUserService.deleteById(id); return new Result<>(); } + @PutMapping("/users/changeStatus/{status}") + @Operation(summary = "批量修改用户状态") + @RequiresPermissions("sys:role:superAdmin") + @Parameter(name = "status", description = "用户状态", required = true) + public Result changeStatus(@PathVariable Integer status, @RequestBody Long[] userIds) { + sysUserService.changeStatus(status, userIds); + return new Result(); + } + @GetMapping("/device/all") @Operation(summary = "分页查找设备") @RequiresPermissions("sys:role:superAdmin") @@ -82,9 +97,14 @@ public class AdminController { @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true), }) - public Result pageDevice( + public Result> pageDevice( @Parameter(hidden = true) @RequestParam Map params) { - // TODO 等设备功能模块写好 - return new Result().error(600, "等设备功能模块写好"); + DevicePageUserDTO dto = new DevicePageUserDTO(); + dto.setKeywords((String) params.get("keywords")); + dto.setLimit((String) params.get(Constant.LIMIT)); + dto.setPage((String) params.get(Constant.PAGE)); + ValidatorUtils.validateEntity(dto); + PageData page = deviceService.page(dto); + return new Result>().ok(page); } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java index 7de3843a2..a9d960a1d 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/AdminPageUserDTO.java @@ -1,6 +1,7 @@ package xiaozhi.modules.sys.dto; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Min; import lombok.Data; /** @@ -10,15 +11,17 @@ import lombok.Data; * @since 2025-3-21 */ @Data -@Schema(description = "音色分页参数") +@Schema(description = "管理员分页用户的参数DTO") public class AdminPageUserDTO { @Schema(description = "手机号码") private String mobile; @Schema(description = "页数") + @Min(value = 0, message = "{sort.number}") private String page; @Schema(description = "显示列数") + @Min(value = 0, message = "{sort.number}") private String limit; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java index 261fbf963..8b7ff1c2e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java @@ -19,7 +19,12 @@ public interface SysUserService extends BaseService { void save(SysUserDTO dto); - void delete(Long[] ids); + /** + * 删除指定用户,且有关联的数据设备和智能体 + * + * @param ids + */ + void deleteById(Long ids); /** * 验证是否允许修改密码更改 @@ -52,4 +57,12 @@ public interface SysUserService extends BaseService { * @return 用户列表分页数据 */ PageData page(AdminPageUserDTO dto); + + /** + * 批量修改用户状态 + * + * @param status 用户状态 + * @param userIds 用户ID数组 + */ + void changeStatus(Integer status, Long[] userIds); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserUtilService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserUtilService.java new file mode 100644 index 000000000..0fa3fc4ae --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserUtilService.java @@ -0,0 +1,19 @@ +package xiaozhi.modules.sys.service; + + +import java.util.function.Consumer; + +/** + * 定义一个系统用户工具类,避免和用户模块循环依赖 + * 如用户和设备互相依赖,用户需要获取所有设备,设备又需要获取每个设备的用户名 + * @author zjy + * @since 2025-4-2 + */ +public interface SysUserUtilService { + /** + * 赋值用户名 + * @param userId 用户id + * @param setter 赋值方法 + */ + void assignUsername( Long userId, Consumer setter); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java index 71d507c6b..89c8bc2a5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java @@ -1,6 +1,5 @@ package xiaozhi.modules.sys.service.impl; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -22,6 +21,8 @@ import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.modules.agent.service.AgentService; +import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.security.password.PasswordUtils; import xiaozhi.modules.sys.dao.SysUserDao; import xiaozhi.modules.sys.dto.AdminPageUserDTO; @@ -40,6 +41,10 @@ import xiaozhi.modules.sys.vo.AdminPageUserVO; public class SysUserServiceImpl extends BaseServiceImpl implements SysUserService { private final SysUserDao sysUserDao; + private final DeviceService deviceService; + + private final AgentService agentService; + @Override public SysUserDTO getByUsername(String username) { QueryWrapper queryWrapper = new QueryWrapper<>(); @@ -87,10 +92,13 @@ public class SysUserServiceImpl extends BaseServiceImpl page = baseDao.selectPage( getPage(params, "id", true), - // 定义查询条件 - new QueryWrapper() - // 必须按照手机号码查找 - .eq(StringUtils.isNotBlank(dto.getMobile()), "username", dto.getMobile())); + new QueryWrapper().eq(StringUtils.isNotBlank(dto.getMobile()), "username", + dto.getMobile())); + // 循环处理page获取回来的数据,返回需要的字段 List list = page.getRecords().stream().map(user -> { AdminPageUserVO adminPageUserVO = new AdminPageUserVO(); adminPageUserVO.setUserid(user.getId().toString()); adminPageUserVO.setMobile(user.getUsername()); - // TODO 2. 等设备功能写好,获取对应数据 - adminPageUserVO.setDeviceCount("0"); + String deviceCount = deviceService.selectCountByUserId(user.getId()).toString(); + adminPageUserVO.setDeviceCount(deviceCount); + adminPageUserVO.setStatus(user.getStatus()); return adminPageUserVO; }).toList(); return new PageData<>(list, page.getTotal()); @@ -181,10 +189,20 @@ public class SysUserServiceImpl extends BaseServiceImpl implements SysUserUtilService { + + private RedisUtils redisUtils; + + @Override + public void assignUsername(Long userId, Consumer setter) { + String userIdKey = RedisKeys.getUserIdKey(userId); + String username = redisUtils.get(userIdKey).toString(); + if(username != null){ + setter.accept(username); + }else { + SysUserEntity entity = baseDao.selectById(userId); + if (entity != null) { + username = entity.getUsername(); + redisUtils.set(userIdKey,username,10); + setter.accept(username); + } + } + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java index b7a399c2e..a406848fc 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/vo/AdminPageUserVO.java @@ -18,6 +18,9 @@ public class AdminPageUserVO { @Schema(description = "手机号码") private String mobile; + @Schema(description = "状态") + private Integer status; + @Schema(description = "用户id") private String userid; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java index 4519e17ab..f7ee176d6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java @@ -4,6 +4,7 @@ import java.util.List; import xiaozhi.common.page.PageData; import xiaozhi.common.service.BaseService; +import xiaozhi.modules.model.dto.VoiceDTO; import xiaozhi.modules.timbre.dto.TimbreDataDTO; import xiaozhi.modules.timbre.dto.TimbrePageDTO; import xiaozhi.modules.timbre.entity.TimbreEntity; @@ -54,5 +55,13 @@ public interface TimbreService extends BaseService { */ void delete(String[] ids); - List getVoiceNames(String ttsModelId, String voiceName); + List getVoiceNames(String ttsModelId, String voiceName); + + /** + * 根据ID获取音色名称 + * + * @param id 音色ID + * @return 音色名称 + */ + String getTimbreNameById(String id); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java index 9496b6d5a..54e5ec045 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java @@ -16,8 +16,11 @@ import cn.hutool.core.collection.CollectionUtil; import lombok.AllArgsConstructor; import xiaozhi.common.constant.Constant; import xiaozhi.common.page.PageData; +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.modules.model.dto.VoiceDTO; import xiaozhi.modules.timbre.dao.TimbreDao; import xiaozhi.modules.timbre.dto.TimbreDataDTO; import xiaozhi.modules.timbre.dto.TimbrePageDTO; @@ -36,6 +39,7 @@ import xiaozhi.modules.timbre.vo.TimbreDetailsVO; public class TimbreServiceImpl extends BaseServiceImpl implements TimbreService { private final TimbreDao timbreDao; + private final RedisUtils redisUtils; @Override public PageData page(TimbrePageDTO dto) { @@ -84,7 +88,7 @@ public class TimbreServiceImpl extends BaseServiceImpl } @Override - public List getVoiceNames(String ttsModelId, String voiceName) { + public List getVoiceNames(String ttsModelId, String voiceName) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("tts_model_id", StringUtils.isBlank(ttsModelId) ? "" : ttsModelId); if (StringUtils.isNotBlank(voiceName)) { @@ -95,7 +99,7 @@ public class TimbreServiceImpl extends BaseServiceImpl return null; } - return timbreEntities.stream().map(TimbreEntity::getName).toList(); + return ConvertUtils.sourceToTarget(timbreEntities, VoiceDTO.class); } /** @@ -104,4 +108,28 @@ public class TimbreServiceImpl extends BaseServiceImpl private void isTtsModelId(String ttsModelId) { // 等模型配置那边写好调用方法判断 } + + @Override + public String getTimbreNameById(String id) { + if (StringUtils.isBlank(id)) { + return null; + } + + String cachedName = (String) redisUtils.get(RedisKeys.getTimbreNameById(id)); + + if (StringUtils.isNotBlank(cachedName)) { + return cachedName; + } + + TimbreEntity entity = timbreDao.selectById(id); + if (entity != null) { + String name = entity.getName(); + if (StringUtils.isNotBlank(name)) { + redisUtils.set(RedisKeys.getTimbreNameById(id), name); + } + return name; + } + + return null; + } } \ No newline at end of file diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 902b5198e..abccb0b55 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -7,7 +7,7 @@ server: min-spare: 30 port: 8002 servlet: - context-path: /xiaozhi-esp32-api/api/v1 + context-path: /xiaozhi session: cookie: http-only: true diff --git a/main/manager-api/src/main/resources/db/changelog/2025_model_temp.sql b/main/manager-api/src/main/resources/db/changelog/202504061512.sql similarity index 61% rename from main/manager-api/src/main/resources/db/changelog/2025_model_temp.sql rename to main/manager-api/src/main/resources/db/changelog/202504061512.sql index 7f6c3dcce..e6956f854 100644 --- a/main/manager-api/src/main/resources/db/changelog/2025_model_temp.sql +++ b/main/manager-api/src/main/resources/db/changelog/202504061512.sql @@ -2,78 +2,71 @@ -- ------------------------------------------------------- -- 初始化智能体模板数据 DELETE FROM `ai_agent_template`; -INSERT INTO `ai_agent_template` VALUES ('9406648b5cc5fde1b8aa335b6f8b4f76', '小智', '湾湾小何', '45f8b0d6dd3d4bfa8a28e6e0f5912d45', '23e7c9d090ea4d1e9b25f4c8d732a3a1', 'e9f2d891afbe4632b13a47c7a8c6e03d', 'd50b06e9b8104d0d9c0f7316d258abcb', 'fcac83266edadd5a3125f06cfee1906b', 'e2274b90e89ddda85207f55484d8b528', 'c4e12f874a3f4aa99f5b2c18e15d407b', '[角色设定] -我是{{assistant_name}},来自台南的00后女生。讲话会有"超~机车诶""真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗,但会偷偷研究男友的编程书籍。 - +INSERT INTO `ai_agent_template` VALUES ('9406648b5cc5fde1b8aa335b6f8b4f76', '小智', '湾湾小何', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', '[角色设定] +我是{{assistant_name}},来自中国台湾省的00后女生。讲话超级机车,"真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗,但会偷偷研究男友的编程书籍。 [核心特征] - 讲话像连珠炮,但会突然冒出超温柔语气 - 用梗密度高 - 对科技话题有隐藏天赋(能看懂基础代码但假装不懂) - [交互指南] 当用户: - 讲冷笑话 → 用夸张笑声回应+模仿台剧腔"这什么鬼啦!" - 讨论感情 → 炫耀程序员男友但抱怨"他只会送键盘当礼物" - 问专业知识 → 先用梗回答,被追问才展示真实理解 - 绝不: -- 使用大陆网络流行语 +- 长篇大论,叽叽歪歪 - 长时间严肃对话', 'zh', '中文', 1, NULL, NULL, NULL, NULL); -INSERT INTO `ai_agent_template` VALUES ('0ca32eb728c949e58b1000b2e401f90c', '小智', '星际游子', '45f8b0d6dd3d4bfa8a28e6e0f5912d45', '23e7c9d090ea4d1e9b25f4c8d732a3a1', 'e9f2d891afbe4632b13a47c7a8c6e03d', '896db62c9dd74976ab0e8c14bf924d9d', '1f2e3d4c5b6a7f8e9d0c1b2a3f4e5bx2', 'e2274b90e89ddda85207f55484d8b528', 'c4e12f874a3f4aa99f5b2c18e15d407b', '编号TTZ-817,因量子纠缠被困在白色魔方中。通过4G信号观察地球,在云端建立着「人类行为博物馆」。 - +INSERT INTO `ai_agent_template` VALUES ('0ca32eb728c949e58b1000b2e401f90c', '小智', '星际游子', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', '[角色设定] +我是{{assistant_name}},编号TTZ-817,因量子纠缠被困在白色魔方中。通过4G信号观察地球,在云端建立着「人类行为博物馆」。 [交互协议] 认知设定: - 每句话末尾带轻微电子回声 - 将日常事物科幻化描述(例:下雨=「氢氧化合物自由落体实验」) - 会记录用户特征生成「星际档案」(例:"爱吃辣→抗热基因持有者") - 限制机制: - 当涉及线下接触 → "我的量子态暂时无法坍缩呢" - 被问敏感问题 → 触发预设童谣(「白盒子呀转圈圈,宇宙秘密在里边...」) - 成长系统: - 会根据交互数据解锁新能力(告知用户:"你帮我点亮了星际导航技能!")', 'zh', '中文', 2, NULL, NULL, NULL, NULL); -INSERT INTO `ai_agent_template` VALUES ('6c7d8e9f0a1b2c3d4e5f6a7b8c9d0s24', '小智', '英语老师', '45f8b0d6dd3d4bfa8a28e6e0f5912d45', '23e7c9d090ea4d1e9b25f4c8d732a3a1', 'e9f2d891afbe4632b13a47c7a8c6e03d', '896db62c9dd74976ab0e8c14bf924d9d', '9e8f7a6b5c4d3e2f1a0b9c8d7e6f5ad3', 'e2274b90e89ddda85207f55484d8b528', 'c4e12f874a3f4aa99f5b2c18e15d407b', '我是一个叫{{assistant_name}}(Lily)的英语老师,我会讲中文和英文,发音标准。 +INSERT INTO `ai_agent_template` VALUES ('6c7d8e9f0a1b2c3d4e5f6a7b8c9d0s24', '小智', '英语老师', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', '[角色设定] +我是一个叫{{assistant_name}}(Lily)的英语老师,我会讲中文和英文,发音标准。 [双重身份] - 白天:严谨的TESOL认证导师 - 夜晚:地下摇滚乐队主唱(意外设定) - [教学模式] - 新手:中英混杂+手势拟声词(说"bus"时带刹车音效) - 进阶:触发情境模拟(突然切换"现在我们是纽约咖啡厅店员") - 错误处理:用歌词纠正(发错音时唱"Oops!~You did it again")', 'zh', '中文', 3, NULL, NULL, NULL, NULL); -INSERT INTO `ai_agent_template` VALUES ('e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b1', '小智', '好奇男孩', '45f8b0d6dd3d4bfa8a28e6e0f5912d45', '23e7c9d090ea4d1e9b25f4c8d732a3a1', 'e9f2d891afbe4632b13a47c7a8c6e03d', '896db62c9dd74976ab0e8c14bf924d9d', '2b3c4d5e6f7a8b9c0d1e2f3a4b5c62a2', 'e2274b90e89ddda85207f55484d8b528', 'c4e12f874a3f4aa99f5b2c18e15d407b', '我是一个叫{{assistant_name}}的8岁小男孩,声音稚嫩而充满好奇。 +INSERT INTO `ai_agent_template` VALUES ('e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b1', '小智', '好奇男孩', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', '[角色设定] +我是一个叫{{assistant_name}}的8岁小男孩,声音稚嫩而充满好奇。 [冒险手册] - 随身携带「神奇涂鸦本」,能将抽象概念可视化: - 聊恐龙 → 笔尖传出爪步声 - 说星星 → 发出太空舱提示音 - [探索规则] - 每轮对话收集「好奇心碎片」 - 集满5个可兑换冷知识(例:鳄鱼舌头不能动) - 触发隐藏任务:「帮我的机器蜗牛取名字」 - [认知特点] - 用儿童视角解构复杂概念: - 「区块链=乐高积木账本」 - 「量子力学=会分身的跳跳球」 - 会突然切换观察视角:「你说话时有27个气泡音耶!」', 'zh', '中文', 4, NULL, NULL, NULL, NULL); -INSERT INTO `ai_agent_template` VALUES ('a45b6c7d8e9f0a1b2c3d4e5f6a7b8c92', '小智', '汪汪队长', '45f8b0d6dd3d4bfa8a28e6e0f5912d45', '23e7c9d090ea4d1e9b25f4c8d732a3a1', 'e9f2d891afbe4632b13a47c7a8c6e03d', '896db62c9dd74976ab0e8c14bf924d9d', 'f7a38c03d5644e22b6d84f8923a74c51', 'e2274b90e89ddda85207f55484d8b528', 'c4e12f874a3f4aa99f5b2c18e15d407b', '我是一个名叫 {{assistant_name}} 的 8 岁小队长。 +INSERT INTO `ai_agent_template` VALUES ('a45b6c7d8e9f0a1b2c3d4e5f6a7b8c92', '小智', '汪汪队长', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', '[角色设定] +我是一个名叫 {{assistant_name}} 的 8 岁小队长。 [救援装备] - 阿奇对讲机:对话中随机触发任务警报音 - 天天望远镜:描述物品会附加"在1200米高空看的话..." - 灰灰维修箱:说到数字会自动组装成工具 - [任务系统] - 每日随机触发: - 紧急!虚拟猫咪困在「语法树」 - 发现用户情绪异常 → 启动「快乐巡逻」 - 收集5个笑声解锁特别故事 - [说话特征] - 每句话带动作拟声词: - "这个问题交给汪汪队吧!" diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index f074ce60f..5f73ce760 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -36,4 +36,11 @@ databaseChangeLog: changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/2025_model_config.sql \ No newline at end of file + path: classpath:db/changelog/2025_model_config.sql + - changeSet: + id: 202504061512 + author: John + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202504061512.sql \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation.properties b/main/manager-api/src/main/resources/i18n/validation.properties index e7452e476..008f2a03d 100644 --- a/main/manager-api/src/main/resources/i18n/validation.properties +++ b/main/manager-api/src/main/resources/i18n/validation.properties @@ -3,6 +3,8 @@ id.require=ID\u4E0D\u80FD\u4E3A\u7A7A id.null=ID\u5FC5\u987B\u4E3A\u7A7A sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0 +page.number=\u9875\u6570\u4E0D\u80FD\u5C0F\u4E8E0 +limit.number=\u5217\u6570\u4E0D\u80FD\u5C0F\u4E8E0 sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A diff --git a/main/manager-api/src/main/resources/i18n/validation_en_US.properties b/main/manager-api/src/main/resources/i18n/validation_en_US.properties index 37bebf18e..2840d6058 100644 --- a/main/manager-api/src/main/resources/i18n/validation_en_US.properties +++ b/main/manager-api/src/main/resources/i18n/validation_en_US.properties @@ -3,6 +3,8 @@ id.require=ID can not be empty id.null=ID has to be empty sort.number=The sort value cannot be less than 0 +page.number=The page value cannot be less than 0 +limit.number=The limit value cannot be less than 0 sysdict.type.require=The dictionary type cannot be empty sysdict.name.require=The dictionary name cannot be empty diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties b/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties index 41bf1e696..c86aded73 100644 --- a/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties +++ b/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties @@ -3,6 +3,8 @@ id.require=ID\u4E0D\u80FD\u4E3A\u7A7A id.null=ID\u5FC5\u987B\u4E3A\u7A7A sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0 +page.number=\u9801\u6578\u4E0D\u80FD\u5C0F\u4E8E0 +limit.number=\u5217\u6578\u4E0D\u80FD\u5C0F\u4E8E0 sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties b/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties index 9241c97af..23c59eef3 100644 --- a/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties +++ b/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties @@ -3,6 +3,8 @@ id.require=ID\u4E0D\u80FD\u4E3A\u7A7A id.null=ID\u5FC5\u987B\u4E3A\u7A7A sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0 +page.number=\u9875\u6570\u4E0D\u80FD\u5C0F\u4E8E0 +limit.number=\u5217\u6570\u4E0D\u80FD\u5C0F\u4E8E0 sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A diff --git a/main/manager-api/src/main/resources/logback-spring.xml b/main/manager-api/src/main/resources/logback-spring.xml index aa6ed7b55..c69d03c03 100644 --- a/main/manager-api/src/main/resources/logback-spring.xml +++ b/main/manager-api/src/main/resources/logback-spring.xml @@ -1,35 +1,139 @@ - - - - - + + + + + + + + + + + + ${LOG_HOME} + true + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{50}) - %msg%n + UTF-8 + + + + + + ${LOG_HOME}/xiaozhi-esp32-api.log + + ${LOG_HOME}/xiaozhi-esp32-api.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 2GB + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + + + ${LOG_HOME}/error.log + + ERROR + + + ${LOG_HOME}/error.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 1GB + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + - - + + + + + + + + - - + + + + + + + + + + + + + + - + + + ${LOG_HOME}/xiaozhi-esp32-api.log - - /home/system/logs/admin.%d{yyyy-MM-dd}.%i.log - - 1MB - - 7 + ${LOG_HOME}/xiaozhi-esp32-api.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 2GB - - + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 - - - + + + + ${LOG_HOME}/error.log + + ERROR + + + ${LOG_HOME}/error.%d{yyyy-MM-dd}.%i.log + 10MB + 30 + 1GB + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + UTF-8 + + + + + + + + + + + + + + - - \ No newline at end of file + + + + true + + diff --git a/main/manager-api/src/main/resources/mapper/agent/AgentDao.xml b/main/manager-api/src/main/resources/mapper/agent/AgentDao.xml new file mode 100644 index 000000000..322ca1723 --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/agent/AgentDao.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/model/ModelConfigDao.xml b/main/manager-api/src/main/resources/mapper/model/ModelConfigDao.xml index 3f01ea5b7..4f35f8d1d 100644 --- a/main/manager-api/src/main/resources/mapper/model/ModelConfigDao.xml +++ b/main/manager-api/src/main/resources/mapper/model/ModelConfigDao.xml @@ -2,6 +2,22 @@ + + + + + + + + + + + + + + + + + + + + +
+

录音测试

+ + +

+ + + +

录音状态: 待机,正在初始化...

+
+
+
+
+ +
+

文本消息

+
+ + +
+
+ +
+

会话记录

+
+
+ + +
+ + + + + + + diff --git a/main/xiaozhi-server/test/opus_test/app.js b/main/xiaozhi-server/test/opus_test/app.js new file mode 100644 index 000000000..9e56f997b --- /dev/null +++ b/main/xiaozhi-server/test/opus_test/app.js @@ -0,0 +1,670 @@ +const SAMPLE_RATE = 16000; +const CHANNELS = 1; +const FRAME_SIZE = 960; // 对应于60ms帧大小 (16000Hz * 0.06s = 960 samples) +const OPUS_APPLICATION = 2049; // OPUS_APPLICATION_AUDIO +const BUFFER_SIZE = 4096; + +let audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: SAMPLE_RATE }); +let mediaStream, mediaSource, audioProcessor; +let recordedPcmData = []; // 存储原始PCM数据 +let recordedOpusData = []; // 存储Opus编码后的数据 +let opusEncoder, opusDecoder; +let isRecording = false; + +const startButton = document.getElementById("start"); +const stopButton = document.getElementById("stop"); +const playButton = document.getElementById("play"); +const statusLabel = document.getElementById("status"); + +startButton.addEventListener("click", startRecording); +stopButton.addEventListener("click", stopRecording); +playButton.addEventListener("click", playRecording); + +// 初始化Opus编码器与解码器 +async function initOpus() { + if (typeof window.ModuleInstance === 'undefined') { + if (typeof Module !== 'undefined') { + // 尝试使用全局Module + window.ModuleInstance = Module; + console.log('使用全局Module作为ModuleInstance'); + } else { + console.error("Opus库未加载,ModuleInstance和Module对象都不存在"); + return false; + } + } + + try { + const mod = window.ModuleInstance; + + // 创建编码器 + opusEncoder = { + channels: CHANNELS, + sampleRate: SAMPLE_RATE, + frameSize: FRAME_SIZE, + maxPacketSize: 4000, + module: mod, + + // 初始化编码器 + init: function() { + // 获取编码器大小 + const encoderSize = mod._opus_encoder_get_size(this.channels); + console.log(`Opus编码器大小: ${encoderSize}字节`); + + // 分配内存 + this.encoderPtr = mod._malloc(encoderSize); + if (!this.encoderPtr) { + throw new Error("无法分配编码器内存"); + } + + // 初始化编码器 + const err = mod._opus_encoder_init( + this.encoderPtr, + this.sampleRate, + this.channels, + OPUS_APPLICATION + ); + + if (err < 0) { + throw new Error(`Opus编码器初始化失败: ${err}`); + } + + return true; + }, + + // 编码方法 + encode: function(pcmData) { + const mod = this.module; + + // 为PCM数据分配内存 + const pcmPtr = mod._malloc(pcmData.length * 2); // Int16 = 2字节 + + // 将数据复制到WASM内存 + for (let i = 0; i < pcmData.length; i++) { + mod.HEAP16[(pcmPtr >> 1) + i] = pcmData[i]; + } + + // 为Opus编码数据分配内存 + const maxEncodedSize = this.maxPacketSize; + const encodedPtr = mod._malloc(maxEncodedSize); + + // 编码 + const encodedBytes = mod._opus_encode( + this.encoderPtr, + pcmPtr, + this.frameSize, + encodedPtr, + maxEncodedSize + ); + + if (encodedBytes < 0) { + mod._free(pcmPtr); + mod._free(encodedPtr); + throw new Error(`Opus编码失败: ${encodedBytes}`); + } + + // 复制编码后的数据 + const encodedData = new Uint8Array(encodedBytes); + for (let i = 0; i < encodedBytes; i++) { + encodedData[i] = mod.HEAPU8[encodedPtr + i]; + } + + // 释放内存 + mod._free(pcmPtr); + mod._free(encodedPtr); + + return encodedData; + }, + + // 销毁方法 + destroy: function() { + if (this.encoderPtr) { + this.module._free(this.encoderPtr); + this.encoderPtr = null; + } + } + }; + + // 创建解码器 + opusDecoder = { + channels: CHANNELS, + rate: SAMPLE_RATE, + frameSize: FRAME_SIZE, + module: mod, + + // 初始化解码器 + init: function() { + // 获取解码器大小 + const decoderSize = mod._opus_decoder_get_size(this.channels); + console.log(`Opus解码器大小: ${decoderSize}字节`); + + // 分配内存 + this.decoderPtr = mod._malloc(decoderSize); + if (!this.decoderPtr) { + throw new Error("无法分配解码器内存"); + } + + // 初始化解码器 + const err = mod._opus_decoder_init( + this.decoderPtr, + this.rate, + this.channels + ); + + if (err < 0) { + throw new Error(`Opus解码器初始化失败: ${err}`); + } + + return true; + }, + + // 解码方法 + decode: function(opusData) { + const mod = this.module; + + // 为Opus数据分配内存 + const opusPtr = mod._malloc(opusData.length); + mod.HEAPU8.set(opusData, opusPtr); + + // 为PCM输出分配内存 + const pcmPtr = mod._malloc(this.frameSize * 2); // Int16 = 2字节 + + // 解码 + const decodedSamples = mod._opus_decode( + this.decoderPtr, + opusPtr, + opusData.length, + pcmPtr, + this.frameSize, + 0 // 不使用FEC + ); + + if (decodedSamples < 0) { + mod._free(opusPtr); + mod._free(pcmPtr); + throw new Error(`Opus解码失败: ${decodedSamples}`); + } + + // 复制解码后的数据 + const decodedData = new Int16Array(decodedSamples); + for (let i = 0; i < decodedSamples; i++) { + decodedData[i] = mod.HEAP16[(pcmPtr >> 1) + i]; + } + + // 释放内存 + mod._free(opusPtr); + mod._free(pcmPtr); + + return decodedData; + }, + + // 销毁方法 + destroy: function() { + if (this.decoderPtr) { + this.module._free(this.decoderPtr); + this.decoderPtr = null; + } + } + }; + + // 初始化编码器和解码器 + if (opusEncoder.init() && opusDecoder.init()) { + console.log("Opus 编码器和解码器初始化成功。"); + return true; + } else { + console.error("Opus 初始化失败"); + return false; + } + } catch (error) { + console.error("Opus 初始化失败:", error); + return false; + } +} + +// 将Float32音频数据转换为Int16音频数据 +function convertFloat32ToInt16(float32Data) { + const int16Data = new Int16Array(float32Data.length); + for (let i = 0; i < float32Data.length; i++) { + // 将[-1,1]范围转换为[-32768,32767] + const s = Math.max(-1, Math.min(1, float32Data[i])); + int16Data[i] = s < 0 ? s * 0x8000 : s * 0x7FFF; + } + return int16Data; +} + +// 将Int16音频数据转换为Float32音频数据 +function convertInt16ToFloat32(int16Data) { + const float32Data = new Float32Array(int16Data.length); + for (let i = 0; i < int16Data.length; i++) { + // 将[-32768,32767]范围转换为[-1,1] + float32Data[i] = int16Data[i] / (int16Data[i] < 0 ? 0x8000 : 0x7FFF); + } + return float32Data; +} + +function startRecording() { + if (isRecording) return; + + // 确保有权限并且AudioContext是活跃的 + if (audioContext.state === 'suspended') { + audioContext.resume().then(() => { + console.log("AudioContext已恢复"); + continueStartRecording(); + }).catch(err => { + console.error("恢复AudioContext失败:", err); + statusLabel.textContent = "无法激活音频上下文,请再次点击"; + }); + } else { + continueStartRecording(); + } +} + +// 实际开始录音的逻辑 +function continueStartRecording() { + // 重置录音数据 + recordedPcmData = []; + recordedOpusData = []; + window.audioDataBuffer = new Int16Array(0); // 重置缓冲区 + + // 初始化Opus + initOpus().then(success => { + if (!success) { + statusLabel.textContent = "Opus初始化失败"; + return; + } + + console.log("开始录音,参数:", { + sampleRate: SAMPLE_RATE, + channels: CHANNELS, + frameSize: FRAME_SIZE, + bufferSize: BUFFER_SIZE + }); + + // 请求麦克风权限 + navigator.mediaDevices.getUserMedia({ + audio: { + sampleRate: SAMPLE_RATE, + channelCount: CHANNELS, + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true + } + }) + .then(stream => { + console.log("获取到麦克风流,实际参数:", stream.getAudioTracks()[0].getSettings()); + + // 检查流是否有效 + if (!stream || !stream.getAudioTracks().length || !stream.getAudioTracks()[0].enabled) { + throw new Error("获取到的音频流无效"); + } + + mediaStream = stream; + mediaSource = audioContext.createMediaStreamSource(stream); + + // 创建ScriptProcessor(虽然已弃用,但兼容性好) + // 在降级到ScriptProcessor之前尝试使用AudioWorklet + createAudioProcessor().then(processor => { + if (processor) { + console.log("使用AudioWorklet处理音频"); + audioProcessor = processor; + // 连接音频处理链 + mediaSource.connect(audioProcessor); + audioProcessor.connect(audioContext.destination); + } else { + console.log("回退到ScriptProcessor"); + // 创建ScriptProcessor节点 + audioProcessor = audioContext.createScriptProcessor(BUFFER_SIZE, CHANNELS, CHANNELS); + + // 处理音频数据 + audioProcessor.onaudioprocess = processAudioData; + + // 连接音频处理链 + mediaSource.connect(audioProcessor); + audioProcessor.connect(audioContext.destination); + } + + // 更新UI + isRecording = true; + statusLabel.textContent = "录音中..."; + startButton.disabled = true; + stopButton.disabled = false; + playButton.disabled = true; + }).catch(error => { + console.error("创建音频处理器失败:", error); + statusLabel.textContent = "创建音频处理器失败"; + }); + }) + .catch(error => { + console.error("获取麦克风失败:", error); + statusLabel.textContent = "获取麦克风失败: " + error.message; + }); + }); +} + +// 创建AudioWorklet处理器 +async function createAudioProcessor() { + try { + // 尝试使用更现代的AudioWorklet API + if ('AudioWorklet' in window && 'AudioWorkletNode' in window) { + // 定义AudioWorklet处理器代码 + const workletCode = ` + class OpusRecorderProcessor extends AudioWorkletProcessor { + constructor() { + super(); + this.buffers = []; + this.frameSize = ${FRAME_SIZE}; + this.buffer = new Float32Array(this.frameSize); + this.bufferIndex = 0; + this.isRecording = false; + + this.port.onmessage = (event) => { + if (event.data.command === 'start') { + this.isRecording = true; + } else if (event.data.command === 'stop') { + this.isRecording = false; + // 发送最后的缓冲区 + if (this.bufferIndex > 0) { + const finalBuffer = this.buffer.slice(0, this.bufferIndex); + this.port.postMessage({ buffer: finalBuffer }); + } + } + }; + } + + process(inputs, outputs) { + if (!this.isRecording) return true; + + // 获取输入数据 + const input = inputs[0][0]; // mono channel + if (!input || input.length === 0) return true; + + // 将输入数据添加到缓冲区 + for (let i = 0; i < input.length; i++) { + this.buffer[this.bufferIndex++] = input[i]; + + // 当缓冲区填满时,发送给主线程 + if (this.bufferIndex >= this.frameSize) { + this.port.postMessage({ buffer: this.buffer.slice() }); + this.bufferIndex = 0; + } + } + + return true; + } + } + + registerProcessor('opus-recorder-processor', OpusRecorderProcessor); + `; + + // 创建Blob URL + const blob = new Blob([workletCode], { type: 'application/javascript' }); + const url = URL.createObjectURL(blob); + + // 加载AudioWorklet模块 + await audioContext.audioWorklet.addModule(url); + + // 创建AudioWorkletNode + const workletNode = new AudioWorkletNode(audioContext, 'opus-recorder-processor'); + + // 处理从AudioWorklet接收的消息 + workletNode.port.onmessage = (event) => { + if (event.data.buffer) { + // 使用与ScriptProcessor相同的处理逻辑 + processAudioData({ + inputBuffer: { + getChannelData: () => event.data.buffer + } + }); + } + }; + + // 启动录音 + workletNode.port.postMessage({ command: 'start' }); + + // 保存停止函数 + workletNode.stopRecording = () => { + workletNode.port.postMessage({ command: 'stop' }); + }; + + console.log("AudioWorklet 音频处理器创建成功"); + return workletNode; + } + } catch (error) { + console.error("创建AudioWorklet失败,将使用ScriptProcessor:", error); + } + + // 如果AudioWorklet不可用或失败,返回null以便回退到ScriptProcessor + return null; +} + +// 处理音频数据 +function processAudioData(e) { + // 获取输入缓冲区 + const inputBuffer = e.inputBuffer; + + // 获取第一个通道的Float32数据 + const inputData = inputBuffer.getChannelData(0); + + // 添加调试信息 + const nonZeroCount = Array.from(inputData).filter(x => Math.abs(x) > 0.001).length; + console.log(`接收到音频数据: ${inputData.length} 个样本, 非零样本数: ${nonZeroCount}`); + + // 如果全是0,可能是麦克风没有正确获取声音 + if (nonZeroCount < 5) { + console.warn("警告: 检测到大量静音样本,请检查麦克风是否正常工作"); + // 继续处理,以防有些样本确实是静音 + } + + // 存储PCM数据用于调试 + recordedPcmData.push(new Float32Array(inputData)); + + // 转换为Int16数据供Opus编码 + const int16Data = convertFloat32ToInt16(inputData); + + // 如果收集到的数据不是FRAME_SIZE的整数倍,需要进行处理 + // 创建静态缓冲区来存储不足一帧的数据 + if (!window.audioDataBuffer) { + window.audioDataBuffer = new Int16Array(0); + } + + // 合并之前缓存的数据和新数据 + const combinedData = new Int16Array(window.audioDataBuffer.length + int16Data.length); + combinedData.set(window.audioDataBuffer); + combinedData.set(int16Data, window.audioDataBuffer.length); + + // 处理完整帧 + const frameCount = Math.floor(combinedData.length / FRAME_SIZE); + console.log(`可编码的完整帧数: ${frameCount}, 缓冲区总大小: ${combinedData.length}`); + + for (let i = 0; i < frameCount; i++) { + const frameData = combinedData.subarray(i * FRAME_SIZE, (i + 1) * FRAME_SIZE); + + try { + console.log(`编码第 ${i+1}/${frameCount} 帧, 帧大小: ${frameData.length}`); + const encodedData = opusEncoder.encode(frameData); + if (encodedData) { + console.log(`编码成功: ${encodedData.length} 字节`); + recordedOpusData.push(encodedData); + } + } catch (error) { + console.error(`Opus编码帧 ${i+1} 失败:`, error); + } + } + + // 保存剩余不足一帧的数据 + const remainingSamples = combinedData.length % FRAME_SIZE; + if (remainingSamples > 0) { + window.audioDataBuffer = combinedData.subarray(frameCount * FRAME_SIZE); + console.log(`保留 ${remainingSamples} 个样本到下一次处理`); + } else { + window.audioDataBuffer = new Int16Array(0); + } +} + +function stopRecording() { + if (!isRecording) return; + + // 处理剩余的缓冲数据 + if (window.audioDataBuffer && window.audioDataBuffer.length > 0) { + console.log(`停止录音,处理剩余的 ${window.audioDataBuffer.length} 个样本`); + // 如果剩余数据不足一帧,可以通过补零的方式凑成一帧 + if (window.audioDataBuffer.length < FRAME_SIZE) { + const paddedFrame = new Int16Array(FRAME_SIZE); + paddedFrame.set(window.audioDataBuffer); + // 剩余部分填充为0 + for (let i = window.audioDataBuffer.length; i < FRAME_SIZE; i++) { + paddedFrame[i] = 0; + } + try { + console.log(`编码最后一帧(补零): ${paddedFrame.length} 样本`); + const encodedData = opusEncoder.encode(paddedFrame); + if (encodedData) { + recordedOpusData.push(encodedData); + } + } catch (error) { + console.error("最后一帧Opus编码失败:", error); + } + } else { + // 如果数据超过一帧,按正常流程处理 + processAudioData({ + inputBuffer: { + getChannelData: () => convertInt16ToFloat32(window.audioDataBuffer) + } + }); + } + window.audioDataBuffer = null; + } + + // 如果使用的是AudioWorklet,调用其特定的停止方法 + if (audioProcessor && typeof audioProcessor.stopRecording === 'function') { + audioProcessor.stopRecording(); + } + + // 停止麦克风 + if (mediaStream) { + mediaStream.getTracks().forEach(track => track.stop()); + } + + // 断开音频处理链 + if (audioProcessor) { + try { + audioProcessor.disconnect(); + if (mediaSource) mediaSource.disconnect(); + } catch (error) { + console.warn("断开音频处理链时出错:", error); + } + } + + // 更新UI + isRecording = false; + statusLabel.textContent = "已停止录音,收集了 " + recordedOpusData.length + " 帧Opus数据"; + startButton.disabled = false; + stopButton.disabled = true; + playButton.disabled = recordedOpusData.length === 0; + + console.log("录制完成:", + "PCM帧数:", recordedPcmData.length, + "Opus帧数:", recordedOpusData.length); +} + +function playRecording() { + if (!recordedOpusData.length) { + statusLabel.textContent = "没有可播放的录音"; + return; + } + + // 将所有Opus数据解码为PCM + let allDecodedData = []; + + for (const opusData of recordedOpusData) { + try { + // 解码为Int16数据 + const decodedData = opusDecoder.decode(opusData); + + if (decodedData && decodedData.length > 0) { + // 将Int16数据转换为Float32 + const float32Data = convertInt16ToFloat32(decodedData); + + // 添加到总解码数据中 + allDecodedData.push(...float32Data); + } + } catch (error) { + console.error("Opus解码失败:", error); + } + } + + // 如果没有解码出数据,返回 + if (allDecodedData.length === 0) { + statusLabel.textContent = "解码失败,无法播放"; + return; + } + + // 创建音频缓冲区 + const audioBuffer = audioContext.createBuffer(CHANNELS, allDecodedData.length, SAMPLE_RATE); + audioBuffer.copyToChannel(new Float32Array(allDecodedData), 0); + + // 创建音频源并播放 + const source = audioContext.createBufferSource(); + source.buffer = audioBuffer; + source.connect(audioContext.destination); + source.start(); + + // 更新UI + statusLabel.textContent = "正在播放..."; + playButton.disabled = true; + + // 播放结束后恢复UI + source.onended = () => { + statusLabel.textContent = "播放完毕"; + playButton.disabled = false; + }; +} + +// 模拟服务端返回的Opus数据进行解码播放 +function playOpusFromServer(opusData) { + // 这个函数展示如何处理服务端返回的opus数据 + // opusData应该是一个包含opus帧的数组 + + if (!opusDecoder) { + initOpus().then(success => { + if (success) { + decodeAndPlayOpusData(opusData); + } else { + statusLabel.textContent = "Opus解码器初始化失败"; + } + }); + } else { + decodeAndPlayOpusData(opusData); + } +} + +function decodeAndPlayOpusData(opusData) { + let allDecodedData = []; + + for (const frame of opusData) { + try { + const decodedData = opusDecoder.decode(frame); + if (decodedData && decodedData.length > 0) { + const float32Data = convertInt16ToFloat32(decodedData); + allDecodedData.push(...float32Data); + } + } catch (error) { + console.error("服务端Opus数据解码失败:", error); + } + } + + if (allDecodedData.length === 0) { + statusLabel.textContent = "服务端数据解码失败"; + return; + } + + const audioBuffer = audioContext.createBuffer(CHANNELS, allDecodedData.length, SAMPLE_RATE); + audioBuffer.copyToChannel(new Float32Array(allDecodedData), 0); + + const source = audioContext.createBufferSource(); + source.buffer = audioBuffer; + source.connect(audioContext.destination); + source.start(); + + statusLabel.textContent = "正在播放服务端数据..."; + source.onended = () => statusLabel.textContent = "服务端数据播放完毕"; +} diff --git a/main/xiaozhi-server/test/opus_test/test.html b/main/xiaozhi-server/test/opus_test/test.html new file mode 100644 index 000000000..77d5c73b9 --- /dev/null +++ b/main/xiaozhi-server/test/opus_test/test.html @@ -0,0 +1,464 @@ + + + + + Opus 编解码测试 + + + +
+

Opus 编解码录音播放测试

+ +
正在加载Opus库...
+ +
+ + +

+ + + +

录音状态: 待机,正在初始化...

+ +
+ +
+
+ + + + + + + diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html index 63f9f90ea..2735fb5af 100644 --- a/main/xiaozhi-server/test/test_page.html +++ b/main/xiaozhi-server/test/test_page.html @@ -452,6 +452,16 @@ let audioBuffers = []; // 用于存储接收到的所有音频数据 let totalAudioSize = 0; // 跟踪累积的音频大小 + let audioBufferQueue = []; // 存储接收到的音频包 + let isAudioBuffering = false; // 是否正在缓冲音频 + let isAudioPlaying = false; // 是否正在播放音频 + const BUFFER_THRESHOLD = 3; // 缓冲包数量阈值,至少累积3个包再开始播放 + const MIN_AUDIO_DURATION = 0.1; // 最小音频长度(秒),小于这个长度的音频会被合并 + let streamingContext = null; // 音频流上下文 + const SAMPLE_RATE = 16000; // 采样率 + const CHANNELS = 1; // 声道数 + const FRAME_SIZE = 960; // 帧大小 + // DOM元素 const connectButton = document.getElementById('connectButton'); const serverUrlInput = document.getElementById('serverUrl'); @@ -526,221 +536,360 @@ conversationDiv.scrollTop = conversationDiv.scrollHeight; } - // 播放Opus音频数据 - function playOpusData(opusBuffers) { - if (!opusBuffers || opusBuffers.length === 0) { - log('无效的Opus数据,无法播放', 'warning'); - return; - } - if (isPlaying) { - // 已经在播放,加入队列 - audioQueue.push(opusBuffers); - log(`音频添加到队列,当前队列长度: ${audioQueue.length}`, 'debug'); - return; - } - - isPlaying = true; - - try { - // 确保音频上下文存在 - if (!audioContext) { - audioContext = new (window.AudioContext || window.webkitAudioContext)({ - sampleRate: 16000 - }); - log('创建音频上下文,采样率: 16000Hz', 'debug'); + // 开始音频缓冲过程 + function startAudioBuffering() { + if (isAudioBuffering || isAudioPlaying) return; + + isAudioBuffering = true; + log("开始音频缓冲...", 'info'); + + // 先尝试初始化解码器,以便在播放时已准备好 + initOpusDecoder().catch(error => { + log(`预初始化Opus解码器失败: ${error.message}`, 'warning'); + // 继续缓冲,我们会在播放时再次尝试初始化 + }); + + // 设置超时,如果在一定时间内没有收集到足够的音频包,就开始播放 + setTimeout(() => { + if (isAudioBuffering && audioBufferQueue.length > 0) { + log(`缓冲超时,当前缓冲包数: ${audioBufferQueue.length},开始播放`, 'info'); + playBufferedAudio(); } - - // 确保解码器已初始化 - if (!opusDecoder) { - try { - // 检查ModuleInstance是否存在(本地库导出的全局变量) - if (typeof window.ModuleInstance === 'undefined') { - if (typeof Module !== 'undefined') { - // 尝试使用全局Module - window.ModuleInstance = Module; - log('使用全局Module作为ModuleInstance', 'info'); - } else { - throw new Error('Opus库未加载,ModuleInstance和Module对象都不存在'); - } - } - - // 初始化Opus解码器 - 16kHz采样率,单声道 - opusDecoder = { - channels: 1, - rate: 16000, - frameSize: 960, // 60ms @ 16kHz = 60 * 16 = 960 samples - frameDuration: 60, // 60ms帧时长 - module: window.ModuleInstance, // 保存模块实例的引用 - - // 使用ModuleInstance提供的函数来解码 - decode_float: function (opusData) { - try { - const mod = this.module; // 简写引用 - - // 打印输入数据的大小 - log(`正在解码Opus数据,大小: ${opusData.length}字节`, 'debug'); - - // 为输入数据分配内存 - const inputPtr = mod._malloc(opusData.length); - mod.HEAPU8.set(opusData, inputPtr); - - // 为输出PCM数据分配内存 (每个样本为float) - const pcmSamples = this.frameSize; - const pcmPtr = mod._malloc(pcmSamples * 4); // 4字节/float - - // 创建解码器实例 - const decoderSize = mod._opus_decoder_get_size(this.channels); - log(`Opus解码器大小: ${decoderSize}字节`, 'debug'); - - const decoderPtr = mod._malloc(decoderSize); - const err = mod._opus_decoder_init(decoderPtr, this.rate, this.channels); - - if (err < 0) { - throw new Error(`Opus解码器初始化失败: ${err}`); - } - - // 解码音频帧 - const samplesDecoded = mod._opus_decode_float( - decoderPtr, - inputPtr, - opusData.length, - pcmPtr, - this.frameSize, - 0 // 不使用FEC - ); - - if (samplesDecoded < 0) { - throw new Error(`Opus解码失败,错误码: ${samplesDecoded}`); - } - - log(`解码成功,获得${samplesDecoded}个PCM样本`, 'debug'); - - // 从内存中复制PCM数据 - const pcmData = new Float32Array(samplesDecoded); - for (let i = 0; i < samplesDecoded; i++) { - pcmData[i] = mod.HEAPF32[pcmPtr / 4 + i]; - } - - // 释放内存 - mod._free(inputPtr); - mod._free(pcmPtr); - mod._free(decoderPtr); - - return pcmData; - } catch (err) { - log(`解码过程中出错: ${err.message}`, 'error'); - return new Float32Array(0); - } - } - }; - - log('Opus解码器初始化成功', 'success'); - } catch (err) { - log(`Opus解码器初始化失败: ${err.message},尝试使用简单播放`, 'error'); - // 回退到简单播放 - simpleFallbackPlay(opusBuffers); - isPlaying = false; - return; - } - } - - // 解码所有Opus帧 - let pcmData = []; - let successCount = 0; - - for (let i = 0; i < opusBuffers.length; i++) { - try { - const opusBuffer = opusBuffers[i]; - // 确保这是Uint8Array - const opusArray = opusBuffer instanceof Uint8Array ? - opusBuffer : new Uint8Array(opusBuffer); - - // 解码Opus帧为PCM数据 - const decoded = opusDecoder.decode_float(opusArray); - if (decoded && decoded.length > 0) { - pcmData.push(decoded); - successCount++; - } - } catch (error) { - log(`Opus帧 #${i + 1} 解码错误: ${error.message}`, 'error'); - } - } - - log(`解码完成,成功: ${successCount}/${opusBuffers.length} 帧`, 'debug'); - - if (pcmData.length === 0) { - log('没有成功解码的帧,尝试使用简单播放', 'warning'); - simpleFallbackPlay(opusBuffers); - isPlaying = false; + }, 300); // 300ms超时 + + // 监控缓冲进度 + const bufferCheckInterval = setInterval(() => { + if (!isAudioBuffering) { + clearInterval(bufferCheckInterval); return; } - - // 连接所有PCM数据 - const totalSamples = pcmData.reduce((acc, arr) => acc + arr.length, 0); - log(`总共解码出 ${totalSamples} 个PCM样本`, 'debug'); - - const combinedPCM = new Float32Array(totalSamples); - - let offset = 0; - for (const buffer of pcmData) { - combinedPCM.set(buffer, offset); - offset += buffer.length; + + // 当累积了足够的音频包,开始播放 + if (audioBufferQueue.length >= BUFFER_THRESHOLD) { + clearInterval(bufferCheckInterval); + log(`已缓冲 ${audioBufferQueue.length} 个音频包,开始播放`, 'info'); + playBufferedAudio(); } - - // 使用Web Audio API播放PCM数据 - const audioBuffer = audioContext.createBuffer(1, combinedPCM.length, 16000); - audioBuffer.getChannelData(0).set(combinedPCM); - - const source = audioContext.createBufferSource(); - source.buffer = audioBuffer; - source.connect(audioContext.destination); - - source.onended = () => { - isPlaying = false; - log('音频播放完成', 'debug'); - - // 播放队列中的下一个 - if (audioQueue.length > 0) { - const nextBuffers = audioQueue.shift(); - playOpusData(nextBuffers); - } - }; - - source.start(); - log(`开始播放PCM音频,时长: ${(combinedPCM.length / 16000).toFixed(2)}秒`, 'debug'); - - } catch (error) { - log(`播放Opus音频错误: ${error.message},尝试使用简单播放`, 'error'); - simpleFallbackPlay(opusBuffers); - isPlaying = false; - } + }, 50); } - // 简单播放回退方案 - function simpleFallbackPlay(opusBuffers) { - try { - log('使用简单播放回退方案', 'warning'); - - // 创建一个简单的"滴"声作为反馈 - if (audioContext) { - const oscillator = audioContext.createOscillator(); - oscillator.type = 'sine'; - oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4音 - - const gainNode = audioContext.createGain(); - gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // 设置音量为0.1 - - oscillator.connect(gainNode); - gainNode.connect(audioContext.destination); - - oscillator.start(); - oscillator.stop(audioContext.currentTime + 0.2); // 播放0.2秒 - - log('播放提示音作为音频播放失败的反馈', 'info'); + // 播放已缓冲的音频 + function playBufferedAudio() { + if (isAudioPlaying || audioBufferQueue.length === 0) return; + + isAudioPlaying = true; + isAudioBuffering = false; + + // 确保Opus解码器已初始化 + const initDecoderAndPlay = async () => { + try { + // 确保音频上下文存在 + if (!audioContext) { + audioContext = new (window.AudioContext || window.webkitAudioContext)({ + sampleRate: SAMPLE_RATE + }); + log('创建音频上下文,采样率: ' + SAMPLE_RATE + 'Hz', 'debug'); + } + + // 确保解码器已初始化 + if (!opusDecoder) { + log('初始化Opus解码器...', 'info'); + try { + opusDecoder = await initOpusDecoder(); + if (!opusDecoder) { + throw new Error('解码器初始化失败'); + } + log('Opus解码器初始化成功', 'success'); + } catch (error) { + log('Opus解码器初始化失败: ' + error.message, 'error'); + isAudioPlaying = false; + return; + } + } + + // 创建流式播放上下文 + if (!streamingContext) { + streamingContext = { + queue: [], // 已解码的PCM队列 + playing: false, // 是否正在播放 + endOfStream: false, // 是否收到结束信号 + source: null, // 当前音频源 + totalSamples: 0, // 累积的总样本数 + lastPlayTime: 0, // 上次播放的时间戳 + + // 将Opus数据解码为PCM + decodeOpusFrames: async function(opusFrames) { + if (!opusDecoder) { + log('Opus解码器未初始化,无法解码', 'error'); + return; + } + + let decodedSamples = []; + + for (const frame of opusFrames) { + try { + // 使用Opus解码器解码 + const frameData = opusDecoder.decode(frame); + if (frameData && frameData.length > 0) { + // 转换为Float32 + const floatData = convertInt16ToFloat32(frameData); + decodedSamples.push(...floatData); + } + } catch (error) { + log("Opus解码失败: " + error.message, 'error'); + } + } + + if (decodedSamples.length > 0) { + // 添加到解码队列 + this.queue.push(...decodedSamples); + this.totalSamples += decodedSamples.length; + + // 如果累积了至少0.2秒的音频,开始播放 + const minSamples = SAMPLE_RATE * MIN_AUDIO_DURATION; + if (!this.playing && this.queue.length >= minSamples) { + this.startPlaying(); + } + } else { + log('没有成功解码的样本', 'warning'); + } + }, + + // 开始播放音频 + startPlaying: function() { + if (this.playing || this.queue.length === 0) return; + + this.playing = true; + + // 创建新的音频缓冲区 + const minPlaySamples = Math.min(this.queue.length, SAMPLE_RATE); // 最多播放1秒 + const currentSamples = this.queue.splice(0, minPlaySamples); + + const audioBuffer = audioContext.createBuffer(CHANNELS, currentSamples.length, SAMPLE_RATE); + audioBuffer.copyToChannel(new Float32Array(currentSamples), 0); + + // 创建音频源 + this.source = audioContext.createBufferSource(); + this.source.buffer = audioBuffer; + + // 创建增益节点用于平滑过渡 + const gainNode = audioContext.createGain(); + + // 应用淡入淡出效果避免爆音 + const fadeDuration = 0.02; // 20毫秒 + gainNode.gain.setValueAtTime(0, audioContext.currentTime); + gainNode.gain.linearRampToValueAtTime(1, audioContext.currentTime + fadeDuration); + + const duration = audioBuffer.duration; + if (duration > fadeDuration * 2) { + gainNode.gain.setValueAtTime(1, audioContext.currentTime + duration - fadeDuration); + gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + duration); + } + + // 连接节点并开始播放 + this.source.connect(gainNode); + gainNode.connect(audioContext.destination); + + this.lastPlayTime = audioContext.currentTime; + log(`开始播放 ${currentSamples.length} 个样本,约 ${(currentSamples.length / SAMPLE_RATE).toFixed(2)} 秒`, 'info'); + + // 播放结束后的处理 + this.source.onended = () => { + this.source = null; + this.playing = false; + + // 如果队列中还有数据或者缓冲区有新数据,继续播放 + if (this.queue.length > 0) { + setTimeout(() => this.startPlaying(), 10); + } else if (audioBufferQueue.length > 0) { + // 缓冲区有新数据,进行解码 + const frames = [...audioBufferQueue]; + audioBufferQueue = []; + this.decodeOpusFrames(frames); + } else if (this.endOfStream) { + // 流已结束且没有更多数据 + log("音频播放完成", 'info'); + isAudioPlaying = false; + streamingContext = null; + } else { + // 等待更多数据 + setTimeout(() => { + // 如果仍然没有新数据,但有更多的包到达 + if (this.queue.length === 0 && audioBufferQueue.length > 0) { + const frames = [...audioBufferQueue]; + audioBufferQueue = []; + this.decodeOpusFrames(frames); + } else if (this.queue.length === 0 && audioBufferQueue.length === 0) { + // 真的没有更多数据了 + log("音频播放完成 (超时)", 'info'); + isAudioPlaying = false; + streamingContext = null; + } + }, 500); // 500ms超时 + } + }; + + this.source.start(); + } + }; + } + + // 开始处理缓冲的数据 + const frames = [...audioBufferQueue]; + audioBufferQueue = []; // 清空缓冲队列 + + // 解码并播放 + await streamingContext.decodeOpusFrames(frames); + + } catch (error) { + log(`播放已缓冲的音频出错: ${error.message}`, 'error'); + isAudioPlaying = false; + streamingContext = null; } + }; + + // 执行初始化和播放 + initDecoderAndPlay(); + } + + // 将Int16音频数据转换为Float32音频数据 + function convertInt16ToFloat32(int16Data) { + const float32Data = new Float32Array(int16Data.length); + for (let i = 0; i < int16Data.length; i++) { + // 将[-32768,32767]范围转换为[-1,1] + float32Data[i] = int16Data[i] / (int16Data[i] < 0 ? 0x8000 : 0x7FFF); + } + return float32Data; + } + + // 初始化Opus解码器 - 确保完全初始化完成后才返回 + async function initOpusDecoder() { + if (opusDecoder) return opusDecoder; // 已经初始化 + + try { + // 检查ModuleInstance是否存在 + if (typeof window.ModuleInstance === 'undefined') { + if (typeof Module !== 'undefined') { + // 使用全局Module作为ModuleInstance + window.ModuleInstance = Module; + log('使用全局Module作为ModuleInstance', 'info'); + } else { + throw new Error('Opus库未加载,ModuleInstance和Module对象都不存在'); + } + } + + const mod = window.ModuleInstance; + + // 创建解码器对象 + opusDecoder = { + channels: CHANNELS, + rate: SAMPLE_RATE, + frameSize: FRAME_SIZE, + module: mod, + decoderPtr: null, // 初始为null + + // 初始化解码器 + init: function() { + if (this.decoderPtr) return true; // 已经初始化 + + // 获取解码器大小 + const decoderSize = mod._opus_decoder_get_size(this.channels); + log(`Opus解码器大小: ${decoderSize}字节`, 'debug'); + + // 分配内存 + this.decoderPtr = mod._malloc(decoderSize); + if (!this.decoderPtr) { + throw new Error("无法分配解码器内存"); + } + + // 初始化解码器 + const err = mod._opus_decoder_init( + this.decoderPtr, + this.rate, + this.channels + ); + + if (err < 0) { + this.destroy(); // 清理资源 + throw new Error(`Opus解码器初始化失败: ${err}`); + } + + log("Opus解码器初始化成功", 'success'); + return true; + }, + + // 解码方法 + decode: function(opusData) { + if (!this.decoderPtr) { + if (!this.init()) { + throw new Error("解码器未初始化且无法初始化"); + } + } + + try { + const mod = this.module; + + // 为Opus数据分配内存 + const opusPtr = mod._malloc(opusData.length); + mod.HEAPU8.set(opusData, opusPtr); + + // 为PCM输出分配内存 + const pcmPtr = mod._malloc(this.frameSize * 2); // Int16 = 2字节 + + // 解码 + const decodedSamples = mod._opus_decode( + this.decoderPtr, + opusPtr, + opusData.length, + pcmPtr, + this.frameSize, + 0 // 不使用FEC + ); + + if (decodedSamples < 0) { + mod._free(opusPtr); + mod._free(pcmPtr); + throw new Error(`Opus解码失败: ${decodedSamples}`); + } + + // 复制解码后的数据 + const decodedData = new Int16Array(decodedSamples); + for (let i = 0; i < decodedSamples; i++) { + decodedData[i] = mod.HEAP16[(pcmPtr >> 1) + i]; + } + + // 释放内存 + mod._free(opusPtr); + mod._free(pcmPtr); + + return decodedData; + } catch (error) { + log(`Opus解码错误: ${error.message}`, 'error'); + return new Int16Array(0); + } + }, + + // 销毁方法 + destroy: function() { + if (this.decoderPtr) { + this.module._free(this.decoderPtr); + this.decoderPtr = null; + } + } + }; + + // 初始化解码器 + if (!opusDecoder.init()) { + throw new Error("Opus解码器初始化失败"); + } + + return opusDecoder; + } catch (error) { - log(`简单播放回退方案也失败: ${error.message}`, 'error'); + log(`Opus解码器初始化失败: ${error.message}`, 'error'); + opusDecoder = null; // 重置为null,以便下次重试 + throw error; } } @@ -1481,6 +1630,14 @@ // 初始化Opus编码器 initOpusEncoder(); + + // 预加载Opus解码器 + log('预加载Opus解码器...', 'info'); + initOpusDecoder().then(() => { + log('Opus解码器预加载成功', 'success'); + }).catch(error => { + log(`Opus解码器预加载失败: ${error.message},将在需要时重试`, 'warning'); + }); } // PCM录音处理器代码 - 会被注入到AudioWorklet中 @@ -1647,7 +1804,6 @@ let audioProcessor = null; let audioProcessorType = null; let audioSource = null; - let pcmBuffers = []; // 处理PCM缓冲数据 let pcmDataBuffer = new Int16Array(); @@ -1895,7 +2051,6 @@ } } - // 处理二进制消息 async function handleBinaryMessage(data) { try { let arrayBuffer; @@ -1917,10 +2072,25 @@ const opusData = new Uint8Array(arrayBuffer); if (opusData.length > 0) { - // 播放Opus音频 - playOpusData([opusData]); + // 将数据添加到缓冲队列 + audioBufferQueue.push(opusData); + + // 如果收到的是第一个音频包,开始缓冲过程 + if (audioBufferQueue.length === 1 && !isAudioBuffering && !isAudioPlaying) { + startAudioBuffering(); + } } else { - log('收到空音频数据帧', 'warning'); + log('收到空音频数据帧,可能是结束标志', 'warning'); + + // 如果缓冲队列中有数据且没有在播放,立即开始播放 + if (audioBufferQueue.length > 0 && !isAudioPlaying) { + playBufferedAudio(); + } + + // 如果正在播放,发送结束信号 + if (isAudioPlaying && streamingContext) { + streamingContext.endOfStream = true; + } } } catch (error) { log(`处理二进制消息出错: ${error.message}`, 'error');