mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
新增ota管理与固件上传于下载
This commit is contained in:
parent
c74dbf03cd
commit
65a66774a8
120 changed files with 3324 additions and 2143 deletions
302
README_en.md
Normal file
302
README_en.md
Normal file
|
|
@ -0,0 +1,302 @@
|
||||||
|
[](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
||||||
|
|
||||||
|
<center>
|
||||||
|
<h1>Xiaozhi Backend Server xiaozhi-esp32-server</h1>
|
||||||
|
</center>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
This project provides backend services for the open-source smart hardware project
|
||||||
|
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||||
|
Implemented in Python according to the <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi Communication Protocol</a><br/>
|
||||||
|
Helping you quickly set up your Xiaozhi server
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="./README.md">简体中文</a>
|
||||||
|
· English
|
||||||
|
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Changelog</a>
|
||||||
|
· <a href="./docs/Deployment.md">Deployment Guide</a>
|
||||||
|
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Report Issues</a>
|
||||||
|
</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors">
|
||||||
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/contributors/xinnan-tech/xiaozhi-esp32-server?logo=github" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">
|
||||||
|
<img alt="Issues" src="https://img.shields.io/github/issues/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/pulls">
|
||||||
|
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/pulls">
|
||||||
|
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
|
||||||
|
<img alt="GitHub pull requests" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Target Users 👥
|
||||||
|
|
||||||
|
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 these videos 🎥
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Xiaozhi esp32 connecting to your own backend model" src="docs/images/demo1.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Custom voice" src="docs/images/demo2.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Communicating in Cantonese" src="docs/images/demo3.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Control home appliances" src="docs/images/demo5.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1kgA2eYEQ9" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Lowest cost configuration" src="docs/images/demo4.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1Vy96YCE3R" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Custom voice" src="docs/images/demo6.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Play music" src="docs/images/demo7.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1Z8XuYZEAS" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Weather plugin" src="docs/images/demo8.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV178XuYfEpi" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="IOT command control device" src="docs/images/demo9.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV17LXWYvENb" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="News broadcast" src="docs/images/demo0.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System Requirements and Prerequisites 🖥️
|
||||||
|
|
||||||
|
- **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 ⚠️
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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:
|
||||||
|
auth:
|
||||||
|
# Enable protection
|
||||||
|
enabled: true
|
||||||
|
```
|
||||||
|
|
||||||
|
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 `xiaozhi-esp32` protocol, implementing data interaction through WebSocket.
|
||||||
|
- **Dialogue Interaction**
|
||||||
|
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**
|
||||||
|
Supports flexible switching of LLM modules, default using ChatGLMLLM, can also use Alibaba Bailian, DeepSeek, Ollama, and other interfaces.
|
||||||
|
- **TTS Module**
|
||||||
|
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.
|
||||||
|
|
||||||
|
### Under Development 🚧
|
||||||
|
|
||||||
|
- Multiple mood modes
|
||||||
|
- Smart control panel webui
|
||||||
|
|
||||||
|
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 List 📋
|
||||||
|
|
||||||
|
### LLM Language Models
|
||||||
|
|
||||||
|
| 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 supporting openai interface calls can be integrated.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### TTS Speech Synthesis
|
||||||
|
|
||||||
|
| 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 Voice Activity Detection
|
||||||
|
|
||||||
|
| Type | Platform Name | Usage Method | Pricing Model | Notes |
|
||||||
|
|:---:|:---------:|:----:|:----:|:--:|
|
||||||
|
| VAD | SileroVAD | Local Use | Free | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ASR Speech Recognition
|
||||||
|
|
||||||
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Local Use | FunASR, SherpaASR | FunASR, SherpaASR |
|
||||||
|
| Interface Call | DoubaoASR | - |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Memory Storage
|
||||||
|
|
||||||
|
| Type | Platform Name | Usage Method | Pricing Model | Notes |
|
||||||
|
|:------:|:---------------:|:----:|:---------:|:--:|
|
||||||
|
| Memory | mem0ai | Interface Call | 1000 times/month quota | |
|
||||||
|
| Memory | mem_local_short | Local Summary | Free | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Intent Recognition
|
||||||
|
|
||||||
|
| 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 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Acknowledgments 🙏
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
|
||||||
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||||
|
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
BIN
docs/images/deploy.png
Normal file
BIN
docs/images/deploy.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 576 KiB |
5
main/.vscode/extensions.json
vendored
Normal file
5
main/.vscode/extensions.json
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"github.copilot-chat"
|
||||||
|
]
|
||||||
|
}
|
||||||
3
main/.vscode/settings.json
vendored
Normal file
3
main/.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
{
|
||||||
|
"java.compile.nullAnalysis.mode": "automatic"
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
|
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](./FAQ.md#%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F-)
|
||||||
|
|
||||||
# 项目目录介绍
|
# 项目目录介绍
|
||||||
|
当你看到这份文件的时候,这个这个项目还没完善好。我们还有很多东西要做。
|
||||||
|
|
||||||
如果你是一名软件开发者,这里有一份[《致开发者的公开信》](../docs/contributor_open_letter.md),欢迎归队!
|
如果你是一名软件开发者,这里有一份[《致开发者的公开信》](../docs/contributor_open_letter.md),欢迎归队!
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
@ -10,9 +12,9 @@ xiaozhi-esp32-server
|
||||||
├─ manager-api 8002 端口 Java语言开发 负责提供控制台的api
|
├─ manager-api 8002 端口 Java语言开发 负责提供控制台的api
|
||||||
```
|
```
|
||||||
|
|
||||||
# xiaozhi-server 和ESP32通讯协议
|
# xiaozhi-server 接口协议
|
||||||
|
|
||||||
https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh
|
[虾哥团队通信协议:Websocket 连接](https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh)
|
||||||
|
|
||||||
# manager-web 、manager-api接口协议
|
# manager-web 、manager-api接口协议
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3)
|
本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../../docs/Deployment.md)
|
||||||
|
|
||||||
# 项目介绍
|
# 项目介绍
|
||||||
|
|
||||||
manager-api 该项目基于SpringBoot框架开发。
|
manager-api 该项目基于SpringBoot框架开发。
|
||||||
|
|
@ -13,6 +12,80 @@ MySQL 8.0+
|
||||||
Redis 5.0+
|
Redis 5.0+
|
||||||
Vue 3.x
|
Vue 3.x
|
||||||
|
|
||||||
|
# 创建数据库
|
||||||
|
|
||||||
|
如果本机已经安装了MySQL,可以直接在数据库中创建名为`xiaozhi_esp32_server`的数据库。
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE DATABASE xiaozhi_esp32_server CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
```
|
||||||
|
|
||||||
|
如果还没有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
|
||||||
|
```
|
||||||
|
|
||||||
|
# 确认项目数据库连接信息
|
||||||
|
|
||||||
|
在`src/main/resources/application-dev.yml`中配置数据库连接信息
|
||||||
|
|
||||||
|
```
|
||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
username: root
|
||||||
|
password: 123456
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
# 连接Redis
|
||||||
|
|
||||||
|
如果还没有Redis,你可以通过docker安装redis
|
||||||
|
|
||||||
|
```
|
||||||
|
docker run --name xiaozhi-esp32-server-redis -d -p 6379:6379 redis
|
||||||
|
```
|
||||||
|
|
||||||
|
# 确认项目Redis连接信息
|
||||||
|
|
||||||
|
在`src/main/resources/application-dev.yml`中配置Redis连接信息
|
||||||
|
|
||||||
|
```
|
||||||
|
spring:
|
||||||
|
data:
|
||||||
|
redis:
|
||||||
|
host: localhost
|
||||||
|
port: 6379
|
||||||
|
password:
|
||||||
|
database: 0
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
# 测试启动
|
||||||
|
|
||||||
|
本项目为SpringBoot项目,启动方式为:
|
||||||
|
打开`Application.java`运行`Main`方法启动
|
||||||
|
|
||||||
|
```
|
||||||
|
路径地址:
|
||||||
|
src/main/java/xiaozhi/AdminApplication.java
|
||||||
|
```
|
||||||
|
|
||||||
|
# 打包编译
|
||||||
|
|
||||||
|
执行以下命令生产jar包
|
||||||
|
|
||||||
|
```
|
||||||
|
mvn clean install
|
||||||
|
```
|
||||||
|
|
||||||
|
把jar包放在服务器上,执行
|
||||||
|
|
||||||
|
```
|
||||||
|
nohup java -jar xiaozhi-esp32-api.jar --spring.profiles.activate=dev
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
# 接口文档
|
# 接口文档
|
||||||
启动后打开:http://localhost:8002/xiaozhi/doc.html
|
启动后打开:http://localhost:8002/xiaozhi/doc.html
|
||||||
|
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -195,6 +195,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>1.18.30</version>
|
||||||
<optional>true</optional>
|
<optional>true</optional>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
@ -232,10 +233,8 @@
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-clean-plugin</artifactId>
|
||||||
<configuration>
|
<version>3.2.0</version>
|
||||||
<skipTests>true</skipTests>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
|
||||||
|
|
@ -71,14 +71,6 @@ public class SwaggerConfig {
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
|
||||||
public GroupedOpenApi configApi() {
|
|
||||||
return GroupedOpenApi.builder()
|
|
||||||
.group("config")
|
|
||||||
.pathsToMatch("/config/**")
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public OpenAPI customOpenAPI() {
|
public OpenAPI customOpenAPI() {
|
||||||
return new OpenAPI().info(new Info()
|
return new OpenAPI().info(new Info()
|
||||||
|
|
|
||||||
|
|
@ -84,16 +84,6 @@ public interface Constant {
|
||||||
*/
|
*/
|
||||||
String SERVER_SECRET = "server.secret";
|
String SERVER_SECRET = "server.secret";
|
||||||
|
|
||||||
/**
|
|
||||||
* 是否允许用户注册
|
|
||||||
*/
|
|
||||||
String SERVER_ALLOW_USER_REGISTER = "server.allow_user_register";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 下发六位验证码时显示的控制面板地址
|
|
||||||
*/
|
|
||||||
String SERVER_FRONTED_URL = "server.fronted_url";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 路径分割符
|
* 路径分割符
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -51,8 +51,4 @@ public interface ErrorCode {
|
||||||
int PARAM_NUMBER_INVALID = 10037;
|
int PARAM_NUMBER_INVALID = 10037;
|
||||||
int PARAM_BOOLEAN_INVALID = 10038;
|
int PARAM_BOOLEAN_INVALID = 10038;
|
||||||
int PARAM_ARRAY_INVALID = 10039;
|
int PARAM_ARRAY_INVALID = 10039;
|
||||||
int PARAM_JSON_INVALID = 10040;
|
|
||||||
|
|
||||||
int OTA_DEVICE_NOT_FOUND = 10041;
|
|
||||||
int OTA_DEVICE_NEED_BIND = 10042;
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -38,14 +38,7 @@ public class RedisKeys {
|
||||||
* 模型名称的Key
|
* 模型名称的Key
|
||||||
*/
|
*/
|
||||||
public static String getModelNameById(String id) {
|
public static String getModelNameById(String id) {
|
||||||
return "model:name:" + id;
|
return "sys:model:name:" + id;
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 模型配置的Key
|
|
||||||
*/
|
|
||||||
public static String getModelConfigById(String id) {
|
|
||||||
return "model:data:" + id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -61,18 +54,4 @@ public class RedisKeys {
|
||||||
public static String getAgentDeviceCountById(String id) {
|
public static String getAgentDeviceCountById(String id) {
|
||||||
return "agent:device:count:" + id;
|
return "agent:device:count:" + id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取系统配置缓存key
|
|
||||||
*/
|
|
||||||
public static String getServerConfigKey() {
|
|
||||||
return "server:config";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取音色详情缓存key
|
|
||||||
*/
|
|
||||||
public static String getTimbreDetailsKey(String id) {
|
|
||||||
return "timbre:details:" + id;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
package xiaozhi.common.utils;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询参数
|
||||||
|
*/
|
||||||
|
public class Query<T> {
|
||||||
|
|
||||||
|
public IPage<T> getPage(Map<String, Object> params) {
|
||||||
|
return getPage(params, null, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
|
||||||
|
// 分页参数
|
||||||
|
long curPage = 1;
|
||||||
|
long limit = 10;
|
||||||
|
|
||||||
|
if (params.get("page") != null) {
|
||||||
|
curPage = Long.parseLong((String) params.get("page"));
|
||||||
|
}
|
||||||
|
if (params.get("limit") != null) {
|
||||||
|
limit = Long.parseLong((String) params.get("limit"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页对象
|
||||||
|
Page<T> page = new Page<>(curPage, limit);
|
||||||
|
|
||||||
|
// 排序字段
|
||||||
|
String orderField = (String) params.get("orderField");
|
||||||
|
String order = (String) params.get("order");
|
||||||
|
|
||||||
|
// 前端字段排序
|
||||||
|
if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)) {
|
||||||
|
if ("asc".equalsIgnoreCase(order)) {
|
||||||
|
return page.addOrder(OrderItem.asc(orderField));
|
||||||
|
} else {
|
||||||
|
return page.addOrder(OrderItem.desc(orderField));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认排序
|
||||||
|
if (isAsc) {
|
||||||
|
page.addOrder(OrderItem.asc(defaultOrderField));
|
||||||
|
} else {
|
||||||
|
page.addOrder(OrderItem.desc(defaultOrderField));
|
||||||
|
}
|
||||||
|
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -191,5 +191,4 @@ public class AgentController {
|
||||||
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
|
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
|
||||||
return new Result<List<AgentTemplateEntity>>().ok(list);
|
return new Result<List<AgentTemplateEntity>>().ok(list);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
@ -17,12 +17,4 @@ public interface AgentTemplateService extends IService<AgentTemplateEntity> {
|
||||||
* @return 默认模板实体
|
* @return 默认模板实体
|
||||||
*/
|
*/
|
||||||
AgentTemplateEntity getDefaultTemplate();
|
AgentTemplateEntity getDefaultTemplate();
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新默认模板中的模型ID
|
|
||||||
*
|
|
||||||
* @param modelType 模型类型
|
|
||||||
* @param modelId 模型ID
|
|
||||||
*/
|
|
||||||
void updateDefaultTemplateModelId(String modelType, String modelId);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,7 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
|
||||||
@Override
|
@Override
|
||||||
public PageData<AgentEntity> adminAgentList(Map<String, Object> params) {
|
public PageData<AgentEntity> adminAgentList(Map<String, Object> params) {
|
||||||
IPage<AgentEntity> page = agentDao.selectPage(
|
IPage<AgentEntity> page = agentDao.selectPage(
|
||||||
getPage(params, "agent_name", true),
|
getPage(params, "sort", true),
|
||||||
new QueryWrapper<>());
|
new QueryWrapper<>());
|
||||||
return new PageData<>(page.getRecords(), page.getTotal());
|
return new PageData<>(page.getRecords(), page.getTotal());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ package xiaozhi.modules.agent.service.impl;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
|
||||||
import xiaozhi.modules.agent.dao.AgentTemplateDao;
|
import xiaozhi.modules.agent.dao.AgentTemplateDao;
|
||||||
|
|
@ -30,40 +29,4 @@ public class AgentTemplateServiceImpl extends ServiceImpl<AgentTemplateDao, Agen
|
||||||
.last("LIMIT 1");
|
.last("LIMIT 1");
|
||||||
return this.getOne(wrapper);
|
return this.getOne(wrapper);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新默认模板中的模型ID
|
|
||||||
*
|
|
||||||
* @param modelType 模型类型
|
|
||||||
* @param modelId 模型ID
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void updateDefaultTemplateModelId(String modelType, String modelId) {
|
|
||||||
modelType = modelType.toUpperCase();
|
|
||||||
|
|
||||||
UpdateWrapper<AgentTemplateEntity> wrapper = new UpdateWrapper<>();
|
|
||||||
switch (modelType) {
|
|
||||||
case "ASR":
|
|
||||||
wrapper.set("asr_model_id", modelId);
|
|
||||||
break;
|
|
||||||
case "VAD":
|
|
||||||
wrapper.set("vad_model_id", modelId);
|
|
||||||
break;
|
|
||||||
case "LLM":
|
|
||||||
wrapper.set("llm_model_id", modelId);
|
|
||||||
break;
|
|
||||||
case "TTS":
|
|
||||||
wrapper.set("tts_model_id", modelId);
|
|
||||||
wrapper.set("tts_voice_id", null);
|
|
||||||
break;
|
|
||||||
case "MEMORY":
|
|
||||||
wrapper.set("mem_model_id", modelId);
|
|
||||||
break;
|
|
||||||
case "INTENT":
|
|
||||||
wrapper.set("intent_model_id", modelId);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
wrapper.ge("sort", 0);
|
|
||||||
update(wrapper);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,23 @@
|
||||||
package xiaozhi.modules.device.controller;
|
package xiaozhi.modules.device.controller;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
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.RestController;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
@ -21,44 +28,224 @@ import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.SneakyThrows;
|
import lombok.SneakyThrows;
|
||||||
|
import xiaozhi.common.page.PageData;
|
||||||
|
import xiaozhi.common.utils.Result;
|
||||||
import xiaozhi.modules.device.dto.DeviceReportReqDTO;
|
import xiaozhi.modules.device.dto.DeviceReportReqDTO;
|
||||||
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
|
import xiaozhi.modules.device.dto.DeviceReportRespDTO;
|
||||||
|
import xiaozhi.modules.device.entity.OtaEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
|
import xiaozhi.modules.device.service.OtaService;
|
||||||
import xiaozhi.modules.device.utils.NetworkUtil;
|
import xiaozhi.modules.device.utils.NetworkUtil;
|
||||||
|
import xiaozhi.common.constant.Constant;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameters;
|
||||||
|
import xiaozhi.common.validator.ValidatorUtils;
|
||||||
|
|
||||||
@Tag(name = "设备管理", description = "OTA 相关接口")
|
@Tag(name = "固件管理", description = "OTA固件管理接口")
|
||||||
@RestController
|
@RestController
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@RequestMapping("/ota/")
|
@RequestMapping("/ota")
|
||||||
public class OTAController {
|
public class OTAController {
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(OTAController.class);
|
||||||
private final DeviceService deviceService;
|
private final DeviceService deviceService;
|
||||||
|
private final OtaService otaService;
|
||||||
|
|
||||||
|
@GetMapping("/otas")
|
||||||
|
@Operation(summary = "分页查询 OTA 固件信息")
|
||||||
|
@Parameters({
|
||||||
|
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
|
||||||
|
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true)
|
||||||
|
})
|
||||||
|
public Result<PageData<OtaEntity>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
|
||||||
|
ValidatorUtils.validateEntity(params);
|
||||||
|
PageData<OtaEntity> page = otaService.page(params);
|
||||||
|
return new Result<PageData<OtaEntity>>().ok(page);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("{id}")
|
||||||
|
@Operation(summary = "信息 OTA 固件信息")
|
||||||
|
public Result<OtaEntity> get(@PathVariable("id") String id) {
|
||||||
|
OtaEntity data = otaService.getById(id);
|
||||||
|
return new Result<OtaEntity>().ok(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@Operation(summary = "保存 OTA 固件信息")
|
||||||
|
public Result<Void> save(@RequestBody OtaEntity entity) {
|
||||||
|
if (entity == null) {
|
||||||
|
return new Result<Void>().error("固件信息不能为空");
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(entity.getFirmwareName())) {
|
||||||
|
return new Result<Void>().error("固件名称不能为空");
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(entity.getType())) {
|
||||||
|
return new Result<Void>().error("固件类型不能为空");
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(entity.getVersion())) {
|
||||||
|
return new Result<Void>().error("版本号不能为空");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
otaService.save(entity);
|
||||||
|
return new Result<Void>();
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
return new Result<Void>().error(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
@Operation(summary = "修改 OTA 固件信息")
|
||||||
|
public Result<?> update(@PathVariable("id") String id, @RequestBody OtaEntity entity) {
|
||||||
|
if (entity == null) {
|
||||||
|
return new Result<>().error("固件信息不能为空");
|
||||||
|
}
|
||||||
|
entity.setId(id);
|
||||||
|
try {
|
||||||
|
otaService.update(entity);
|
||||||
|
return new Result<>();
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
return new Result<>().error(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
@Operation(summary = "OTA 删除")
|
||||||
|
public Result<Void> delete(@PathVariable("id") String[] ids) {
|
||||||
|
if (ids == null || ids.length == 0) {
|
||||||
|
return new Result<Void>().error("删除的固件ID不能为空");
|
||||||
|
}
|
||||||
|
otaService.delete(ids);
|
||||||
|
return new Result<Void>();
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "检查 OTA 版本和设备激活状态")
|
@Operation(summary = "检查 OTA 版本和设备激活状态")
|
||||||
@PostMapping
|
@PostMapping("check")
|
||||||
public ResponseEntity<String> checkOTAVersion(
|
public ResponseEntity<String> checkOTAVersion(
|
||||||
@RequestBody DeviceReportReqDTO deviceReportReqDTO,
|
@RequestBody DeviceReportReqDTO deviceReportReqDTO,
|
||||||
@Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId,
|
@Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Device-Id") String deviceId,
|
||||||
@Parameter(name = "Client-Id", description = "客户端标识", required = false, in = ParameterIn.HEADER) @RequestHeader(value = "Client-Id", required = false) String clientId) {
|
@Parameter(name = "Client-Id", description = "客户端标识", required = true, in = ParameterIn.HEADER) @RequestHeader("Client-Id") String clientId) {
|
||||||
if (StringUtils.isBlank(deviceId)) {
|
if (StringUtils.isAnyBlank(deviceId, clientId)) {
|
||||||
return createResponse(DeviceReportRespDTO.createError("Device ID is required"));
|
return createResponse(DeviceReportRespDTO.createError("Device ID is required"));
|
||||||
}
|
}
|
||||||
if (StringUtils.isBlank(clientId)) {
|
|
||||||
clientId = deviceId;
|
|
||||||
}
|
|
||||||
String macAddress = deviceReportReqDTO.getMacAddress();
|
String macAddress = deviceReportReqDTO.getMacAddress();
|
||||||
boolean macAddressValid = NetworkUtil.isMacAddressValid(macAddress);
|
boolean macAddressValid = NetworkUtil.isMacAddressValid(macAddress);
|
||||||
// 设备Id和Mac地址应是一致的, 并且必须需要application字段
|
// 设备Id和Mac地址应是一致的, 并且必须需要application字段
|
||||||
if (!deviceId.equals(macAddress) || !macAddressValid || deviceReportReqDTO.getApplication() == null) {
|
if (!deviceId.equals(macAddress) || !macAddressValid || deviceReportReqDTO.getApplication() == null) {
|
||||||
return createResponse(DeviceReportRespDTO.createError("Invalid OTA request"));
|
return createResponse(DeviceReportRespDTO.createError("Invalid OTA request"));
|
||||||
}
|
}
|
||||||
return createResponse(deviceService.checkDeviceActive(macAddress, clientId, deviceReportReqDTO));
|
return createResponse(deviceService.checkDeviceActive(macAddress, deviceId, clientId, deviceReportReqDTO));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@Operation(summary = "获取 OTA 提示信息")
|
||||||
|
@GetMapping("prompt")
|
||||||
public ResponseEntity<String> getOTAPrompt() {
|
public ResponseEntity<String> getOTAPrompt() {
|
||||||
return createResponse(DeviceReportRespDTO.createError("请提交正确的ota参数"));
|
return createResponse(DeviceReportRespDTO.createError("请提交正确的ota参数"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/download/{id}")
|
||||||
|
@Operation(summary = "下载固件文件")
|
||||||
|
public ResponseEntity<byte[]> downloadFirmware(@PathVariable("id") String id) {
|
||||||
|
try {
|
||||||
|
// 获取固件信息
|
||||||
|
OtaEntity otaEntity = otaService.getById(id);
|
||||||
|
if (otaEntity == null || StringUtils.isBlank(otaEntity.getFirmwarePath())) {
|
||||||
|
logger.warn("Firmware not found or path is empty for ID: {}", id);
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取文件路径 - 确保路径是绝对路径或正确的相对路径
|
||||||
|
String firmwarePath = otaEntity.getFirmwarePath();
|
||||||
|
Path path;
|
||||||
|
|
||||||
|
// 检查是否是绝对路径
|
||||||
|
if (Paths.get(firmwarePath).isAbsolute()) {
|
||||||
|
path = Paths.get(firmwarePath);
|
||||||
|
} else {
|
||||||
|
// 如果是相对路径,则从当前工作目录解析
|
||||||
|
path = Paths.get(System.getProperty("user.dir"), firmwarePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("Attempting to download firmware for ID: {}, DB path: {}, resolved path: {}",
|
||||||
|
id, firmwarePath, path.toAbsolutePath());
|
||||||
|
|
||||||
|
if (!Files.exists(path) || !Files.isRegularFile(path)) {
|
||||||
|
// 尝试直接从firmware目录下查找文件名
|
||||||
|
String fileName = new File(firmwarePath).getName();
|
||||||
|
Path altPath = Paths.get(System.getProperty("user.dir"), "firmware", fileName);
|
||||||
|
|
||||||
|
logger.info("File not found at primary path, trying alternative path: {}", altPath.toAbsolutePath());
|
||||||
|
|
||||||
|
if (Files.exists(altPath) && Files.isRegularFile(altPath)) {
|
||||||
|
path = altPath;
|
||||||
|
} else {
|
||||||
|
logger.error("Firmware file not found at either path: {} or {}",
|
||||||
|
path.toAbsolutePath(), altPath.toAbsolutePath());
|
||||||
|
return ResponseEntity.notFound().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取文件内容
|
||||||
|
byte[] fileContent = Files.readAllBytes(path);
|
||||||
|
|
||||||
|
// 设置响应头
|
||||||
|
String originalFilename = otaEntity.getFirmwareName() + "_" + otaEntity.getVersion();
|
||||||
|
if (firmwarePath.contains(".")) {
|
||||||
|
String extension = firmwarePath.substring(firmwarePath.lastIndexOf("."));
|
||||||
|
originalFilename += extension;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理文件名,移除不安全字符
|
||||||
|
String safeFilename = originalFilename.replaceAll("[^a-zA-Z0-9._-]", "_");
|
||||||
|
|
||||||
|
logger.info("Providing download for firmware ID: {}, filename: {}, size: {} bytes",
|
||||||
|
id, safeFilename, fileContent.length);
|
||||||
|
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + safeFilename + "\"")
|
||||||
|
.body(fileContent);
|
||||||
|
} catch (IOException e) {
|
||||||
|
logger.error("Error reading firmware file for ID: {}", id, e);
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Unexpected error during firmware download for ID: {}", id, e);
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/upload")
|
||||||
|
@Operation(summary = "上传固件文件")
|
||||||
|
public Result<String> uploadFirmware(@RequestParam("file") MultipartFile file) {
|
||||||
|
if (file.isEmpty()) {
|
||||||
|
return new Result<String>().error("上传文件不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 获取文件名
|
||||||
|
String originalFilename = file.getOriginalFilename();
|
||||||
|
// 生成唯一的文件名
|
||||||
|
String uniqueFileName = UUID.randomUUID().toString() + "_" + originalFilename;
|
||||||
|
// 设置存储路径
|
||||||
|
String uploadDir = "firmware";
|
||||||
|
Path uploadPath = Paths.get(uploadDir);
|
||||||
|
System.out.println(uploadPath);
|
||||||
|
|
||||||
|
// 如果目录不存在,创建目录
|
||||||
|
if (!Files.exists(uploadPath)) {
|
||||||
|
Files.createDirectories(uploadPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 完整的文件路径
|
||||||
|
Path filePath = uploadPath.resolve(uniqueFileName);
|
||||||
|
|
||||||
|
// 保存文件
|
||||||
|
Files.copy(file.getInputStream(), filePath);
|
||||||
|
|
||||||
|
// 返回文件路径
|
||||||
|
return new Result<String>().ok(filePath.toString());
|
||||||
|
} catch (IOException e) {
|
||||||
|
return new Result<String>().error("文件上传失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@SneakyThrows
|
@SneakyThrows
|
||||||
private ResponseEntity<String> createResponse(DeviceReportRespDTO deviceReportRespDTO) {
|
private ResponseEntity<String> createResponse(DeviceReportRespDTO deviceReportRespDTO) {
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
package xiaozhi.modules.device.dao;
|
||||||
|
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
|
||||||
|
import xiaozhi.modules.device.entity.OtaEntity;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OTA固件管理
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface OtaDao extends BaseMapper<OtaEntity> {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,61 @@
|
||||||
|
package xiaozhi.modules.device.entity;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@TableName("ai_ota")
|
||||||
|
@Schema(description = "固件信息")
|
||||||
|
public class OtaEntity {
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_UUID)
|
||||||
|
@Schema(description = "ID")
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
@Schema(description = "固件名称")
|
||||||
|
private String firmwareName;
|
||||||
|
|
||||||
|
@Schema(description = "固件类型")
|
||||||
|
private String type;
|
||||||
|
|
||||||
|
@Schema(description = "版本号")
|
||||||
|
private String version;
|
||||||
|
|
||||||
|
@Schema(description = "文件大小(字节)")
|
||||||
|
private Long size;
|
||||||
|
|
||||||
|
@Schema(description = "备注/说明")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
@Schema(description = "固件路径")
|
||||||
|
private String firmwarePath;
|
||||||
|
|
||||||
|
@Schema(description = "排序")
|
||||||
|
private Integer sort;
|
||||||
|
|
||||||
|
@Schema(description = "更新者")
|
||||||
|
@TableField(fill = FieldFill.UPDATE)
|
||||||
|
private Long updater;
|
||||||
|
|
||||||
|
@Schema(description = "更新时间")
|
||||||
|
@TableField(fill = FieldFill.UPDATE)
|
||||||
|
private Date updateDate;
|
||||||
|
|
||||||
|
@Schema(description = "创建者")
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private Long creator;
|
||||||
|
|
||||||
|
@Schema(description = "创建时间")
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private Date createDate;
|
||||||
|
}
|
||||||
|
|
@ -19,7 +19,7 @@ public interface DeviceService {
|
||||||
/**
|
/**
|
||||||
* 检查设备是否激活
|
* 检查设备是否激活
|
||||||
*/
|
*/
|
||||||
DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId,
|
DeviceReportRespDTO checkDeviceActive(String macAddress, String deviceId, String clientId,
|
||||||
DeviceReportReqDTO deviceReport);
|
DeviceReportReqDTO deviceReport);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -66,20 +66,4 @@ public interface DeviceService {
|
||||||
* @return 用户列表分页数据
|
* @return 用户列表分页数据
|
||||||
*/
|
*/
|
||||||
PageData<UserShowDeviceListVO> page(DevicePageUserDTO dto);
|
PageData<UserShowDeviceListVO> page(DevicePageUserDTO dto);
|
||||||
|
|
||||||
/**
|
|
||||||
* 根据MAC地址获取设备信息
|
|
||||||
*
|
|
||||||
* @param macAddress MAC地址
|
|
||||||
* @return 设备信息
|
|
||||||
*/
|
|
||||||
DeviceEntity getDeviceByMacAddress(String macAddress);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 根据设备ID获取激活码
|
|
||||||
*
|
|
||||||
* @param deviceId 设备ID
|
|
||||||
* @return 激活码
|
|
||||||
*/
|
|
||||||
String geCodeByDeviceId(String deviceId);
|
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
package xiaozhi.modules.device.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import xiaozhi.common.page.PageData;
|
||||||
|
import xiaozhi.modules.device.entity.OtaEntity;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OTA固件管理
|
||||||
|
*/
|
||||||
|
public interface OtaService extends IService<OtaEntity> {
|
||||||
|
PageData<OtaEntity> page(Map<String, Object> params);
|
||||||
|
|
||||||
|
boolean save(OtaEntity entity);
|
||||||
|
|
||||||
|
void update(OtaEntity entity);
|
||||||
|
|
||||||
|
void delete(String[] ids);
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,7 @@ import java.util.TimeZone;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.data.redis.core.RedisTemplate;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
|
@ -33,7 +34,6 @@ import xiaozhi.modules.device.entity.DeviceEntity;
|
||||||
import xiaozhi.modules.device.service.DeviceService;
|
import xiaozhi.modules.device.service.DeviceService;
|
||||||
import xiaozhi.modules.device.vo.UserShowDeviceListVO;
|
import xiaozhi.modules.device.vo.UserShowDeviceListVO;
|
||||||
import xiaozhi.modules.security.user.SecurityUser;
|
import xiaozhi.modules.security.user.SecurityUser;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
|
||||||
import xiaozhi.modules.sys.service.SysUserUtilService;
|
import xiaozhi.modules.sys.service.SysUserUtilService;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
|
|
@ -49,11 +49,11 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
|
|
||||||
// 添加构造函数来初始化 deviceMapper
|
// 添加构造函数来初始化 deviceMapper
|
||||||
public DeviceServiceImpl(DeviceDao deviceDao, SysUserUtilService sysUserUtilService,
|
public DeviceServiceImpl(DeviceDao deviceDao, SysUserUtilService sysUserUtilService,
|
||||||
SysParamsService sysParamsService,
|
@Value("${app.fronted-url:http://localhost:8001}") String frontedUrl,
|
||||||
RedisTemplate<String, Object> redisTemplate) {
|
RedisTemplate<String, Object> redisTemplate) {
|
||||||
this.deviceDao = deviceDao;
|
this.deviceDao = deviceDao;
|
||||||
this.sysUserUtilService = sysUserUtilService;
|
this.sysUserUtilService = sysUserUtilService;
|
||||||
this.frontedUrl = sysParamsService.getValue(Constant.SERVER_FRONTED_URL, true);
|
this.frontedUrl = frontedUrl;
|
||||||
this.redisTemplate = redisTemplate;
|
this.redisTemplate = redisTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -120,7 +120,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId,
|
public DeviceReportRespDTO checkDeviceActive(String macAddress, String deviceId, String clientId,
|
||||||
DeviceReportReqDTO deviceReport) {
|
DeviceReportReqDTO deviceReport) {
|
||||||
DeviceReportRespDTO response = new DeviceReportRespDTO();
|
DeviceReportRespDTO response = new DeviceReportRespDTO();
|
||||||
response.setServer_time(buildServerTime());
|
response.setServer_time(buildServerTime());
|
||||||
|
|
@ -132,12 +132,46 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
firmware.setUrl("http://localhost:8002/xiaozhi/ota/download");
|
firmware.setUrl("http://localhost:8002/xiaozhi/ota/download");
|
||||||
response.setFirmware(firmware);
|
response.setFirmware(firmware);
|
||||||
|
|
||||||
DeviceEntity deviceById = getDeviceById(macAddress);
|
DeviceEntity deviceById = getDeviceById(deviceId);
|
||||||
if (deviceById != null) { // 如果设备存在,则更新上次连接时间
|
if (deviceById != null) { // 如果设备存在,则更新上次连接时间
|
||||||
deviceById.setLastConnectedAt(new Date());
|
deviceById.setLastConnectedAt(new Date());
|
||||||
deviceDao.updateById(deviceById);
|
deviceDao.updateById(deviceById);
|
||||||
} else { // 如果设备不存在,则生成激活码
|
} else { // 如果设备不存在,则生成激活码
|
||||||
DeviceReportRespDTO.Activation code = buildActivation(macAddress, deviceReport);
|
String safeDeviceId = deviceId.replace(":", "_").toLowerCase();
|
||||||
|
String dataKey = String.format("ota:activation:data:%s", safeDeviceId);
|
||||||
|
|
||||||
|
Map<Object, Object> cacheMap = redisTemplate.opsForHash().entries(dataKey);
|
||||||
|
DeviceReportRespDTO.Activation code = new DeviceReportRespDTO.Activation();
|
||||||
|
|
||||||
|
if (cacheMap != null && cacheMap.containsKey("activation_code")) {
|
||||||
|
String cachedCode = (String) cacheMap.get("activation_code");
|
||||||
|
code.setCode(cachedCode);
|
||||||
|
code.setMessage(frontedUrl + "\n" + cachedCode);
|
||||||
|
} else {
|
||||||
|
String newCode = RandomUtil.randomNumbers(6);
|
||||||
|
code.setCode(newCode);
|
||||||
|
code.setMessage(frontedUrl + "\n" + newCode);
|
||||||
|
|
||||||
|
Map<String, Object> dataMap = new HashMap<>();
|
||||||
|
dataMap.put("id", deviceId);
|
||||||
|
dataMap.put("mac_address", macAddress);
|
||||||
|
dataMap.put("board", (deviceReport.getChipModelName() != null) ? deviceReport.getChipModelName()
|
||||||
|
: (deviceReport.getBoard() != null ? deviceReport.getBoard().getType() : "unknown"));
|
||||||
|
dataMap.put("app_version", (deviceReport.getApplication() != null)
|
||||||
|
? deviceReport.getApplication().getVersion()
|
||||||
|
: null);
|
||||||
|
dataMap.put("deviceId", deviceId);
|
||||||
|
dataMap.put("activation_code", newCode);
|
||||||
|
|
||||||
|
// 写入主数据 key
|
||||||
|
redisTemplate.opsForHash().putAll(dataKey, dataMap);
|
||||||
|
redisTemplate.expire(dataKey, 24, TimeUnit.HOURS);
|
||||||
|
|
||||||
|
// 写入反查激活码 key
|
||||||
|
String codeKey = "ota:activation:code:" + newCode;
|
||||||
|
redisTemplate.opsForValue().set(codeKey, deviceId, 24, TimeUnit.HOURS);
|
||||||
|
}
|
||||||
|
|
||||||
response.setActivation(code);
|
response.setActivation(code);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -187,7 +221,7 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
params.put(Constant.PAGE, dto.getPage());
|
params.put(Constant.PAGE, dto.getPage());
|
||||||
params.put(Constant.LIMIT, dto.getLimit());
|
params.put(Constant.LIMIT, dto.getLimit());
|
||||||
IPage<DeviceEntity> page = baseDao.selectPage(
|
IPage<DeviceEntity> page = baseDao.selectPage(
|
||||||
getPage(params, "mac_address", true),
|
getPage(params, "sort", true),
|
||||||
// 定义查询条件
|
// 定义查询条件
|
||||||
new QueryWrapper<DeviceEntity>()
|
new QueryWrapper<DeviceEntity>()
|
||||||
// 必须设备关键词查找
|
// 必须设备关键词查找
|
||||||
|
|
@ -206,16 +240,6 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
return new PageData<>(list, page.getTotal());
|
return new PageData<>(list, page.getTotal());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public DeviceEntity getDeviceByMacAddress(String macAddress) {
|
|
||||||
if (StringUtils.isBlank(macAddress)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
|
|
||||||
wrapper.eq("mac_address", macAddress);
|
|
||||||
return baseDao.selectOne(wrapper);
|
|
||||||
}
|
|
||||||
|
|
||||||
private DeviceReportRespDTO.ServerTime buildServerTime() {
|
private DeviceReportRespDTO.ServerTime buildServerTime() {
|
||||||
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
|
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
|
||||||
TimeZone tz = TimeZone.getDefault();
|
TimeZone tz = TimeZone.getDefault();
|
||||||
|
|
@ -224,60 +248,4 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
serverTime.setTimezone_offset(tz.getOffset(System.currentTimeMillis()) / (60 * 1000));
|
serverTime.setTimezone_offset(tz.getOffset(System.currentTimeMillis()) / (60 * 1000));
|
||||||
return serverTime;
|
return serverTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String geCodeByDeviceId(String deviceId) {
|
|
||||||
String dataKey = getDeviceCacheKey(deviceId);
|
|
||||||
|
|
||||||
Map<Object, Object> cacheMap = redisTemplate.opsForHash().entries(dataKey);
|
|
||||||
if (cacheMap != null && cacheMap.containsKey("activation_code")) {
|
|
||||||
String cachedCode = (String) cacheMap.get("activation_code");
|
|
||||||
return cachedCode;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getDeviceCacheKey(String deviceId) {
|
|
||||||
String safeDeviceId = deviceId.replace(":", "_").toLowerCase();
|
|
||||||
String dataKey = String.format("ota:activation:data:%s", safeDeviceId);
|
|
||||||
return dataKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DeviceReportRespDTO.Activation buildActivation(String deviceId, DeviceReportReqDTO deviceReport) {
|
|
||||||
DeviceReportRespDTO.Activation code = new DeviceReportRespDTO.Activation();
|
|
||||||
|
|
||||||
String cachedCode = geCodeByDeviceId(deviceId);
|
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(cachedCode)) {
|
|
||||||
code.setCode(cachedCode);
|
|
||||||
code.setMessage(frontedUrl + "\n" + cachedCode);
|
|
||||||
} else {
|
|
||||||
String newCode = RandomUtil.randomNumbers(6);
|
|
||||||
code.setCode(newCode);
|
|
||||||
code.setMessage(frontedUrl + "\n" + newCode);
|
|
||||||
|
|
||||||
Map<String, Object> dataMap = new HashMap<>();
|
|
||||||
dataMap.put("id", deviceId);
|
|
||||||
dataMap.put("mac_address", deviceId);
|
|
||||||
|
|
||||||
dataMap.put("board", (deviceReport.getChipModelName() != null) ? deviceReport.getChipModelName()
|
|
||||||
: (deviceReport.getBoard() != null ? deviceReport.getBoard().getType() : "unknown"));
|
|
||||||
dataMap.put("app_version", (deviceReport.getApplication() != null)
|
|
||||||
? deviceReport.getApplication().getVersion()
|
|
||||||
: null);
|
|
||||||
|
|
||||||
dataMap.put("deviceId", deviceId);
|
|
||||||
dataMap.put("activation_code", newCode);
|
|
||||||
|
|
||||||
// 写入主数据 key
|
|
||||||
String dataKey = getDeviceCacheKey(deviceId);
|
|
||||||
redisTemplate.opsForHash().putAll(dataKey, dataMap);
|
|
||||||
redisTemplate.expire(dataKey, 24, TimeUnit.HOURS);
|
|
||||||
|
|
||||||
// 写入反查激活码 key
|
|
||||||
String codeKey = "ota:activation:code:" + newCode;
|
|
||||||
redisTemplate.opsForValue().set(codeKey, deviceId, 24, TimeUnit.HOURS);
|
|
||||||
}
|
|
||||||
return code;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,65 @@
|
||||||
|
package xiaozhi.modules.device.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import xiaozhi.common.page.PageData;
|
||||||
|
import xiaozhi.common.utils.Query;
|
||||||
|
import xiaozhi.modules.device.dao.OtaDao;
|
||||||
|
import xiaozhi.modules.device.entity.OtaEntity;
|
||||||
|
import xiaozhi.modules.device.service.OtaService;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class OtaServiceImpl extends ServiceImpl<OtaDao, OtaEntity> implements OtaService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageData<OtaEntity> page(Map<String, Object> params) {
|
||||||
|
IPage<OtaEntity> page = baseMapper.selectPage(
|
||||||
|
new Query<OtaEntity>().getPage(params),
|
||||||
|
new QueryWrapper<OtaEntity>()
|
||||||
|
.orderByDesc("create_date")
|
||||||
|
);
|
||||||
|
|
||||||
|
return new PageData<>(page.getRecords(), page.getTotal());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(OtaEntity entity) {
|
||||||
|
// 检查是否存在相同名称、类型和版本的固件(排除当前记录)
|
||||||
|
QueryWrapper<OtaEntity> queryWrapper = new QueryWrapper<OtaEntity>()
|
||||||
|
.eq("firmware_name", entity.getFirmwareName())
|
||||||
|
.eq("type", entity.getType())
|
||||||
|
.eq("version", entity.getVersion())
|
||||||
|
.ne("id", entity.getId()); // 排除当前记录
|
||||||
|
|
||||||
|
if (baseMapper.selectCount(queryWrapper) > 0) {
|
||||||
|
throw new RuntimeException("已存在相同名称、类型和版本的固件,请修改后重试");
|
||||||
|
}
|
||||||
|
|
||||||
|
baseMapper.updateById(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(String[] ids) {
|
||||||
|
baseMapper.deleteBatchIds(Arrays.asList(ids));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean save(OtaEntity entity) {
|
||||||
|
// 检查是否存在相同名称、类型和版本的固件
|
||||||
|
QueryWrapper<OtaEntity> queryWrapper = new QueryWrapper<OtaEntity>()
|
||||||
|
.eq("firmware_name", entity.getFirmwareName())
|
||||||
|
.eq("type", entity.getType())
|
||||||
|
.eq("version", entity.getVersion());
|
||||||
|
|
||||||
|
if (baseMapper.selectCount(queryWrapper) > 0) {
|
||||||
|
throw new RuntimeException("已存在相同名称、类型和版本的固件,请勿重复添加");
|
||||||
|
}
|
||||||
|
|
||||||
|
return baseMapper.insert(entity) > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -19,8 +19,6 @@ import lombok.AllArgsConstructor;
|
||||||
import xiaozhi.common.page.PageData;
|
import xiaozhi.common.page.PageData;
|
||||||
import xiaozhi.common.utils.ConvertUtils;
|
import xiaozhi.common.utils.ConvertUtils;
|
||||||
import xiaozhi.common.utils.Result;
|
import xiaozhi.common.utils.Result;
|
||||||
import xiaozhi.modules.agent.service.AgentTemplateService;
|
|
||||||
import xiaozhi.modules.config.service.ConfigService;
|
|
||||||
import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
|
import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
|
||||||
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
|
||||||
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
import xiaozhi.modules.model.dto.ModelConfigDTO;
|
||||||
|
|
@ -40,8 +38,6 @@ public class ModelController {
|
||||||
private final ModelProviderService modelProviderService;
|
private final ModelProviderService modelProviderService;
|
||||||
private final TimbreService timbreService;
|
private final TimbreService timbreService;
|
||||||
private final ModelConfigService modelConfigService;
|
private final ModelConfigService modelConfigService;
|
||||||
private final ConfigService configService;
|
|
||||||
private final AgentTemplateService agentTemplateService;
|
|
||||||
|
|
||||||
@GetMapping("/names")
|
@GetMapping("/names")
|
||||||
@Operation(summary = "获取所有模型名称")
|
@Operation(summary = "获取所有模型名称")
|
||||||
|
|
@ -79,7 +75,6 @@ public class ModelController {
|
||||||
@PathVariable String provideCode,
|
@PathVariable String provideCode,
|
||||||
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
|
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
|
||||||
ModelConfigDTO modelConfigDTO = modelConfigService.add(modelType, provideCode, modelConfigBodyDTO);
|
ModelConfigDTO modelConfigDTO = modelConfigService.add(modelType, provideCode, modelConfigBodyDTO);
|
||||||
configService.getConfig(false);
|
|
||||||
return new Result<ModelConfigDTO>().ok(modelConfigDTO);
|
return new Result<ModelConfigDTO>().ok(modelConfigDTO);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -91,7 +86,6 @@ public class ModelController {
|
||||||
@PathVariable String id,
|
@PathVariable String id,
|
||||||
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
|
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
|
||||||
ModelConfigDTO modelConfigDTO = modelConfigService.edit(modelType, provideCode, id, modelConfigBodyDTO);
|
ModelConfigDTO modelConfigDTO = modelConfigService.edit(modelType, provideCode, id, modelConfigBodyDTO);
|
||||||
configService.getConfig(false);
|
|
||||||
return new Result<ModelConfigDTO>().ok(modelConfigDTO);
|
return new Result<ModelConfigDTO>().ok(modelConfigDTO);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -125,27 +119,6 @@ public class ModelController {
|
||||||
return new Result<Void>();
|
return new Result<Void>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/default/{id}")
|
|
||||||
@Operation(summary = "设置默认模型")
|
|
||||||
@RequiresPermissions("sys:role:superAdmin")
|
|
||||||
public Result<Void> setDefaultModel(@PathVariable String id) {
|
|
||||||
ModelConfigEntity entity = modelConfigService.selectById(id);
|
|
||||||
if (entity == null) {
|
|
||||||
return new Result<Void>().error("模型配置不存在");
|
|
||||||
}
|
|
||||||
// 将其他模型设置为非默认
|
|
||||||
modelConfigService.setDefaultModel(entity.getModelType(), 0);
|
|
||||||
entity.setIsEnabled(1);
|
|
||||||
entity.setIsDefault(1);
|
|
||||||
modelConfigService.updateById(entity);
|
|
||||||
|
|
||||||
// 更新模板表中对应的模型ID
|
|
||||||
agentTemplateService.updateDefaultTemplateModelId(entity.getModelType(), entity.getId());
|
|
||||||
|
|
||||||
configService.getConfig(false);
|
|
||||||
return new Result<Void>();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/{modelId}/voices")
|
@GetMapping("/{modelId}/voices")
|
||||||
@Operation(summary = "获取模型音色")
|
@Operation(summary = "获取模型音色")
|
||||||
@RequiresPermissions("sys:role:normal")
|
@RequiresPermissions("sys:role:normal")
|
||||||
|
|
|
||||||
|
|
@ -28,21 +28,4 @@ public interface ModelConfigService extends BaseService<ModelConfigEntity> {
|
||||||
* @return 模型名称
|
* @return 模型名称
|
||||||
*/
|
*/
|
||||||
String getModelNameById(String id);
|
String getModelNameById(String id);
|
||||||
|
|
||||||
/**
|
|
||||||
* 根据ID获取模型配置
|
|
||||||
*
|
|
||||||
* @param id 模型ID
|
|
||||||
* @param isCache 是否缓存
|
|
||||||
* @return 模型配置实体
|
|
||||||
*/
|
|
||||||
ModelConfigEntity getModelById(String id, boolean isCache);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置默认模型
|
|
||||||
*
|
|
||||||
* @param modelType 模型类型
|
|
||||||
* @param isDefault 是否默认
|
|
||||||
*/
|
|
||||||
void setDefaultModel(String modelType, int isDefault);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,6 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
||||||
List<ModelConfigEntity> entities = modelConfigDao.selectList(
|
List<ModelConfigEntity> entities = modelConfigDao.selectList(
|
||||||
new QueryWrapper<ModelConfigEntity>()
|
new QueryWrapper<ModelConfigEntity>()
|
||||||
.eq("model_type", modelType)
|
.eq("model_type", modelType)
|
||||||
.eq("is_enabled", 1)
|
|
||||||
.like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%")
|
.like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%")
|
||||||
.select("id", "model_name"));
|
.select("id", "model_name"));
|
||||||
return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class);
|
return ConvertUtils.sourceToTarget(entities, ModelBasicInfoDTO.class);
|
||||||
|
|
@ -95,8 +94,6 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
||||||
modelConfigEntity.setId(id);
|
modelConfigEntity.setId(id);
|
||||||
modelConfigEntity.setModelType(modelType);
|
modelConfigEntity.setModelType(modelType);
|
||||||
modelConfigDao.updateById(modelConfigEntity);
|
modelConfigDao.updateById(modelConfigEntity);
|
||||||
// 清除缓存
|
|
||||||
redisUtils.delete(RedisKeys.getModelConfigById(modelConfigEntity.getId()));
|
|
||||||
return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class);
|
return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -128,30 +125,4 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public ModelConfigEntity getModelById(String id, boolean isCache) {
|
|
||||||
if (StringUtils.isBlank(id)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (isCache) {
|
|
||||||
ModelConfigEntity cachedConfig = (ModelConfigEntity) redisUtils.get(RedisKeys.getModelConfigById(id));
|
|
||||||
if (cachedConfig != null) {
|
|
||||||
return ConvertUtils.sourceToTarget(cachedConfig, ModelConfigEntity.class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ModelConfigEntity entity = modelConfigDao.selectById(id);
|
|
||||||
if (entity != null) {
|
|
||||||
redisUtils.set(RedisKeys.getModelConfigById(id), entity);
|
|
||||||
}
|
|
||||||
return entity;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setDefaultModel(String modelType, int isDefault) {
|
|
||||||
ModelConfigEntity entity = new ModelConfigEntity();
|
|
||||||
entity.setIsDefault(isDefault);
|
|
||||||
modelConfigDao.update(entity, new QueryWrapper<ModelConfigEntity>()
|
|
||||||
.eq("model_type", modelType));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -76,10 +76,8 @@ public class ShiroConfig {
|
||||||
filterMap.put("/favicon.ico", "anon");
|
filterMap.put("/favicon.ico", "anon");
|
||||||
filterMap.put("/user/captcha", "anon");
|
filterMap.put("/user/captcha", "anon");
|
||||||
filterMap.put("/user/login", "anon");
|
filterMap.put("/user/login", "anon");
|
||||||
filterMap.put("/user/pub-config", "anon");
|
|
||||||
filterMap.put("/user/register", "anon");
|
filterMap.put("/user/register", "anon");
|
||||||
filterMap.put("/config/server-base", "anon");
|
filterMap.put("/device/register", "anon");
|
||||||
filterMap.put("/config/agent-models", "anon");
|
|
||||||
filterMap.put("/**", "oauth2");
|
filterMap.put("/**", "oauth2");
|
||||||
shiroFilter.setFilterChainDefinitionMap(filterMap);
|
shiroFilter.setFilterChainDefinitionMap(filterMap);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
package xiaozhi.modules.security.controller;
|
package xiaozhi.modules.security.controller;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
|
@ -77,9 +75,6 @@ public class LoginController {
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
@Operation(summary = "注册")
|
@Operation(summary = "注册")
|
||||||
public Result<Void> register(@RequestBody LoginDTO login) {
|
public Result<Void> register(@RequestBody LoginDTO login) {
|
||||||
if (!sysUserService.getAllowUserRegister()) {
|
|
||||||
throw new RenException("当前不允许普通用户注册");
|
|
||||||
}
|
|
||||||
// 验证是否正确输入验证码
|
// 验证是否正确输入验证码
|
||||||
boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha());
|
boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha());
|
||||||
if (!validate) {
|
if (!validate) {
|
||||||
|
|
@ -116,13 +111,4 @@ public class LoginController {
|
||||||
sysUserTokenService.changePassword(userId, passwordDTO);
|
sysUserTokenService.changePassword(userId, passwordDTO);
|
||||||
return new Result<>();
|
return new Result<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/pub-config")
|
|
||||||
@Operation(summary = "公共配置")
|
|
||||||
public Result<Map<String, Object>> pubConfig() {
|
|
||||||
Map<String, Object> config = new HashMap<>();
|
|
||||||
config.put("version", "0.3.6");
|
|
||||||
config.put("allowUserRegister", sysUserService.getAllowUserRegister());
|
|
||||||
return new Result<Map<String, Object>>().ok(config);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
package xiaozhi.modules.sys.config;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.DependsOn;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@DependsOn("liquibase")
|
||||||
|
public class SystemInitConfig {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private SysParamsService sysParamsService;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
sysParamsService.initServerSecret();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -27,7 +27,6 @@ import xiaozhi.common.validator.ValidatorUtils;
|
||||||
import xiaozhi.common.validator.group.AddGroup;
|
import xiaozhi.common.validator.group.AddGroup;
|
||||||
import xiaozhi.common.validator.group.DefaultGroup;
|
import xiaozhi.common.validator.group.DefaultGroup;
|
||||||
import xiaozhi.common.validator.group.UpdateGroup;
|
import xiaozhi.common.validator.group.UpdateGroup;
|
||||||
import xiaozhi.modules.config.service.ConfigService;
|
|
||||||
import xiaozhi.modules.sys.dto.SysParamsDTO;
|
import xiaozhi.modules.sys.dto.SysParamsDTO;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
|
|
||||||
|
|
@ -43,7 +42,6 @@ import xiaozhi.modules.sys.service.SysParamsService;
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class SysParamsController {
|
public class SysParamsController {
|
||||||
private final SysParamsService sysParamsService;
|
private final SysParamsService sysParamsService;
|
||||||
private final ConfigService configService;
|
|
||||||
|
|
||||||
@GetMapping("page")
|
@GetMapping("page")
|
||||||
@Operation(summary = "分页")
|
@Operation(summary = "分页")
|
||||||
|
|
@ -79,7 +77,7 @@ public class SysParamsController {
|
||||||
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
|
ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
|
||||||
|
|
||||||
sysParamsService.save(dto);
|
sysParamsService.save(dto);
|
||||||
configService.getConfig(false);
|
|
||||||
return new Result<Void>();
|
return new Result<Void>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -92,7 +90,7 @@ public class SysParamsController {
|
||||||
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
|
ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
|
||||||
|
|
||||||
sysParamsService.update(dto);
|
sysParamsService.update(dto);
|
||||||
configService.getConfig(false);
|
|
||||||
return new Result<Void>();
|
return new Result<Void>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -105,7 +103,7 @@ public class SysParamsController {
|
||||||
AssertUtils.isArrayEmpty(ids, "id");
|
AssertUtils.isArrayEmpty(ids, "id");
|
||||||
|
|
||||||
sysParamsService.delete(ids);
|
sysParamsService.delete(ids);
|
||||||
configService.getConfig(false);
|
|
||||||
return new Result<Void>();
|
return new Result<Void>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -65,11 +65,4 @@ public interface SysUserService extends BaseService<SysUserEntity> {
|
||||||
* @param userIds 用户ID数组
|
* @param userIds 用户ID数组
|
||||||
*/
|
*/
|
||||||
void changeStatus(Integer status, String[] userIds);
|
void changeStatus(Integer status, String[] userIds);
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取是否允许用户注册
|
|
||||||
*
|
|
||||||
* @return 是否允许用户注册
|
|
||||||
*/
|
|
||||||
boolean getAllowUserRegister();
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
|
||||||
@Override
|
@Override
|
||||||
public PageData<SysParamsDTO> page(Map<String, Object> params) {
|
public PageData<SysParamsDTO> page(Map<String, Object> params) {
|
||||||
IPage<SysParamsEntity> page = baseDao.selectPage(
|
IPage<SysParamsEntity> page = baseDao.selectPage(
|
||||||
getPage(params, null, false),
|
getPage(params, Constant.CREATE_DATE, false),
|
||||||
getWrapper(params));
|
getWrapper(params));
|
||||||
|
|
||||||
return getPageData(page, SysParamsDTO.class);
|
return getPageData(page, SysParamsDTO.class);
|
||||||
|
|
@ -125,13 +125,6 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
|
||||||
throw new RenException(ErrorCode.PARAM_BOOLEAN_INVALID);
|
throw new RenException(ErrorCode.PARAM_BOOLEAN_INVALID);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "json":
|
|
||||||
try {
|
|
||||||
JsonUtils.parseObject(paramValue, Object.class);
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RenException(ErrorCode.PARAM_JSON_INVALID);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
default:
|
||||||
throw new RenException(ErrorCode.PARAM_TYPE_INVALID);
|
throw new RenException(ErrorCode.PARAM_TYPE_INVALID);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,6 @@ import xiaozhi.modules.sys.dto.PasswordDTO;
|
||||||
import xiaozhi.modules.sys.dto.SysUserDTO;
|
import xiaozhi.modules.sys.dto.SysUserDTO;
|
||||||
import xiaozhi.modules.sys.entity.SysUserEntity;
|
import xiaozhi.modules.sys.entity.SysUserEntity;
|
||||||
import xiaozhi.modules.sys.enums.SuperAdminEnum;
|
import xiaozhi.modules.sys.enums.SuperAdminEnum;
|
||||||
import xiaozhi.modules.sys.service.SysParamsService;
|
|
||||||
import xiaozhi.modules.sys.service.SysUserService;
|
import xiaozhi.modules.sys.service.SysUserService;
|
||||||
import xiaozhi.modules.sys.vo.AdminPageUserVO;
|
import xiaozhi.modules.sys.vo.AdminPageUserVO;
|
||||||
|
|
||||||
|
|
@ -46,8 +45,6 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
|
||||||
|
|
||||||
private final AgentService agentService;
|
private final AgentService agentService;
|
||||||
|
|
||||||
private final SysParamsService sysParamsService;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SysUserDTO getByUsername(String username) {
|
public SysUserDTO getByUsername(String username) {
|
||||||
QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
|
QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
|
||||||
|
|
@ -208,17 +205,4 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
|
||||||
updateById(entity);
|
updateById(entity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean getAllowUserRegister() {
|
|
||||||
String allowUserRegister = sysParamsService.getValue(Constant.SERVER_ALLOW_USER_REGISTER, true);
|
|
||||||
if (allowUserRegister.equals("true")) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
Long userCount = baseDao.selectCount(new QueryWrapper<SysUserEntity>());
|
|
||||||
if (userCount == 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@ public interface TimbreService extends BaseService<TimbreEntity> {
|
||||||
* @param timbreId 音色表id
|
* @param timbreId 音色表id
|
||||||
* @return 音色信息
|
* @return 音色信息
|
||||||
*/
|
*/
|
||||||
TimbreDetailsVO get(String timbreId);
|
TimbreDetailsVO get(Long timbreId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 保存音色信息
|
* 保存音色信息
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
||||||
params.put(Constant.PAGE, dto.getPage());
|
params.put(Constant.PAGE, dto.getPage());
|
||||||
params.put(Constant.LIMIT, dto.getLimit());
|
params.put(Constant.LIMIT, dto.getLimit());
|
||||||
IPage<TimbreEntity> page = baseDao.selectPage(
|
IPage<TimbreEntity> page = baseDao.selectPage(
|
||||||
getPage(params, null, true),
|
getPage(params, "sort", true),
|
||||||
// 定义查询条件
|
// 定义查询条件
|
||||||
new QueryWrapper<TimbreEntity>()
|
new QueryWrapper<TimbreEntity>()
|
||||||
// 必须按照ttsID查找
|
// 必须按照ttsID查找
|
||||||
|
|
@ -59,33 +59,9 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TimbreDetailsVO get(String timbreId) {
|
public TimbreDetailsVO get(Long timbreId) {
|
||||||
if (StringUtils.isBlank(timbreId)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 先从Redis获取缓存
|
|
||||||
String key = RedisKeys.getTimbreDetailsKey(timbreId);
|
|
||||||
TimbreDetailsVO cachedDetails = (TimbreDetailsVO) redisUtils.get(key);
|
|
||||||
if (cachedDetails != null) {
|
|
||||||
return cachedDetails;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果缓存中没有,则从数据库获取
|
|
||||||
TimbreEntity entity = baseDao.selectById(timbreId);
|
TimbreEntity entity = baseDao.selectById(timbreId);
|
||||||
if (entity == null) {
|
return ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class);
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 转换为VO对象
|
|
||||||
TimbreDetailsVO details = ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class);
|
|
||||||
|
|
||||||
// 存入Redis缓存
|
|
||||||
if (details != null) {
|
|
||||||
redisUtils.set(key, details);
|
|
||||||
}
|
|
||||||
|
|
||||||
return details;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
@ -103,8 +79,6 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
||||||
TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class);
|
TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class);
|
||||||
timbreEntity.setId(timbreId);
|
timbreEntity.setId(timbreId);
|
||||||
baseDao.updateById(timbreEntity);
|
baseDao.updateById(timbreEntity);
|
||||||
// 删除缓存
|
|
||||||
redisUtils.delete(RedisKeys.getTimbreDetailsKey(timbreId));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
||||||
|
|
@ -12,9 +12,9 @@ spring:
|
||||||
druid:
|
druid:
|
||||||
#MySQL
|
#MySQL
|
||||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||||
url: jdbc:mysql://127.0.0.1:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
|
url: jdbc:mysql://127.0.0.1:3308/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
|
||||||
username: root
|
username: root
|
||||||
password: 123456
|
password: jky123456
|
||||||
initial-size: 10
|
initial-size: 10
|
||||||
max-active: 100
|
max-active: 100
|
||||||
min-idle: 10
|
min-idle: 10
|
||||||
|
|
|
||||||
|
|
@ -64,3 +64,6 @@ mybatis-plus:
|
||||||
prefix:
|
prefix:
|
||||||
blobType: BLOB
|
blobType: BLOB
|
||||||
boolValue: TRUE
|
boolValue: TRUE
|
||||||
|
|
||||||
|
app:
|
||||||
|
fronted-url: http://localhost:8001
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
-- 本文件用于初始化模型配置数据,无需手动执行,在项目启动时会自动执行
|
||||||
|
-- -------------------------------------------------------
|
||||||
|
-- 初始化模型配置数据
|
||||||
|
DELETE FROM `ai_model_config`;
|
||||||
|
|
||||||
|
-- VAD模型配置
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('VAD_SileroVAD', 'VAD', 'SileroVAD', '语音活动检测', 1, 1, '{\"type\": \"silero\", \"model_dir\": \"models/snakers4_silero-vad\", \"threshold\": 0.5, \"min_silence_duration_ms\": 700}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
|
||||||
|
-- ASR模型配置
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('ASR_FunASR', 'ASR', 'FunASR', 'FunASR语音识别', 1, 1, '{\"type\": \"fun_local\", \"model_dir\": \"models/SenseVoiceSmall\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('ASR_SherpaASR', 'ASR', 'SherpaASR', 'Sherpa语音识别', 1, 0, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('ASR_DoubaoASR', 'ASR', 'DoubaoASR', '豆包语音识别', 1, 0, '{\"type\": \"doubao\", \"appid\": \"\", \"access_token\": \"\", \"cluster\": \"volcengine_input_common\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
|
||||||
|
-- LLM模型配置
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_AliLLM', 'LLM', 'AliLLM', '通义千问', 1, 0, '{\"type\": \"openai\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"model_name\": \"qwen-turbo\", \"api_key\": \"\", \"temperature\": 0.7, \"max_tokens\": 500, \"top_p\": 1, \"top_k\": 50, \"frequency_penalty\": 0}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_AliAppLLM', 'LLM', 'AliAppLLM', '通义百炼', 1, 0, '{\"type\": \"AliBL\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"app_id\": \"\", \"api_key\": \"\", \"is_no_prompt\": true, \"ali_memory_id\": false}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_DoubaoLLM', 'LLM', 'DoubaoLLM', '豆包大模型', 1, 0, '{\"type\": \"openai\", \"base_url\": \"https://ark.cn-beijing.volces.com/api/v3\", \"model_name\": \"doubao-pro-32k-functioncall-241028\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_DeepSeekLLM', 'LLM', 'DeepSeekLLM', 'DeepSeek', 1, 0, '{\"type\": \"openai\", \"model_name\": \"deepseek-chat\", \"url\": \"https://api.deepseek.com\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_ChatGLMLLM', 'LLM', 'ChatGLMLLM', '智谱AI', 1, 1, '{\"type\": \"openai\", \"model_name\": \"glm-4-flash\", \"url\": \"https://open.bigmodel.cn/api/paas/v4/\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_OllamaLLM', 'LLM', 'OllamaLLM', 'Ollama本地模型', 1, 0, '{\"type\": \"ollama\", \"model_name\": \"qwen2.5\", \"base_url\": \"http://localhost:11434\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_DifyLLM', 'LLM', 'DifyLLM', 'Dify', 1, 0, '{\"type\": \"dify\", \"base_url\": \"https://api.dify.ai/v1\", \"api_key\": \"\", \"mode\": \"chat-messages\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_GeminiLLM', 'LLM', 'GeminiLLM', '谷歌Gemini', 1, 0, '{\"type\": \"gemini\", \"api_key\": \"\", \"model_name\": \"gemini-2.0-flash\", \"http_proxy\": \"\", \"https_proxy\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_CozeLLM', 'LLM', 'CozeLLM', 'Coze', 1, 0, '{\"type\": \"coze\", \"bot_id\": \"\", \"user_id\": \"\", \"personal_access_token\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_LMStudioLLM', 'LLM', 'LMStudioLLM', 'LM Studio', 1, 0, '{\"type\": \"openai\", \"model_name\": \"deepseek-r1-distill-llama-8b@q4_k_m\", \"url\": \"http://localhost:1234/v1\", \"api_key\": \"lm-studio\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_FastgptLLM', 'LLM', 'FastgptLLM', 'FastGPT', 1, 0, '{\"type\": \"fastgpt\", \"base_url\": \"https://host/api/v1\", \"api_key\": \"fastgpt-xxx\", \"variables\": {\"k\": \"v\", \"k2\": \"v2\"}}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceLLM', 'LLM', 'XinferenceLLM', 'Xinference大模型', 1, 0, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:72b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceSmallLLM', 'LLM', 'XinferenceSmallLLM', 'Xinference小模型', 1, 0, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:3b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
|
||||||
|
-- TTS模型配置
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_EdgeTTS', 'TTS', 'EdgeTTS', 'Edge语音合成', 1, 1, '{\"type\": \"edge\", \"voice\": \"zh-CN-XiaoxiaoNeural\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_DoubaoTTS', 'TTS', 'DoubaoTTS', '豆包语音合成', 1, 0, '{\"type\": \"doubao\", \"api_url\": \"https://openspeech.bytedance.com/api/v1/tts\", \"voice\": \"BV001_streaming\", \"output_dir\": \"tmp/\", \"authorization\": \"Bearer;\", \"appid\": \"\", \"access_token\": \"\", \"cluster\": \"volcano_tts\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_CosyVoiceSiliconflow', 'TTS', 'CosyVoiceSiliconflow', '硅基流动语音合成', 1, 0, '{\"type\": \"siliconflow\", \"model\": \"FunAudioLLM/CosyVoice2-0.5B\", \"voice\": \"FunAudioLLM/CosyVoice2-0.5B:alex\", \"output_dir\": \"tmp/\", \"access_token\": \"\", \"response_format\": \"wav\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_CozeCnTTS', 'TTS', 'CozeCnTTS', 'Coze中文语音合成', 1, 0, '{\"type\": \"cozecn\", \"voice\": \"7426720361733046281\", \"output_dir\": \"tmp/\", \"access_token\": \"\", \"response_format\": \"wav\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_FishSpeech', 'TTS', 'FishSpeech', 'FishSpeech语音合成', 1, 0, '{\"type\": \"fishspeech\", \"output_dir\": \"tmp/\", \"response_format\": \"wav\", \"reference_id\": null, \"reference_audio\": [\"/tmp/test.wav\"], \"reference_text\": [\"你弄来这些吟词宴曲来看,还是这些混话来欺负我。\"], \"normalize\": true, \"max_new_tokens\": 1024, \"chunk_length\": 200, \"top_p\": 0.7, \"repetition_penalty\": 1.2, \"temperature\": 0.7, \"streaming\": false, \"use_memory_cache\": \"on\", \"seed\": null, \"channels\": 1, \"rate\": 44100, \"api_key\": \"\", \"api_url\": \"http://127.0.0.1:8080/v1/tts\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V2', 'TTS', 'GPT_SOVITS_V2', 'GPT-SoVITS V2', 1, 0, '{\"type\": \"gpt_sovits_v2\", \"url\": \"http://127.0.0.1:9880/tts\", \"output_dir\": \"tmp/\", \"text_lang\": \"auto\", \"ref_audio_path\": \"caixukun.wav\", \"prompt_text\": \"\", \"prompt_lang\": \"zh\", \"top_k\": 5, \"top_p\": 1, \"temperature\": 1, \"text_split_method\": \"cut0\", \"batch_size\": 1, \"batch_threshold\": 0.75, \"split_bucket\": true, \"return_fragment\": false, \"speed_factor\": 1.0, \"streaming_mode\": false, \"seed\": -1, \"parallel_infer\": true, \"repetition_penalty\": 1.35, \"aux_ref_audio_paths\": []}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V3', 'TTS', 'GPT_SOVITS_V3', 'GPT-SoVITS V3', 1, 0, '{\"type\": \"gpt_sovits_v3\", \"url\": \"http://127.0.0.1:9880\", \"output_dir\": \"tmp/\", \"text_language\": \"auto\", \"refer_wav_path\": \"caixukun.wav\", \"prompt_language\": \"zh\", \"prompt_text\": \"\", \"top_k\": 15, \"top_p\": 1.0, \"temperature\": 1.0, \"cut_punc\": \"\", \"speed\": 1.0, \"inp_refs\": [], \"sample_steps\": 32, \"if_sr\": false}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_MinimaxTTS', 'TTS', 'MinimaxTTS', 'MiniMax语音合成', 1, 0, '{\"type\": \"minimax\", \"output_dir\": \"tmp/\", \"group_id\": \"\", \"api_key\": \"\", \"model\": \"speech-01-turbo\", \"voice_id\": \"female-shaonv\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_AliyunTTS', 'TTS', 'AliyunTTS', '阿里云语音合成', 1, 0, '{\"type\": \"aliyun\", \"output_dir\": \"tmp/\", \"appkey\": \"\", \"token\": \"\", \"voice\": \"xiaoyun\", \"access_key_id\": \"\", \"access_key_secret\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_TTS302AI', 'TTS', 'TTS302AI', '302AI语音合成', 1, 0, '{\"type\": \"doubao\", \"api_url\": \"https://api.302ai.cn/doubao/tts_hd\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_GizwitsTTS', 'TTS', 'GizwitsTTS', '机智云语音合成', 1, 0, '{\"type\": \"doubao\", \"api_url\": \"https://bytedance.gizwitsapi.com/api/v1/tts\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_ACGNTTS', 'TTS', 'ACGNTTS', 'ACGN语音合成', 1, 0, '{\"type\": \"ttson\", \"token\": \"\", \"voice_id\": 1695, \"speed_factor\": 1, \"pitch_factor\": 0, \"volume_change_dB\": 0, \"to_lang\": \"ZH\", \"url\": \"https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=\", \"format\": \"mp3\", \"output_dir\": \"tmp/\", \"emotion\": 1}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_OpenAITTS', 'TTS', 'OpenAITTS', 'OpenAI语音合成', 1, 0, '{\"type\": \"openai\", \"api_key\": \"\", \"api_url\": \"https://api.openai.com/v1/audio/speech\", \"model\": \"tts-1\", \"voice\": \"onyx\", \"speed\": 1, \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('TTS_CustomTTS', 'TTS', 'CustomTTS', '自定义语音合成', 1, 0, '{\"type\": \"custom\", \"url\": \"http://127.0.0.1:9880/tts\", \"params\": {}, \"headers\": {}, \"format\": \"wav\", \"output_dir\": \"tmp/\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
|
||||||
|
-- Memory模型配置
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('Memory_mem0ai', 'Memory', 'mem0ai', 'Mem0AI记忆', 1, 0, '{\"type\": \"mem0ai\", \"api_key\": \"\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('Memory_nomem', 'Memory', 'nomem', '无记忆', 1, 1, '{\"type\": \"nomem\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('Memory_mem_local_short', 'Memory', 'mem_local_short', '本地短期记忆', 1, 0, '{\"type\": \"mem_local_short\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
|
||||||
|
-- Intent模型配置
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('Intent_nointent', 'Intent', 'nointent', '无意图识别', 1, 0, '{\"type\": \"nointent\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('Intent_intent_llm', 'Intent', 'intent_llm', 'LLM意图识别', 1, 0, '{\"type\": \"intent_llm\", \"llm\": \"ChatGLMLLM\"}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
INSERT INTO `ai_model_config` VALUES ('Intent_function_call', 'Intent', 'function_call', '函数调用意图识别', 1, 1, '{\"type\": \"function_call\", \"functions\": [\"change_role\", \"get_weather\", \"get_news\", \"play_music\"]}', NULL, NULL, 0, NULL, NULL, NULL, NULL);
|
||||||
|
|
@ -0,0 +1,61 @@
|
||||||
|
-- 本文件用于初始化系统参数数据,无需手动执行,在项目启动时会自动执行
|
||||||
|
-- --------------------------------------------------------
|
||||||
|
-- 初始化参数管理配置
|
||||||
|
DROP TABLE IF EXISTS sys_params;
|
||||||
|
-- 参数管理
|
||||||
|
create table sys_params
|
||||||
|
(
|
||||||
|
id bigint NOT NULL COMMENT 'id',
|
||||||
|
param_code varchar(100) COMMENT '参数编码',
|
||||||
|
param_value varchar(2000) COMMENT '参数值',
|
||||||
|
value_type varchar(20) default 'string' COMMENT '值类型:string-字符串,number-数字,boolean-布尔,array-数组',
|
||||||
|
param_type tinyint unsigned default 1 COMMENT '类型 0:系统参数 1:非系统参数',
|
||||||
|
remark varchar(200) COMMENT '备注',
|
||||||
|
creator bigint COMMENT '创建者',
|
||||||
|
create_date datetime COMMENT '创建时间',
|
||||||
|
updater bigint COMMENT '更新者',
|
||||||
|
update_date datetime COMMENT '更新时间',
|
||||||
|
primary key (id),
|
||||||
|
unique key uk_param_code (param_code)
|
||||||
|
)ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT='参数管理';
|
||||||
|
|
||||||
|
-- 服务器配置
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (100, 'server.ip', '0.0.0.0', 'string', 1, '服务器监听IP地址');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (101, 'server.port', '8000', 'number', 1, '服务器监听端口');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (102, 'server.secret', 'null', 'string', 1, '服务器密钥');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (201, 'log.log_format', '<green>{time:YYMMDD HH:mm:ss}</green>[{version}_{selected_module}][<light-blue>{extra[tag]}</light-blue>]-<level>{level}</level>-<light-green>{message}</light-green>', 'string', 1, '控制台日志格式');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (202, 'log.log_format_file', '{time:YYYY-MM-DD HH:mm:ss} - {version}_{selected_module} - {name} - {level} - {extra[tag]} - {message}', 'string', 1, '文件日志格式');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (203, 'log.log_level', 'INFO', 'string', 1, '日志级别');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (204, 'log.log_dir', 'tmp', 'string', 1, '日志目录');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (205, 'log.log_file', 'server.log', 'string', 1, '日志文件名');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (206, 'log.data_dir', 'data', 'string', 1, '数据目录');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (301, 'delete_audio', 'true', 'boolean', 1, '是否删除使用后的音频文件');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (302, 'close_connection_no_voice_time', '120', 'number', 1, '无语音输入断开连接时间(秒)');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (303, 'tts_timeout', '10', 'number', 1, 'TTS请求超时时间(秒)');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (304, 'enable_wakeup_words_response_cache', 'true', 'boolean', 1, '是否开启唤醒词加速');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (305, 'enable_greeting', 'true', 'boolean', 1, '是否开启开场回复');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (306, 'enable_stop_tts_notify', 'false', 'boolean', 1, '是否开启结束提示音');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (307, 'stop_tts_notify_voice', 'config/assets/tts_notify.mp3', 'string', 1, '结束提示音文件路径');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (308, 'exit_commands', '退出;关闭', 'array', 1, '退出命令列表');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (309, 'xiaozhi', '{
|
||||||
|
"type": "hello",
|
||||||
|
"version": 1,
|
||||||
|
"transport": "websocket",
|
||||||
|
"audio_params": {
|
||||||
|
"format": "opus",
|
||||||
|
"sample_rate": 16000,
|
||||||
|
"channels": 1,
|
||||||
|
"frame_duration": 60
|
||||||
|
}
|
||||||
|
}', 'string', 1, '小智类型');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (310, 'wakeup_words', '你好小智;你好小志;小爱同学;你好小鑫;你好小新;小美同学;小龙小龙;喵喵同学;小滨小滨;小冰小冰', 'array', 1, '唤醒词列表,用于识别唤醒词');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (400, 'plugin.weather.api_key', 'a861d0d5e7bf4ee1a83d9a9e4f96d4da', 'string', 1, '天气插件API密钥');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (401, 'plugin.weather.default_location', '广州', 'string', 1, '天气插件默认城市');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (410, 'plugin.news.default_rss_url', 'https://www.chinanews.com.cn/rss/society.xml', 'string', 1, '新闻插件默认RSS地址');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (411, 'plugin.news.category_urls', '{"society":"https://www.chinanews.com.cn/rss/society.xml","world":"https://www.chinanews.com.cn/rss/world.xml","finance":"https://www.chinanews.com.cn/rss/finance.xml"}', 'string', 1, '新闻插件分类RSS地址');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (421, 'plugin.home_assistant.devices', '客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1;卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1', 'array', 1, 'Home Assistant设备列表');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (422, 'plugin.home_assistant.base_url', 'http://homeassistant.local:8123', 'string', 1, 'Home Assistant服务器地址');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (423, 'plugin.home_assistant.api_key', '你的home assistant api访问令牌', 'string', 1, 'Home Assistant API密钥');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (430, 'plugin.music.music_dir', './music', 'string', 1, '音乐文件存放路径');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (431, 'plugin.music.music_ext', 'mp3;wav;p3', 'array', 1, '音乐文件类型');
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (432, 'plugin.music.refresh_time', '300', 'number', 1, '音乐列表刷新间隔(秒)');
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
-- 本文件用于初始化模型模版数据,无需手动执行,在项目启动时会自动执行
|
||||||
|
-- -------------------------------------------------------
|
||||||
|
-- 初始化智能体模板数据
|
||||||
|
CREATE TABLE `ai_ota` (
|
||||||
|
`id` varchar(32) NOT NULL COMMENT 'ID',
|
||||||
|
`firmware_name` varchar(100) DEFAULT NULL COMMENT '固件名称',
|
||||||
|
`type` varchar(50) DEFAULT NULL COMMENT '固件类型',
|
||||||
|
`version` varchar(50) DEFAULT NULL COMMENT '版本号',
|
||||||
|
`size` bigint DEFAULT NULL COMMENT '文件大小(字节)',
|
||||||
|
`remark` varchar(500) DEFAULT NULL COMMENT '备注/说明',
|
||||||
|
`firmware_path` varchar(255) DEFAULT NULL COMMENT '固件路径',
|
||||||
|
`sort` int unsigned DEFAULT '0' COMMENT '排序',
|
||||||
|
`updater` bigint DEFAULT NULL COMMENT '更新者',
|
||||||
|
`update_date` datetime DEFAULT NULL COMMENT '更新时间',
|
||||||
|
`creator` bigint DEFAULT NULL COMMENT '创建者',
|
||||||
|
`create_date` datetime DEFAULT NULL COMMENT '创建时间',
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='固件信息表';
|
||||||
|
|
@ -23,6 +23,13 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/2025_tts_voive.sql
|
path: classpath:db/changelog/2025_tts_voive.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202504082210
|
||||||
|
author: John
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202504082210.sql
|
||||||
- changeSet:
|
- changeSet:
|
||||||
id: 202504082211
|
id: 202504082211
|
||||||
author: John
|
author: John
|
||||||
|
|
@ -30,6 +37,13 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202504082211.sql
|
path: classpath:db/changelog/202504082211.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202504092313
|
||||||
|
author: John
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202504092313.sql
|
||||||
- changeSet:
|
- changeSet:
|
||||||
id: 202504092335
|
id: 202504092335
|
||||||
author: John
|
author: John
|
||||||
|
|
@ -37,31 +51,3 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202504092335.sql
|
path: classpath:db/changelog/202504092335.sql
|
||||||
- changeSet:
|
|
||||||
id: 202504112044
|
|
||||||
author: John
|
|
||||||
changes:
|
|
||||||
- sqlFile:
|
|
||||||
encoding: utf8
|
|
||||||
path: classpath:db/changelog/202504112044.sql
|
|
||||||
- changeSet:
|
|
||||||
id: 202504112058
|
|
||||||
author: John
|
|
||||||
changes:
|
|
||||||
- sqlFile:
|
|
||||||
encoding: utf8
|
|
||||||
path: classpath:db/changelog/202504112058.sql
|
|
||||||
- changeSet:
|
|
||||||
id: 202504151206
|
|
||||||
author: John
|
|
||||||
changes:
|
|
||||||
- sqlFile:
|
|
||||||
encoding: utf8
|
|
||||||
path: classpath:db/changelog/202504151206.sql
|
|
||||||
- changeSet:
|
|
||||||
id: 202504181534
|
|
||||||
author: John
|
|
||||||
changes:
|
|
||||||
- sqlFile:
|
|
||||||
encoding: utf8
|
|
||||||
path: classpath:db/changelog/202504181534.sql
|
|
||||||
|
|
@ -40,7 +40,3 @@
|
||||||
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
|
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
|
||||||
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
|
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
|
||||||
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
|
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
|
||||||
10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F
|
|
||||||
|
|
||||||
10041=\u8BBE\u5907\u672A\u627E\u5230
|
|
||||||
10042={0}
|
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,3 @@
|
||||||
10037=Parameter value must be a valid number
|
10037=Parameter value must be a valid number
|
||||||
10038=Parameter value must be true or false
|
10038=Parameter value must be true or false
|
||||||
10039=Parameter value must be a valid JSON array format
|
10039=Parameter value must be a valid JSON array format
|
||||||
10040=Parameter value must be a valid JSON format
|
|
||||||
|
|
||||||
10041=Device not found
|
|
||||||
10042={0}
|
|
||||||
|
|
@ -40,7 +40,3 @@
|
||||||
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
|
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
|
||||||
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
|
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
|
||||||
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
|
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
|
||||||
10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F
|
|
||||||
|
|
||||||
10041=\u8BBE\u5907\u672A\u627E\u5230
|
|
||||||
10042={0}
|
|
||||||
|
|
@ -40,7 +40,3 @@
|
||||||
10037=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684\u6578\u5B57
|
10037=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684\u6578\u5B57
|
||||||
10038=\u53C3\u6578\u503C\u5FC5\u9808\u662Ftrue\u6216false
|
10038=\u53C3\u6578\u503C\u5FC5\u9808\u662Ftrue\u6216false
|
||||||
10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F
|
10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F
|
||||||
10040=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u683C\u5F0F
|
|
||||||
|
|
||||||
10041=\u8A2D\u5099\u672A\u627E\u5230
|
|
||||||
10042={0}
|
|
||||||
|
|
@ -33,5 +33,3 @@ timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4
|
||||||
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
||||||
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
||||||
|
|
||||||
ota.device.not.found=\u8BBE\u5907\u672A\u627E\u5230
|
|
||||||
ota.device.need.bind={0}
|
|
||||||
|
|
|
||||||
|
|
@ -32,5 +32,3 @@ timbre.ttsModelId.require=The TTS model ID of the timbre cannot be empty
|
||||||
timbre.ttsVoice.require=The TTS voice of the timbre cannot be empty
|
timbre.ttsVoice.require=The TTS voice of the timbre cannot be empty
|
||||||
timbre.voiceDemo.require=The voice demo of the timbre cannot be empty
|
timbre.voiceDemo.require=The voice demo of the timbre cannot be empty
|
||||||
|
|
||||||
ota.device.not.found=Device not found
|
|
||||||
ota.device.need.bind={0}
|
|
||||||
|
|
@ -32,5 +32,3 @@ timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u9375\u4E0D\u53EF\u4EE5\u7
|
||||||
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7DE8\u78BC\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7DE8\u78BC\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
||||||
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653E\u5730\u5740\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653E\u5730\u5740\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
||||||
|
|
||||||
ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230
|
|
||||||
ota.device.need.bind={0}
|
|
||||||
|
|
@ -31,6 +31,3 @@ timbre.remark.require=\u97F3\u8272\u7684\u5907\u6CE8\u4E0D\u53EF\u4EE5\u4E3A\u7A
|
||||||
timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
||||||
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
||||||
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
timbre.voiceDemo.require=\u97F3\u8272\u7684\u64AD\u653EDemo\u4E0D\u53EF\u4EE5\u4E3A\u7A7A
|
||||||
|
|
||||||
ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230
|
|
||||||
ota.device.need.bind={0}
|
|
||||||
|
|
@ -5,6 +5,7 @@ import device from './module/device.js'
|
||||||
import model from './module/model.js'
|
import model from './module/model.js'
|
||||||
import timbre from "./module/timbre.js"
|
import timbre from "./module/timbre.js"
|
||||||
import user from './module/user.js'
|
import user from './module/user.js'
|
||||||
|
import ota from './module/ota.js'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 接口地址
|
* 接口地址
|
||||||
|
|
@ -31,4 +32,5 @@ export default {
|
||||||
device,
|
device,
|
||||||
model,
|
model,
|
||||||
timbre,
|
timbre,
|
||||||
|
ota
|
||||||
}
|
}
|
||||||
|
|
|
||||||
107
main/manager-web/src/apis/module/ota.js
Normal file
107
main/manager-web/src/apis/module/ota.js
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
import { getServiceUrl } from '../api';
|
||||||
|
import RequestService from '../httpRequest';
|
||||||
|
|
||||||
|
export default {
|
||||||
|
// 分页查询OTA固件信息
|
||||||
|
getOtaList(params, callback) {
|
||||||
|
RequestService.sendRequest()
|
||||||
|
.url(`${getServiceUrl()}/ota/otas`)
|
||||||
|
.method('GET')
|
||||||
|
.data(params)
|
||||||
|
.success((res) => {
|
||||||
|
RequestService.clearRequestTime();
|
||||||
|
callback(res);
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
console.error('获取OTA固件列表失败:', err);
|
||||||
|
RequestService.reAjaxFun(() => {
|
||||||
|
this.getOtaList(params, callback);
|
||||||
|
});
|
||||||
|
}).send();
|
||||||
|
},
|
||||||
|
// 获取单个OTA固件信息
|
||||||
|
getOtaInfo(id, callback) {
|
||||||
|
RequestService.sendRequest()
|
||||||
|
.url(`${getServiceUrl()}/ota/${id}`)
|
||||||
|
.method('GET')
|
||||||
|
.success((res) => {
|
||||||
|
RequestService.clearRequestTime();
|
||||||
|
callback(res);
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
console.error('获取OTA固件信息失败:', err);
|
||||||
|
RequestService.reAjaxFun(() => {
|
||||||
|
this.getOtaInfo(id, callback);
|
||||||
|
});
|
||||||
|
}).send();
|
||||||
|
},
|
||||||
|
// 保存OTA固件信息
|
||||||
|
saveOta(entity, callback) {
|
||||||
|
RequestService.sendRequest()
|
||||||
|
.url(`${getServiceUrl()}/ota`)
|
||||||
|
.method('POST')
|
||||||
|
.data(entity)
|
||||||
|
.success((res) => {
|
||||||
|
RequestService.clearRequestTime();
|
||||||
|
callback(res);
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
console.error('保存OTA固件信息失败:', err);
|
||||||
|
RequestService.reAjaxFun(() => {
|
||||||
|
this.saveOta(entity, callback);
|
||||||
|
});
|
||||||
|
}).send();
|
||||||
|
},
|
||||||
|
// 更新OTA固件信息
|
||||||
|
updateOta(id, entity, callback) {
|
||||||
|
RequestService.sendRequest()
|
||||||
|
.url(`${getServiceUrl()}/ota/${id}`)
|
||||||
|
.method('PUT')
|
||||||
|
.data(entity)
|
||||||
|
.success((res) => {
|
||||||
|
RequestService.clearRequestTime();
|
||||||
|
callback(res);
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
console.error('更新OTA固件信息失败:', err);
|
||||||
|
RequestService.reAjaxFun(() => {
|
||||||
|
this.updateOta(id, entity, callback);
|
||||||
|
});
|
||||||
|
}).send();
|
||||||
|
},
|
||||||
|
// 删除OTA固件
|
||||||
|
deleteOta(id, callback) {
|
||||||
|
RequestService.sendRequest()
|
||||||
|
.url(`${getServiceUrl()}/ota/${id}`)
|
||||||
|
.method('DELETE')
|
||||||
|
.success((res) => {
|
||||||
|
RequestService.clearRequestTime();
|
||||||
|
callback(res);
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
console.error('删除OTA固件失败:', err);
|
||||||
|
RequestService.reAjaxFun(() => {
|
||||||
|
this.deleteOta(id, callback);
|
||||||
|
});
|
||||||
|
}).send();
|
||||||
|
},
|
||||||
|
// 上传固件文件
|
||||||
|
uploadFirmware(file, callback) {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
RequestService.sendRequest()
|
||||||
|
.url(`${getServiceUrl()}/ota/upload`)
|
||||||
|
.method('POST')
|
||||||
|
.data(formData)
|
||||||
|
.success((res) => {
|
||||||
|
RequestService.clearRequestTime();
|
||||||
|
callback(res);
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
console.error('上传固件文件失败:', err);
|
||||||
|
RequestService.reAjaxFun(() => {
|
||||||
|
this.uploadFirmware(file, callback);
|
||||||
|
});
|
||||||
|
}).send();
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
main/manager-web/src/assets/header/firmware_update.png
Normal file
BIN
main/manager-web/src/assets/header/firmware_update.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.6 KiB |
137
main/manager-web/src/components/FirmwareDialog.vue
Normal file
137
main/manager-web/src/components/FirmwareDialog.vue
Normal file
|
|
@ -0,0 +1,137 @@
|
||||||
|
<template>
|
||||||
|
<el-dialog :title="title" :visible.sync="visible" width="500px" @close="handleClose">
|
||||||
|
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
|
||||||
|
<el-form-item label="固件名称" prop="firmwareName">
|
||||||
|
<el-input v-model="form.firmwareName" placeholder="请输入固件名称"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="固件类型" prop="type">
|
||||||
|
<el-input v-model="form.type" placeholder="请输入固件类型"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="版本号" prop="version">
|
||||||
|
<el-input v-model="form.version" placeholder="请输入版本号"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="固件文件" prop="firmwarePath">
|
||||||
|
<el-upload
|
||||||
|
class="upload-demo"
|
||||||
|
action="#"
|
||||||
|
:http-request="handleUpload"
|
||||||
|
:before-upload="beforeUpload"
|
||||||
|
:accept="'.bin,.hex,.elf'"
|
||||||
|
:limit="1"
|
||||||
|
:multiple="false"
|
||||||
|
:auto-upload="true">
|
||||||
|
<el-button size="small" type="primary">点击上传</el-button>
|
||||||
|
<div slot="tip" class="el-upload__tip">只能上传固件文件(.bin/.hex/.elf),且不超过100MB</div>
|
||||||
|
</el-upload>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="备注" prop="remark">
|
||||||
|
<el-input type="textarea" v-model="form.remark" placeholder="请输入备注信息"></el-input>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<div slot="footer" class="dialog-footer">
|
||||||
|
<el-button @click="handleCancel">取 消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmit">确 定</el-button>
|
||||||
|
</div>
|
||||||
|
</el-dialog>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import Api from '@/apis/api'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
name: 'FirmwareDialog',
|
||||||
|
props: {
|
||||||
|
visible: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
type: String,
|
||||||
|
default: ''
|
||||||
|
},
|
||||||
|
form: {
|
||||||
|
type: Object,
|
||||||
|
default: () => ({})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
rules: {
|
||||||
|
firmwareName: [
|
||||||
|
{ required: true, message: '请输入固件名称', trigger: 'blur' }
|
||||||
|
],
|
||||||
|
type: [
|
||||||
|
{ required: true, message: '请输入固件类型', trigger: 'blur' }
|
||||||
|
],
|
||||||
|
version: [
|
||||||
|
{ required: true, message: '请输入版本号', trigger: 'blur' }
|
||||||
|
],
|
||||||
|
firmwarePath: [
|
||||||
|
{ required: false, message: '请上传固件文件', trigger: 'change' }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
handleClose() {
|
||||||
|
this.$refs.form.clearValidate();
|
||||||
|
this.$emit('cancel');
|
||||||
|
},
|
||||||
|
handleCancel() {
|
||||||
|
this.$refs.form.clearValidate();
|
||||||
|
this.$emit('cancel');
|
||||||
|
},
|
||||||
|
handleSubmit() {
|
||||||
|
this.$refs.form.validate(valid => {
|
||||||
|
if (valid) {
|
||||||
|
// 如果是新增模式且没有上传文件,则提示错误
|
||||||
|
if (!this.form.id && !this.form.firmwarePath) {
|
||||||
|
this.$message.error('请上传固件文件')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 提交成功后将关闭对话框的逻辑交给父组件处理
|
||||||
|
this.$emit('submit', this.form)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
beforeUpload(file) {
|
||||||
|
const isValidSize = file.size / 1024 / 1024 < 100
|
||||||
|
const isValidType = ['.bin', '.hex', '.elf'].some(ext => file.name.toLowerCase().endsWith(ext))
|
||||||
|
|
||||||
|
if (!isValidType) {
|
||||||
|
this.$message.error('只能上传.bin/.hex/.elf格式的固件文件!')
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (!isValidSize) {
|
||||||
|
this.$message.error('固件文件大小不能超过100MB!')
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
handleUpload(options) {
|
||||||
|
const { file } = options
|
||||||
|
Api.ota.uploadFirmware(file, (res) => {
|
||||||
|
res = res.data
|
||||||
|
if (res.code === 0) {
|
||||||
|
this.form.firmwarePath = res.data
|
||||||
|
this.form.size = file.size
|
||||||
|
this.$message.success('固件文件上传成功')
|
||||||
|
} else {
|
||||||
|
this.$message.error(res.msg || '文件上传失败')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style lang="scss" scoped>
|
||||||
|
.upload-demo {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.el-upload__tip {
|
||||||
|
line-height: 1.2;
|
||||||
|
padding-top: 5px;
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
@ -32,6 +32,12 @@
|
||||||
:style="{ filter: $route.path === '/params-management' ? 'brightness(0) invert(1)' : 'None' }" />
|
:style="{ filter: $route.path === '/params-management' ? 'brightness(0) invert(1)' : 'None' }" />
|
||||||
参数管理
|
参数管理
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="isSuperAdmin" class="equipment-management"
|
||||||
|
:class="{ 'active-tab': $route.path === '/ota-management' }" @click="goOtaManagement">
|
||||||
|
<img loading="lazy" alt="" src="@/assets/header/firmware_update.png"
|
||||||
|
:style="{ filter: $route.path === '/ota-management' ? 'brightness(0) invert(1)' : 'None' }" />
|
||||||
|
OTA管理
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 右侧元素 -->
|
<!-- 右侧元素 -->
|
||||||
|
|
@ -105,6 +111,9 @@ export default {
|
||||||
goParamManagement() {
|
goParamManagement() {
|
||||||
this.$router.push('/params-management')
|
this.$router.push('/params-management')
|
||||||
},
|
},
|
||||||
|
goOtaManagement() {
|
||||||
|
this.$router.push('/ota-management')
|
||||||
|
},
|
||||||
// 获取用户信息
|
// 获取用户信息
|
||||||
fetchUserInfo() {
|
fetchUserInfo() {
|
||||||
userApi.getUserInfo(({ data }) => {
|
userApi.getUserInfo(({ data }) => {
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,17 @@ const routes = [
|
||||||
title: '参数管理'
|
title: '参数管理'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/ota-management',
|
||||||
|
name: 'OtaManagement',
|
||||||
|
component: function () {
|
||||||
|
return import('../views/OtaManagement.vue')
|
||||||
|
},
|
||||||
|
meta: {
|
||||||
|
requiresAuth: true,
|
||||||
|
title: 'OTA管理'
|
||||||
|
}
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
const router = new VueRouter({
|
const router = new VueRouter({
|
||||||
|
|
|
||||||
21
main/manager-web/src/utils/format.js
Normal file
21
main/manager-web/src/utils/format.js
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
// 日期格式化函数
|
||||||
|
export function formatDate(date) {
|
||||||
|
if (!date) return '';
|
||||||
|
const d = new Date(date);
|
||||||
|
const year = d.getFullYear();
|
||||||
|
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||||
|
const day = String(d.getDate()).padStart(2, '0');
|
||||||
|
const hour = String(d.getHours()).padStart(2, '0');
|
||||||
|
const minute = String(d.getMinutes()).padStart(2, '0');
|
||||||
|
const second = String(d.getSeconds()).padStart(2, '0');
|
||||||
|
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 文件大小格式化函数
|
||||||
|
export function formatFileSize(bytes) {
|
||||||
|
if (!bytes || bytes === 0) return '0 B';
|
||||||
|
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
const k = 1024;
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + units[i];
|
||||||
|
}
|
||||||
637
main/manager-web/src/views/OtaManagement.vue
Normal file
637
main/manager-web/src/views/OtaManagement.vue
Normal file
|
|
@ -0,0 +1,637 @@
|
||||||
|
<template>
|
||||||
|
<div class="welcome">
|
||||||
|
<HeaderBar />
|
||||||
|
|
||||||
|
<div class="operation-bar">
|
||||||
|
<h2 class="page-title">固件管理</h2>
|
||||||
|
<div class="right-operations">
|
||||||
|
<el-input placeholder="请输入固件名称查询" v-model="searchName" class="search-input"
|
||||||
|
@keyup.enter.native="handleSearch" clearable />
|
||||||
|
<el-button class="btn-search" @click="handleSearch">搜索</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="main-wrapper">
|
||||||
|
<div class="content-panel">
|
||||||
|
<div class="content-area">
|
||||||
|
<el-card class="params-card" shadow="never">
|
||||||
|
<el-table ref="paramsTable" :data="paramsList" class="transparent-table"
|
||||||
|
:header-cell-class-name="headerCellClassName">
|
||||||
|
<el-table-column label="选择" align="center" width="120">
|
||||||
|
<template slot-scope="scope">
|
||||||
|
<el-checkbox v-model="scope.row.selected"></el-checkbox>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="固件名称" prop="firmwareName" align="center"></el-table-column>
|
||||||
|
<el-table-column label="固件类型" prop="type" align="center"></el-table-column>
|
||||||
|
<el-table-column label="版本号" prop="version" align="center"></el-table-column>
|
||||||
|
<el-table-column label="文件大小" prop="size" align="center">
|
||||||
|
<template slot-scope="scope">
|
||||||
|
{{ formatFileSize(scope.row.size) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip></el-table-column>
|
||||||
|
<el-table-column label="创建时间" prop="createDate" align="center">
|
||||||
|
<template slot-scope="scope">
|
||||||
|
{{ formatDate(scope.row.createDate) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" align="center">
|
||||||
|
<template slot-scope="scope">
|
||||||
|
<el-button size="mini" type="text" @click="downloadFirmware(scope.row)">下载</el-button>
|
||||||
|
<el-button size="mini" type="text" @click="editParam(scope.row)">编辑</el-button>
|
||||||
|
<el-button size="mini" type="text" @click="deleteParam(scope.row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="table_bottom">
|
||||||
|
<div class="ctrl_btn">
|
||||||
|
<el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll">
|
||||||
|
{{ isAllSelected ? '取消全选' : '全选' }}
|
||||||
|
</el-button>
|
||||||
|
<el-button size="mini" type="success" @click="showAddDialog">新增</el-button>
|
||||||
|
<el-button size="mini" type="danger" icon="el-icon-delete"
|
||||||
|
@click="deleteSelectedParams">删除</el-button>
|
||||||
|
</div>
|
||||||
|
<div class="custom-pagination">
|
||||||
|
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select">
|
||||||
|
<el-option
|
||||||
|
v-for="item in pageSizeOptions"
|
||||||
|
:key="item"
|
||||||
|
:label="`${item}条/页`"
|
||||||
|
:value="item">
|
||||||
|
</el-option>
|
||||||
|
</el-select>
|
||||||
|
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">
|
||||||
|
首页
|
||||||
|
</button>
|
||||||
|
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">
|
||||||
|
上一页
|
||||||
|
</button>
|
||||||
|
<button v-for="page in visiblePages" :key="page" class="pagination-btn"
|
||||||
|
:class="{ active: page === currentPage }" @click="goToPage(page)">
|
||||||
|
{{ page }}
|
||||||
|
</button>
|
||||||
|
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">
|
||||||
|
下一页
|
||||||
|
</button>
|
||||||
|
<span class="total-text">共{{ total }}条记录</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 新增/编辑固件对话框 -->
|
||||||
|
<firmware-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="firmwareForm" @submit="handleSubmit"
|
||||||
|
@cancel="dialogVisible = false" />
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import Api from "@/apis/api";
|
||||||
|
import HeaderBar from "@/components/HeaderBar.vue";
|
||||||
|
import FirmwareDialog from "@/components/FirmwareDialog.vue";
|
||||||
|
import { formatDate, formatFileSize } from "@/utils/format";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
components: { HeaderBar, FirmwareDialog },
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
searchName: "",
|
||||||
|
paramsList: [],
|
||||||
|
firmwareList: [],
|
||||||
|
currentPage: 1,
|
||||||
|
pageSize: 10,
|
||||||
|
pageSizeOptions: [10, 20, 50, 100],
|
||||||
|
total: 0,
|
||||||
|
dialogVisible: false,
|
||||||
|
dialogTitle: "新增固件",
|
||||||
|
isAllSelected: false,
|
||||||
|
firmwareForm: {
|
||||||
|
id: null,
|
||||||
|
firmwareName: "",
|
||||||
|
type: "",
|
||||||
|
version: "",
|
||||||
|
size: 0,
|
||||||
|
remark: "",
|
||||||
|
firmwarePath: ""
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
created() {
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
},
|
||||||
|
|
||||||
|
computed: {
|
||||||
|
pageCount() {
|
||||||
|
return Math.ceil(this.total / this.pageSize);
|
||||||
|
},
|
||||||
|
visiblePages() {
|
||||||
|
const pages = [];
|
||||||
|
const maxVisible = 3;
|
||||||
|
let start = Math.max(1, this.currentPage - 1);
|
||||||
|
let end = Math.min(this.pageCount, start + maxVisible - 1);
|
||||||
|
|
||||||
|
if (end - start + 1 < maxVisible) {
|
||||||
|
start = Math.max(1, end - maxVisible + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = start; i <= end; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
return pages;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
handlePageSizeChange(val) {
|
||||||
|
this.pageSize = val;
|
||||||
|
this.currentPage = 1;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
},
|
||||||
|
fetchFirmwareList() {
|
||||||
|
const params = {
|
||||||
|
pageNum: this.currentPage,
|
||||||
|
pageSize: this.pageSize,
|
||||||
|
firmwareName: this.searchName || undefined,
|
||||||
|
orderField: "create_date",
|
||||||
|
order: "desc"
|
||||||
|
};
|
||||||
|
Api.ota.getOtaList(params, (res) => {
|
||||||
|
res = res.data
|
||||||
|
if (res.code === 0) {
|
||||||
|
this.firmwareList = res.data.list.map(item => ({
|
||||||
|
...item,
|
||||||
|
selected: false
|
||||||
|
}));
|
||||||
|
this.paramsList = this.firmwareList;
|
||||||
|
this.total = res.data.total || 0;
|
||||||
|
} else {
|
||||||
|
this.firmwareList = [];
|
||||||
|
this.paramsList = [];
|
||||||
|
this.total = 0;
|
||||||
|
this.$message.error({
|
||||||
|
message: res?.data?.msg || '获取固件列表失败',
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
handleSearch() {
|
||||||
|
this.currentPage = 1;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
},
|
||||||
|
handleSelectAll() {
|
||||||
|
this.isAllSelected = !this.isAllSelected;
|
||||||
|
this.firmwareList.forEach(row => {
|
||||||
|
row.selected = this.isAllSelected;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
showAddDialog() {
|
||||||
|
this.dialogTitle = "新增固件";
|
||||||
|
// 完全重置表单数据
|
||||||
|
this.firmwareForm = {
|
||||||
|
id: null,
|
||||||
|
firmwareName: "",
|
||||||
|
type: "",
|
||||||
|
version: "",
|
||||||
|
size: 0,
|
||||||
|
remark: "",
|
||||||
|
firmwarePath: ""
|
||||||
|
};
|
||||||
|
this.$nextTick(() => {
|
||||||
|
// 重置表单的校验状态
|
||||||
|
if (this.$refs.firmwareDialog && this.$refs.firmwareDialog.$refs.form) {
|
||||||
|
this.$refs.firmwareDialog.$refs.form.clearValidate();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.dialogVisible = true;
|
||||||
|
},
|
||||||
|
editParam(row) {
|
||||||
|
this.dialogTitle = "编辑固件";
|
||||||
|
this.firmwareForm = { ...row };
|
||||||
|
this.dialogVisible = true;
|
||||||
|
},
|
||||||
|
handleSubmit(form) {
|
||||||
|
if (form.id) {
|
||||||
|
// 编辑
|
||||||
|
Api.ota.updateOta(form.id, form, (res) => {
|
||||||
|
res = res.data;
|
||||||
|
if (res.code === 0) {
|
||||||
|
this.$message.success({
|
||||||
|
message: "修改成功",
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
this.dialogVisible = false;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
} else {
|
||||||
|
this.$message.error({
|
||||||
|
message: res.msg || "修改失败",
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// 新增
|
||||||
|
Api.ota.saveOta(form, (res) => {
|
||||||
|
res = res.data;
|
||||||
|
if (res.code === 0) {
|
||||||
|
this.$message.success({
|
||||||
|
message: "新增成功",
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
this.dialogVisible = false;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
} else {
|
||||||
|
this.$message.error({
|
||||||
|
message: res.msg || "新增失败",
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteSelectedParams() {
|
||||||
|
const selectedRows = this.firmwareList.filter(row => row.selected);
|
||||||
|
if (selectedRows.length === 0) {
|
||||||
|
this.$message.warning({
|
||||||
|
message: "请先选择需要删除的固件",
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.deleteParam(selectedRows);
|
||||||
|
},
|
||||||
|
deleteParam(row) {
|
||||||
|
// 处理单个参数或参数数组
|
||||||
|
const params = Array.isArray(row) ? row : [row];
|
||||||
|
|
||||||
|
if (Array.isArray(row) && row.length === 0) {
|
||||||
|
this.$message.warning({
|
||||||
|
message: "请先选择需要删除的参数",
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const paramCount = params.length;
|
||||||
|
this.$confirm(`确定要删除选中的${paramCount}个固件吗?`, '警告', {
|
||||||
|
confirmButtonText: '确定',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
type: 'warning',
|
||||||
|
distinguishCancelAndClose: true
|
||||||
|
}).then(() => {
|
||||||
|
const ids = params.map(param => param.id);
|
||||||
|
if (ids.some(id => !id)) {
|
||||||
|
this.$message.error({
|
||||||
|
message: '存在无效的参数ID',
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Api.ota.deleteOta(ids, (res) => {
|
||||||
|
res = res.data;
|
||||||
|
if (res.code === 0) {
|
||||||
|
this.$message.success({
|
||||||
|
message: `成功删除${paramCount}个固件`,
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
} else {
|
||||||
|
this.$message.error({
|
||||||
|
message: res.msg || '删除失败,请重试',
|
||||||
|
showClose: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}).catch(action => {
|
||||||
|
if (action === 'cancel') {
|
||||||
|
this.$message({
|
||||||
|
type: 'info',
|
||||||
|
message: '已取消删除操作',
|
||||||
|
duration: 1000
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.$message({
|
||||||
|
type: 'info',
|
||||||
|
message: '操作已关闭',
|
||||||
|
duration: 1000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
headerCellClassName({ columnIndex }) {
|
||||||
|
if (columnIndex === 0) {
|
||||||
|
return "custom-selection-header";
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
},
|
||||||
|
goFirst() {
|
||||||
|
this.currentPage = 1;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
},
|
||||||
|
goPrev() {
|
||||||
|
if (this.currentPage > 1) {
|
||||||
|
this.currentPage--;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
goNext() {
|
||||||
|
if (this.currentPage < this.pageCount) {
|
||||||
|
this.currentPage++;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
goToPage(page) {
|
||||||
|
this.currentPage = page;
|
||||||
|
this.fetchFirmwareList();
|
||||||
|
},
|
||||||
|
downloadFirmware(firmware) {
|
||||||
|
if (!firmware || !firmware.id) {
|
||||||
|
this.$message.error('固件信息不完整');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 使用正确的API基础URL变量
|
||||||
|
const baseUrl = process.env.VUE_APP_API_BASE_URL || '';
|
||||||
|
window.open(`${window.location.origin}${baseUrl}/ota/download/${firmware.id}`);
|
||||||
|
},
|
||||||
|
downloadSelectedFirmwares() {
|
||||||
|
const selectedFirmwares = this.firmwareList.filter(item => item.selected);
|
||||||
|
if (selectedFirmwares.length === 0) {
|
||||||
|
this.$message.warning('请先选择需要下载的固件');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
selectedFirmwares.forEach(firmware => {
|
||||||
|
this.downloadFirmware(firmware);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
formatDate,
|
||||||
|
formatFileSize
|
||||||
|
},
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style lang="scss" scoped>
|
||||||
|
.welcome {
|
||||||
|
min-width: 900px;
|
||||||
|
min-height: 506px;
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
position: relative;
|
||||||
|
flex-direction: column;
|
||||||
|
background-size: cover;
|
||||||
|
background: linear-gradient(to bottom right, #dce8ff, #e4eeff, #e6cbfd) center;
|
||||||
|
-webkit-background-size: cover;
|
||||||
|
-o-background-size: cover;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-wrapper {
|
||||||
|
margin: 5px 22px;
|
||||||
|
border-radius: 15px;
|
||||||
|
min-height: calc(100vh - 24vh);
|
||||||
|
height: auto;
|
||||||
|
max-height: 80vh;
|
||||||
|
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
|
||||||
|
position: relative;
|
||||||
|
background: rgba(237, 242, 255, 0.5);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.operation-bar {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 16px 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-title {
|
||||||
|
font-size: 24px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.right-operations {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.search-input {
|
||||||
|
width: 240px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-search {
|
||||||
|
background: linear-gradient(135deg, #6b8cff, #a966ff);
|
||||||
|
border: none;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content-panel {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
overflow: hidden;
|
||||||
|
height: 100%;
|
||||||
|
border-radius: 15px;
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content-area {
|
||||||
|
flex: 1;
|
||||||
|
height: 100%;
|
||||||
|
min-width: 600px;
|
||||||
|
overflow: auto;
|
||||||
|
background-color: white;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.params-card {
|
||||||
|
background: white;
|
||||||
|
border: none;
|
||||||
|
box-shadow: none;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
flex: 1;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table_bottom {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-top: 10px;
|
||||||
|
padding-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ctrl_btn {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
padding-left: 26px;
|
||||||
|
|
||||||
|
.el-button {
|
||||||
|
min-width: 72px;
|
||||||
|
height: 32px;
|
||||||
|
padding: 7px 12px 7px 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
line-height: 1;
|
||||||
|
font-weight: 500;
|
||||||
|
border: none;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-button--primary {
|
||||||
|
background: #5f70f3;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-button--danger {
|
||||||
|
background: #fd5b63;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-pagination {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
|
||||||
|
.el-select {
|
||||||
|
margin-right: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-btn:first-child,
|
||||||
|
.pagination-btn:nth-child(2),
|
||||||
|
.pagination-btn:nth-last-child(2),
|
||||||
|
.pagination-btn:nth-child(3) {
|
||||||
|
min-width: 60px;
|
||||||
|
height: 32px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid #e4e7ed;
|
||||||
|
background: #dee7ff;
|
||||||
|
color: #606266;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #d7dce6;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-btn:not(:first-child):not(:nth-child(3)):not(:nth-child(2)):not(:nth-last-child(2)) {
|
||||||
|
min-width: 28px;
|
||||||
|
height: 32px;
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 4px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
background: transparent;
|
||||||
|
color: #606266;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: rgba(245, 247, 250, 0.3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-btn.active {
|
||||||
|
background: #5f70f3 !important;
|
||||||
|
color: #ffffff !important;
|
||||||
|
border-color: #5f70f3 !important;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #6d7cf5 !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.total-text {
|
||||||
|
margin-left: 10px;
|
||||||
|
color: #606266;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-size-select {
|
||||||
|
width: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-selection-header {
|
||||||
|
text-align: center !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.transparent-table) {
|
||||||
|
background-color: transparent;
|
||||||
|
|
||||||
|
.el-table__header-wrapper {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-table__header th {
|
||||||
|
background-color: white !important;
|
||||||
|
color: black;
|
||||||
|
font-weight: 600;
|
||||||
|
height: 40px;
|
||||||
|
padding: 8px 0;
|
||||||
|
font-size: 14px;
|
||||||
|
border-bottom: 1px solid #e4e7ed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-table__body-wrapper {
|
||||||
|
td {
|
||||||
|
background-color: transparent;
|
||||||
|
border-bottom: 1px solid #e4e7ed;
|
||||||
|
padding: 8px 0;
|
||||||
|
height: 40px;
|
||||||
|
color: #606266;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.el-table__row:hover > td {
|
||||||
|
background-color: #f5f7fa !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-table .el-button--text) {
|
||||||
|
color: #7079aa !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-table .el-button--text:hover) {
|
||||||
|
color: #5a64b5 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-checkbox__inner) {
|
||||||
|
background-color: #eeeeee !important;
|
||||||
|
border-color: #cccccc !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-checkbox__inner:hover) {
|
||||||
|
border-color: #cccccc !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
|
||||||
|
background-color: #5f70f3 !important;
|
||||||
|
border-color: #5f70f3 !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
@ -7,7 +7,6 @@ from core.utils.util import check_ffmpeg_installed
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def wait_for_exit():
|
async def wait_for_exit():
|
||||||
"""Windows 和 Linux 兼容的退出监听"""
|
"""Windows 和 Linux 兼容的退出监听"""
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
|
|
@ -20,12 +19,10 @@ async def wait_for_exit():
|
||||||
# Linux/macOS: 用 signal 监听 Ctrl + C
|
# Linux/macOS: 用 signal 监听 Ctrl + C
|
||||||
def stop():
|
def stop():
|
||||||
stop_event.set()
|
stop_event.set()
|
||||||
|
|
||||||
loop.add_signal_handler(signal.SIGINT, stop)
|
loop.add_signal_handler(signal.SIGINT, stop)
|
||||||
loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程
|
loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程
|
||||||
await stop_event.wait()
|
await stop_event.wait()
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
check_config_file()
|
check_config_file()
|
||||||
check_ffmpeg_installed()
|
check_ffmpeg_installed()
|
||||||
|
|
@ -47,7 +44,6 @@ async def main():
|
||||||
pass
|
pass
|
||||||
print("服务器已关闭,程序退出。")
|
print("服务器已关闭,程序退出。")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
try:
|
try:
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
|
||||||
|
|
@ -52,7 +52,7 @@ enable_stop_tts_notify: false
|
||||||
# 说完话是否开启提示音,音效地址
|
# 说完话是否开启提示音,音效地址
|
||||||
stop_tts_notify_voice: "config/assets/tts_notify.mp3"
|
stop_tts_notify_voice: "config/assets/tts_notify.mp3"
|
||||||
|
|
||||||
exit_commands:
|
CMD_exit:
|
||||||
- "退出"
|
- "退出"
|
||||||
- "关闭"
|
- "关闭"
|
||||||
|
|
||||||
|
|
@ -147,7 +147,7 @@ selected_module:
|
||||||
Memory: nomem
|
Memory: nomem
|
||||||
# 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。
|
# 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。
|
||||||
# 不想开通意图识别,就设置成:nointent
|
# 不想开通意图识别,就设置成:nointent
|
||||||
# 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,这个意图识别暂时不支持控制音量大小等iot操作
|
# 意图识别可使用intent_llm,如果你的LLM是DifyLLM或CozeLLM,建议使用这个。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,这个意图识别暂时不支持控制音量大小等iot操作
|
||||||
# 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令
|
# 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令
|
||||||
# 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-pro-32k-functioncall-241028
|
# 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-pro-32k-functioncall-241028
|
||||||
Intent: function_call
|
Intent: function_call
|
||||||
|
|
@ -163,7 +163,7 @@ Intent:
|
||||||
type: intent_llm
|
type: intent_llm
|
||||||
# 配备意图识别独立的思考模型
|
# 配备意图识别独立的思考模型
|
||||||
# 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型
|
# 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型
|
||||||
# 如果你的不想使用selected_module.LLM意图识别,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM
|
# 如果你的selected_module.LLM选择了DifyLLM或CozeLLM,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM
|
||||||
llm: ChatGLMLLM
|
llm: ChatGLMLLM
|
||||||
function_call:
|
function_call:
|
||||||
# 不需要动type
|
# 不需要动type
|
||||||
|
|
@ -222,7 +222,6 @@ ASR:
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
VAD:
|
VAD:
|
||||||
SileroVAD:
|
SileroVAD:
|
||||||
type: silero
|
|
||||||
threshold: 0.5
|
threshold: 0.5
|
||||||
model_dir: models/snakers4_silero-vad
|
model_dir: models/snakers4_silero-vad
|
||||||
min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些
|
min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些
|
||||||
|
|
|
||||||
|
|
@ -1,34 +1,9 @@
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
from config.config_loader import load_config
|
from config.settings import load_config
|
||||||
|
|
||||||
SERVER_VERSION = "0.3.6"
|
SERVER_VERSION = "0.2.1"
|
||||||
|
|
||||||
|
|
||||||
def get_module_abbreviation(module_name, module_dict):
|
|
||||||
"""获取模块名称的缩写,如果为空则返回00"""
|
|
||||||
return (
|
|
||||||
module_dict.get(module_name, "")[:2] if module_dict.get(module_name) else "00"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def build_module_string(selected_module):
|
|
||||||
"""构建模块字符串"""
|
|
||||||
return (
|
|
||||||
get_module_abbreviation("VAD", selected_module)
|
|
||||||
+ get_module_abbreviation("ASR", selected_module)
|
|
||||||
+ get_module_abbreviation("LLM", selected_module)
|
|
||||||
+ get_module_abbreviation("TTS", selected_module)
|
|
||||||
+ get_module_abbreviation("Memory", selected_module)
|
|
||||||
+ get_module_abbreviation("Intent", selected_module)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def formatter(record):
|
|
||||||
"""为没有 tag 的日志添加默认值"""
|
|
||||||
record["extra"].setdefault("tag", record["name"])
|
|
||||||
return record["message"]
|
|
||||||
|
|
||||||
|
|
||||||
def setup_logging():
|
def setup_logging():
|
||||||
|
|
@ -43,7 +18,11 @@ def setup_logging():
|
||||||
"log_format_file",
|
"log_format_file",
|
||||||
"{time:YYYY-MM-DD HH:mm:ss} - {version_{selected_module}} - {name} - {level} - {extra[tag]} - {message}",
|
"{time:YYYY-MM-DD HH:mm:ss} - {version_{selected_module}} - {name} - {level} - {extra[tag]} - {message}",
|
||||||
)
|
)
|
||||||
selected_module_str = build_module_string(config.get("selected_module", {}))
|
|
||||||
|
selected_module = config.get("selected_module")
|
||||||
|
selected_module_str = "".join(
|
||||||
|
[value[0] + value[1] for key, value in selected_module.items()]
|
||||||
|
)
|
||||||
|
|
||||||
log_format = log_format.replace("{version}", SERVER_VERSION)
|
log_format = log_format.replace("{version}", SERVER_VERSION)
|
||||||
log_format = log_format.replace("{selected_module}", selected_module_str)
|
log_format = log_format.replace("{selected_module}", selected_module_str)
|
||||||
|
|
@ -62,14 +41,9 @@ def setup_logging():
|
||||||
logger.remove()
|
logger.remove()
|
||||||
|
|
||||||
# 输出到控制台
|
# 输出到控制台
|
||||||
logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
|
logger.add(sys.stdout, format=log_format, level=log_level)
|
||||||
|
|
||||||
# 输出到文件
|
# 输出到文件
|
||||||
logger.add(
|
logger.add(os.path.join(log_dir, log_file), format=log_format_file, level=log_level)
|
||||||
os.path.join(log_dir, log_file),
|
|
||||||
format=log_format_file,
|
|
||||||
level=log_level,
|
|
||||||
filter=formatter,
|
|
||||||
)
|
|
||||||
|
|
||||||
return logger
|
return logger
|
||||||
|
|
|
||||||
241
main/xiaozhi-server/config/private_config.py
Normal file
241
main/xiaozhi-server/config/private_config.py
Normal file
|
|
@ -0,0 +1,241 @@
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import yaml
|
||||||
|
from config.logger import setup_logging
|
||||||
|
from typing import Dict, Any, Optional
|
||||||
|
from copy import deepcopy
|
||||||
|
from core.utils.util import get_project_dir
|
||||||
|
from core.utils import llm, tts
|
||||||
|
from core.utils.lock_manager import FileLockManager
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
class PrivateConfig:
|
||||||
|
def __init__(self, device_id: str, default_config: Dict[str, Any], auth_code_gen=None):
|
||||||
|
self.device_id = device_id
|
||||||
|
self.default_config = default_config
|
||||||
|
self.config_path = get_project_dir() + 'data/.private_config.yaml'
|
||||||
|
self.logger = setup_logging()
|
||||||
|
self.private_config = {}
|
||||||
|
self.auth_code_gen = auth_code_gen
|
||||||
|
self.lock_manager = FileLockManager()
|
||||||
|
|
||||||
|
async def load_or_create(self):
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
|
try:
|
||||||
|
if os.path.exists(self.config_path):
|
||||||
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
else:
|
||||||
|
all_configs = {}
|
||||||
|
|
||||||
|
if self.device_id not in all_configs:
|
||||||
|
# Get selected module names
|
||||||
|
selected_modules = self.default_config['selected_module']
|
||||||
|
selected_tts = selected_modules['TTS']
|
||||||
|
selected_llm = selected_modules['LLM']
|
||||||
|
selected_asr = selected_modules['ASR']
|
||||||
|
selected_vad = selected_modules['VAD']
|
||||||
|
|
||||||
|
# 生成认证码
|
||||||
|
auth_code = None
|
||||||
|
if self.auth_code_gen:
|
||||||
|
auth_code = self.auth_code_gen.generate_code()
|
||||||
|
|
||||||
|
# Initialize device config with only necessary configurations
|
||||||
|
device_config = {
|
||||||
|
'selected_module': deepcopy(selected_modules),
|
||||||
|
'prompt': self.default_config['prompt'],
|
||||||
|
'LLM': {
|
||||||
|
selected_llm: deepcopy(self.default_config['LLM'][selected_llm])
|
||||||
|
},
|
||||||
|
'TTS': {
|
||||||
|
selected_tts: deepcopy(self.default_config['TTS'][selected_tts])
|
||||||
|
},
|
||||||
|
'ASR': {
|
||||||
|
selected_asr: deepcopy(self.default_config['ASR'][selected_asr])
|
||||||
|
},
|
||||||
|
'VAD': {
|
||||||
|
selected_vad: deepcopy(self.default_config['VAD'][selected_vad])
|
||||||
|
},
|
||||||
|
'auth_code': auth_code # 添加认证码字段
|
||||||
|
}
|
||||||
|
|
||||||
|
all_configs[self.device_id] = device_config
|
||||||
|
|
||||||
|
# Save updated configs
|
||||||
|
with open(self.config_path, 'w', encoding='utf-8') as f:
|
||||||
|
yaml.dump(all_configs, f, allow_unicode=True)
|
||||||
|
|
||||||
|
self.private_config = all_configs[self.device_id]
|
||||||
|
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.config_path)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"Error handling private config: {e}")
|
||||||
|
self.private_config = {}
|
||||||
|
|
||||||
|
async def update_config(self, selected_modules: Dict[str, str], prompt: str, nickname: str) -> bool:
|
||||||
|
"""更新设备配置
|
||||||
|
Args:
|
||||||
|
selected_modules: 选择的模块配置,格式如 {'LLM': 'AliLLM', 'TTS': 'EdgeTTS',...}
|
||||||
|
prompt: 提示词配置
|
||||||
|
Returns:
|
||||||
|
bool: 更新是否成功
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
|
try:
|
||||||
|
# Read main config to get full module configurations
|
||||||
|
main_config = self.default_config
|
||||||
|
|
||||||
|
# Create new device config
|
||||||
|
device_config = {
|
||||||
|
'selected_module': selected_modules,
|
||||||
|
'prompt': prompt,
|
||||||
|
'nickname': nickname,
|
||||||
|
}
|
||||||
|
if self.private_config.get('last_chat_time'):
|
||||||
|
device_config['last_chat_time'] = self.private_config['last_chat_time']
|
||||||
|
if self.private_config.get('owner'):
|
||||||
|
device_config['owner'] = self.private_config['owner']
|
||||||
|
|
||||||
|
# Copy full module configurations from main config
|
||||||
|
for module_type, selected_name in selected_modules.items():
|
||||||
|
if selected_name and selected_name in main_config.get(module_type, {}):
|
||||||
|
device_config[module_type] = {
|
||||||
|
selected_name: main_config[module_type][selected_name]
|
||||||
|
}
|
||||||
|
|
||||||
|
# Read all configs
|
||||||
|
if os.path.exists(self.config_path):
|
||||||
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
else:
|
||||||
|
all_configs = {}
|
||||||
|
|
||||||
|
# Update device config
|
||||||
|
all_configs[self.device_id] = device_config
|
||||||
|
self.private_config = device_config
|
||||||
|
|
||||||
|
# Save back to file
|
||||||
|
with open(self.config_path, 'w', encoding='utf-8') as f:
|
||||||
|
yaml.dump(all_configs, f, allow_unicode=True)
|
||||||
|
|
||||||
|
return True
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.config_path)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"Error updating config: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def delete_config(self) -> bool:
|
||||||
|
"""删除设备配置
|
||||||
|
Returns:
|
||||||
|
bool: 删除是否成功
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
|
try:
|
||||||
|
# 读取所有配置
|
||||||
|
if os.path.exists(self.config_path):
|
||||||
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 删除设备配置
|
||||||
|
if self.device_id in all_configs:
|
||||||
|
del all_configs[self.device_id]
|
||||||
|
|
||||||
|
# 保存更新后的配置
|
||||||
|
with open(self.config_path, 'w', encoding='utf-8') as f:
|
||||||
|
yaml.dump(all_configs, f, allow_unicode=True)
|
||||||
|
|
||||||
|
self.private_config = {}
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.config_path)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"Error deleting config: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def create_private_instances(self):
|
||||||
|
# 判断存在私有配置,并且self.device_id在私有配置中
|
||||||
|
if not self.private_config:
|
||||||
|
self.logger.bind(tag=TAG).error("Private config not found for device_id: {}", self.device_id)
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
"""创建私有处理模块实例"""
|
||||||
|
config = self.private_config
|
||||||
|
selected_modules = config['selected_module']
|
||||||
|
return (
|
||||||
|
llm.create_instance(
|
||||||
|
selected_modules["LLM"]
|
||||||
|
if not 'type' in config["LLM"][selected_modules["LLM"]]
|
||||||
|
else
|
||||||
|
config["LLM"][selected_modules["LLM"]]['type'],
|
||||||
|
config["LLM"][selected_modules["LLM"]],
|
||||||
|
),
|
||||||
|
tts.create_instance(
|
||||||
|
selected_modules["TTS"]
|
||||||
|
if not 'type' in config["TTS"][selected_modules["TTS"]]
|
||||||
|
else
|
||||||
|
config["TTS"][selected_modules["TTS"]]["type"],
|
||||||
|
config["TTS"][selected_modules["TTS"]],
|
||||||
|
self.default_config.get("delete_audio", True) # Using default_config for global settings
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def update_last_chat_time(self, timestamp=None):
|
||||||
|
"""更新设备最近一次的聊天时间
|
||||||
|
Args:
|
||||||
|
timestamp: 指定的时间戳,不传则使用当前时间
|
||||||
|
"""
|
||||||
|
if not self.private_config:
|
||||||
|
self.logger.bind(tag=TAG).error("Private config not found")
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
await self.lock_manager.acquire_lock(self.config_path)
|
||||||
|
try:
|
||||||
|
if timestamp is None:
|
||||||
|
timestamp = int(time.time())
|
||||||
|
|
||||||
|
self.private_config['last_chat_time'] = timestamp
|
||||||
|
|
||||||
|
# 读取所有配置
|
||||||
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
|
all_configs = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
|
# 更新当前设备配置
|
||||||
|
all_configs[self.device_id] = self.private_config
|
||||||
|
|
||||||
|
# 保存回文件
|
||||||
|
with open(self.config_path, 'w', encoding='utf-8') as f:
|
||||||
|
yaml.dump(all_configs, f, allow_unicode=True)
|
||||||
|
|
||||||
|
return True
|
||||||
|
finally:
|
||||||
|
self.lock_manager.release_lock(self.config_path)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"Error updating last chat time: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_auth_code(self) -> str:
|
||||||
|
"""获取设备的认证码
|
||||||
|
Returns:
|
||||||
|
str: 认证码,如果没有返回空字符串
|
||||||
|
"""
|
||||||
|
return self.private_config.get('auth_code', '')
|
||||||
|
|
||||||
|
def get_owner(self) -> Optional[str]:
|
||||||
|
"""获取设备当前所有者"""
|
||||||
|
return self.private_config.get('owner')
|
||||||
|
|
@ -1,11 +1,82 @@
|
||||||
import os
|
import os
|
||||||
|
import argparse
|
||||||
|
from ruamel.yaml import YAML
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from config.config_loader import read_config, get_project_dir, load_config
|
from core.utils.util import read_config, get_project_dir
|
||||||
|
|
||||||
default_config_file = "config.yaml"
|
default_config_file = "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
def find_missing_keys(new_config, old_config, parent_key=""):
|
def ensure_directories(config):
|
||||||
|
"""确保所有配置路径存在"""
|
||||||
|
dirs_to_create = set()
|
||||||
|
project_dir = get_project_dir() # 获取项目根目录
|
||||||
|
# 日志文件目录
|
||||||
|
log_dir = config.get('log', {}).get('log_dir', 'tmp')
|
||||||
|
dirs_to_create.add(os.path.join(project_dir, log_dir))
|
||||||
|
|
||||||
|
# ASR/TTS模块输出目录
|
||||||
|
for module in ['ASR', 'TTS']:
|
||||||
|
for provider in config.get(module, {}).values():
|
||||||
|
output_dir = provider.get('output_dir', '')
|
||||||
|
if output_dir:
|
||||||
|
dirs_to_create.add(output_dir)
|
||||||
|
|
||||||
|
# 根据selected_module创建模型目录
|
||||||
|
selected_modules = config.get('selected_module', {})
|
||||||
|
for module_type in ['ASR', 'LLM', 'TTS']:
|
||||||
|
selected_provider = selected_modules.get(module_type)
|
||||||
|
if not selected_provider:
|
||||||
|
continue
|
||||||
|
provider_config = config.get(module_type, {}).get(selected_provider, {})
|
||||||
|
output_dir = provider_config.get('output_dir')
|
||||||
|
if output_dir:
|
||||||
|
full_model_dir = os.path.join(project_dir, output_dir)
|
||||||
|
dirs_to_create.add(full_model_dir)
|
||||||
|
|
||||||
|
# 统一创建目录(保留原data目录创建)
|
||||||
|
for dir_path in dirs_to_create:
|
||||||
|
try:
|
||||||
|
os.makedirs(dir_path, exist_ok=True)
|
||||||
|
except PermissionError:
|
||||||
|
print(f"警告:无法创建目录 {dir_path},请检查写入权限")
|
||||||
|
|
||||||
|
|
||||||
|
def get_config_file():
|
||||||
|
global default_config_file
|
||||||
|
"""获取配置文件路径,优先使用私有配置文件(若存在)。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 配置文件路径(相对路径或默认路径)
|
||||||
|
"""
|
||||||
|
config_file = default_config_file
|
||||||
|
if os.path.exists(get_project_dir() + "data/." + default_config_file):
|
||||||
|
config_file = "data/." + default_config_file
|
||||||
|
return config_file
|
||||||
|
|
||||||
|
|
||||||
|
def load_config():
|
||||||
|
"""加载配置文件"""
|
||||||
|
parser = argparse.ArgumentParser(description="Server configuration")
|
||||||
|
config_file = get_config_file()
|
||||||
|
|
||||||
|
parser.add_argument("--config_path", type=str, default=config_file)
|
||||||
|
args = parser.parse_args()
|
||||||
|
config = read_config(args.config_path)
|
||||||
|
# 初始化目录
|
||||||
|
ensure_directories(config)
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
def update_config(config):
|
||||||
|
yaml = YAML()
|
||||||
|
yaml.preserve_quotes = True
|
||||||
|
"""将配置保存到YAML文件"""
|
||||||
|
with open(get_config_file(), 'w') as f:
|
||||||
|
yaml.dump(config, f)
|
||||||
|
|
||||||
|
|
||||||
|
def find_missing_keys(new_config, old_config, parent_key=''):
|
||||||
"""
|
"""
|
||||||
递归查找缺失的配置项
|
递归查找缺失的配置项
|
||||||
返回格式:[缺失配置路径]
|
返回格式:[缺失配置路径]
|
||||||
|
|
@ -27,28 +98,28 @@ def find_missing_keys(new_config, old_config, parent_key=""):
|
||||||
# 递归检查嵌套字典
|
# 递归检查嵌套字典
|
||||||
if isinstance(value, Mapping):
|
if isinstance(value, Mapping):
|
||||||
sub_missing = find_missing_keys(
|
sub_missing = find_missing_keys(
|
||||||
value, old_config[key], parent_key=full_path
|
value,
|
||||||
|
old_config[key],
|
||||||
|
parent_key=full_path
|
||||||
)
|
)
|
||||||
missing_keys.extend(sub_missing)
|
missing_keys.extend(sub_missing)
|
||||||
|
|
||||||
return missing_keys
|
return missing_keys
|
||||||
|
|
||||||
|
|
||||||
def check_config_file():
|
def check_config_file():
|
||||||
old_config_file = get_project_dir() + "data/." + default_config_file
|
old_config_file = get_config_file()
|
||||||
if not os.path.exists(old_config_file):
|
global default_config_file
|
||||||
|
if not 'data' in old_config_file:
|
||||||
return
|
return
|
||||||
old_config = load_config()
|
old_config = read_config(get_project_dir() + old_config_file)
|
||||||
new_config = read_config(get_project_dir() + default_config_file)
|
new_config = read_config(get_project_dir() + default_config_file)
|
||||||
# 查找缺失的配置项
|
# 查找缺失的配置项
|
||||||
missing_keys = find_missing_keys(new_config, old_config)
|
missing_keys = find_missing_keys(new_config, old_config)
|
||||||
read_config_from_api = old_config.get("read_config_from_api", False)
|
|
||||||
if read_config_from_api:
|
|
||||||
return
|
|
||||||
|
|
||||||
if missing_keys:
|
if missing_keys:
|
||||||
missing_keys_str = "\n".join(f"- {key}" for key in missing_keys)
|
|
||||||
error_msg = "您的配置文件太旧了,缺少了:\n"
|
error_msg = "您的配置文件太旧了,缺少了:\n"
|
||||||
error_msg += missing_keys_str
|
error_msg += "\n".join(f"- {key}" for key in missing_keys)
|
||||||
error_msg += "\n建议您:\n"
|
error_msg += "\n建议您:\n"
|
||||||
error_msg += "1、备份data/.config.yaml文件\n"
|
error_msg += "1、备份data/.config.yaml文件\n"
|
||||||
error_msg += "2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n"
|
error_msg += "2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n"
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import os
|
import os
|
||||||
import copy
|
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
import time
|
import time
|
||||||
|
|
@ -18,17 +17,16 @@ from core.utils.util import (
|
||||||
get_string_no_punctuation_or_emoji,
|
get_string_no_punctuation_or_emoji,
|
||||||
extract_json_from_string,
|
extract_json_from_string,
|
||||||
get_ip_info,
|
get_ip_info,
|
||||||
initialize_modules,
|
|
||||||
)
|
)
|
||||||
from concurrent.futures import ThreadPoolExecutor, TimeoutError
|
from concurrent.futures import ThreadPoolExecutor, TimeoutError
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage
|
from core.handle.sendAudioHandle import sendAudioMessage
|
||||||
from core.handle.receiveAudioHandle import handleAudioMessage
|
from core.handle.receiveAudioHandle import handleAudioMessage
|
||||||
from core.handle.functionHandler import FunctionHandler
|
from core.handle.functionHandler import FunctionHandler
|
||||||
from plugins_func.register import Action, ActionResponse
|
from plugins_func.register import Action, ActionResponse
|
||||||
|
from config.private_config import PrivateConfig
|
||||||
from core.auth import AuthMiddleware, AuthenticationError
|
from core.auth import AuthMiddleware, AuthenticationError
|
||||||
|
from core.utils.auth_code_gen import AuthCodeGenerator
|
||||||
from core.mcp.manager import MCPManager
|
from core.mcp.manager import MCPManager
|
||||||
from config.config_loader import get_private_config_from_api
|
|
||||||
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
@ -43,13 +41,10 @@ class ConnectionHandler:
|
||||||
def __init__(
|
def __init__(
|
||||||
self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent
|
self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent
|
||||||
):
|
):
|
||||||
self.config = copy.deepcopy(config)
|
self.config = config
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
self.auth = AuthMiddleware(config)
|
self.auth = AuthMiddleware(config)
|
||||||
|
|
||||||
self.need_bind = False
|
|
||||||
self.bind_code = None
|
|
||||||
|
|
||||||
self.websocket = None
|
self.websocket = None
|
||||||
self.headers = None
|
self.headers = None
|
||||||
self.client_ip = None
|
self.client_ip = None
|
||||||
|
|
@ -100,45 +95,24 @@ class ConnectionHandler:
|
||||||
self.iot_descriptors = {}
|
self.iot_descriptors = {}
|
||||||
self.func_handler = None
|
self.func_handler = None
|
||||||
|
|
||||||
self.cmd_exit = self.config["exit_commands"]
|
self.cmd_exit = self.config["CMD_exit"]
|
||||||
self.max_cmd_length = 0
|
self.max_cmd_length = 0
|
||||||
for cmd in self.cmd_exit:
|
for cmd in self.cmd_exit:
|
||||||
if len(cmd) > self.max_cmd_length:
|
if len(cmd) > self.max_cmd_length:
|
||||||
self.max_cmd_length = len(cmd)
|
self.max_cmd_length = len(cmd)
|
||||||
|
|
||||||
|
self.private_config = None
|
||||||
|
self.auth_code_gen = AuthCodeGenerator.get_instance()
|
||||||
|
self.is_device_verified = False # 添加设备验证状态标志
|
||||||
self.close_after_chat = False # 是否在聊天结束后关闭连接
|
self.close_after_chat = False # 是否在聊天结束后关闭连接
|
||||||
self.use_function_call_mode = False
|
self.use_function_call_mode = False
|
||||||
|
if self.config["selected_module"]["Intent"] == "function_call":
|
||||||
self.timeout_task = None
|
self.use_function_call_mode = True
|
||||||
self.timeout_seconds = (
|
|
||||||
int(self.config.get("close_connection_no_voice_time", 120)) + 60
|
|
||||||
) # 在原来第一道关闭的基础上加60秒,进行二道关闭
|
|
||||||
|
|
||||||
async def handle_connection(self, ws):
|
async def handle_connection(self, ws):
|
||||||
try:
|
try:
|
||||||
# 获取并验证headers
|
# 获取并验证headers
|
||||||
self.headers = dict(ws.request.headers)
|
self.headers = dict(ws.request.headers)
|
||||||
|
|
||||||
if self.headers.get("device-id", None) is None:
|
|
||||||
# 尝试从 URL 的查询参数中获取 device-id
|
|
||||||
from urllib.parse import parse_qs, urlparse
|
|
||||||
|
|
||||||
# 从 WebSocket 请求中获取路径
|
|
||||||
request_path = ws.request.path
|
|
||||||
if not request_path:
|
|
||||||
self.logger.bind(tag=TAG).error("无法获取请求路径")
|
|
||||||
return
|
|
||||||
parsed_url = urlparse(request_path)
|
|
||||||
query_params = parse_qs(parsed_url.query)
|
|
||||||
if "device-id" in query_params:
|
|
||||||
self.headers["device-id"] = query_params["device-id"][0]
|
|
||||||
self.headers["client-id"] = query_params["client-id"][0]
|
|
||||||
else:
|
|
||||||
self.logger.bind(tag=TAG).error(
|
|
||||||
"无法从请求头和URL查询参数中获取device-id"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
# 获取客户端ip地址
|
# 获取客户端ip地址
|
||||||
self.client_ip = ws.remote_address[0]
|
self.client_ip = ws.remote_address[0]
|
||||||
self.logger.bind(tag=TAG).info(
|
self.logger.bind(tag=TAG).info(
|
||||||
|
|
@ -147,22 +121,51 @@ class ConnectionHandler:
|
||||||
|
|
||||||
# 进行认证
|
# 进行认证
|
||||||
await self.auth.authenticate(self.headers)
|
await self.auth.authenticate(self.headers)
|
||||||
|
device_id = self.headers.get("device-id", None)
|
||||||
|
|
||||||
# 认证通过,继续处理
|
# 认证通过,继续处理
|
||||||
self.websocket = ws
|
self.websocket = ws
|
||||||
self.session_id = str(uuid.uuid4())
|
self.session_id = str(uuid.uuid4())
|
||||||
|
|
||||||
# 启动超时检查任务
|
|
||||||
self.timeout_task = asyncio.create_task(self._check_timeout())
|
|
||||||
|
|
||||||
self.welcome_msg = self.config["xiaozhi"]
|
self.welcome_msg = self.config["xiaozhi"]
|
||||||
self.welcome_msg["session_id"] = self.session_id
|
self.welcome_msg["session_id"] = self.session_id
|
||||||
await self.websocket.send(json.dumps(self.welcome_msg))
|
await self.websocket.send(json.dumps(self.welcome_msg))
|
||||||
|
# Load private configuration if device_id is provided
|
||||||
|
bUsePrivateConfig = self.config.get("use_private_config", False)
|
||||||
|
if bUsePrivateConfig and device_id:
|
||||||
|
try:
|
||||||
|
self.private_config = PrivateConfig(
|
||||||
|
device_id, self.config, self.auth_code_gen
|
||||||
|
)
|
||||||
|
await self.private_config.load_or_create()
|
||||||
|
# 判断是否已经绑定
|
||||||
|
owner = self.private_config.get_owner()
|
||||||
|
self.is_device_verified = owner is not None
|
||||||
|
|
||||||
|
if self.is_device_verified:
|
||||||
|
await self.private_config.update_last_chat_time()
|
||||||
|
|
||||||
|
llm, tts = self.private_config.create_private_instances()
|
||||||
|
if all([llm, tts]):
|
||||||
|
self.llm = llm
|
||||||
|
self.tts = tts
|
||||||
|
self.logger.bind(tag=TAG).info(
|
||||||
|
f"Loaded private config and instances for device {device_id}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.logger.bind(tag=TAG).error(
|
||||||
|
f"Failed to create instances for device {device_id}"
|
||||||
|
)
|
||||||
|
self.private_config = None
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(
|
||||||
|
f"Error initializing private config: {e}"
|
||||||
|
)
|
||||||
|
self.private_config = None
|
||||||
|
raise
|
||||||
|
|
||||||
# 获取差异化配置
|
|
||||||
private_config = self._initialize_private_config()
|
|
||||||
# 异步初始化
|
# 异步初始化
|
||||||
self.executor.submit(self._initialize_components, private_config)
|
self.executor.submit(self._initialize_components)
|
||||||
# tts 消化线程
|
# tts 消化线程
|
||||||
self.tts_priority_thread = threading.Thread(
|
self.tts_priority_thread = threading.Thread(
|
||||||
target=self._tts_priority_thread, daemon=True
|
target=self._tts_priority_thread, daemon=True
|
||||||
|
|
@ -202,183 +205,47 @@ class ConnectionHandler:
|
||||||
|
|
||||||
async def _route_message(self, message):
|
async def _route_message(self, message):
|
||||||
"""消息路由"""
|
"""消息路由"""
|
||||||
# 重置超时计时器
|
|
||||||
if self.timeout_task:
|
|
||||||
self.timeout_task.cancel()
|
|
||||||
self.timeout_task = asyncio.create_task(self._check_timeout())
|
|
||||||
|
|
||||||
if isinstance(message, str):
|
if isinstance(message, str):
|
||||||
await handleTextMessage(self, message)
|
await handleTextMessage(self, message)
|
||||||
elif isinstance(message, bytes):
|
elif isinstance(message, bytes):
|
||||||
await handleAudioMessage(self, message)
|
await handleAudioMessage(self, message)
|
||||||
|
|
||||||
def _initialize_components(self, private_config):
|
def _initialize_components(self):
|
||||||
"""初始化组件"""
|
"""加载提示词"""
|
||||||
if private_config is not None:
|
|
||||||
self._initialize_models(private_config)
|
|
||||||
else:
|
|
||||||
self.prompt = self.config["prompt"]
|
self.prompt = self.config["prompt"]
|
||||||
self.change_system_prompt(self.prompt)
|
if self.private_config:
|
||||||
|
self.prompt = self.private_config.private_config.get("prompt", self.prompt)
|
||||||
|
self.dialogue.put(Message(role="system", content=self.prompt))
|
||||||
|
|
||||||
"""加载记忆"""
|
"""加载记忆"""
|
||||||
self._initialize_memory()
|
self._initialize_memory()
|
||||||
"""加载意图识别"""
|
"""加载意图识别"""
|
||||||
self._initialize_intent()
|
self._initialize_intent()
|
||||||
"""加载位置信息"""
|
"""加载位置信息"""
|
||||||
self.client_ip_info = get_ip_info(self.client_ip, self.logger)
|
self.client_ip_info = get_ip_info(self.client_ip)
|
||||||
if self.client_ip_info is not None and "city" in self.client_ip_info:
|
if self.client_ip_info is not None and "city" in self.client_ip_info:
|
||||||
self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
|
self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
|
||||||
self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}"
|
self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}"
|
||||||
|
|
||||||
self.dialogue.update_system_message(self.prompt)
|
self.dialogue.update_system_message(self.prompt)
|
||||||
|
|
||||||
def _initialize_private_config(self):
|
|
||||||
read_config_from_api = self.config.get("read_config_from_api", False)
|
|
||||||
"""如果是从配置文件获取,则进行二次实例化"""
|
|
||||||
if not read_config_from_api:
|
|
||||||
return
|
|
||||||
"""从接口获取差异化的配置进行二次实例化,非全量重新实例化"""
|
|
||||||
try:
|
|
||||||
begin_time = time.time()
|
|
||||||
private_config = get_private_config_from_api(
|
|
||||||
self.config,
|
|
||||||
self.headers.get("device-id", None),
|
|
||||||
self.headers.get("client-id", None),
|
|
||||||
)
|
|
||||||
private_config["delete_audio"] = bool(self.config.get("delete_audio", True))
|
|
||||||
self.logger.bind(tag=TAG).info(
|
|
||||||
f"{time.time() - begin_time} 秒,获取差异化配置成功: {private_config}"
|
|
||||||
)
|
|
||||||
except DeviceNotFoundException as e:
|
|
||||||
self.need_bind = True
|
|
||||||
private_config = {}
|
|
||||||
except DeviceBindException as e:
|
|
||||||
self.need_bind = True
|
|
||||||
self.bind_code = e.bind_code
|
|
||||||
private_config = {}
|
|
||||||
except Exception as e:
|
|
||||||
self.need_bind = True
|
|
||||||
self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
|
|
||||||
private_config = {}
|
|
||||||
|
|
||||||
init_tts = False
|
|
||||||
if private_config.get("TTS", None) is not None:
|
|
||||||
init_tts = True
|
|
||||||
self.config["TTS"] = private_config["TTS"]
|
|
||||||
self.config["selected_module"]["TTS"] = private_config["selected_module"][
|
|
||||||
"TTS"
|
|
||||||
]
|
|
||||||
|
|
||||||
try:
|
|
||||||
modules = initialize_modules(
|
|
||||||
self.logger,
|
|
||||||
private_config,
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
init_tts,
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
|
|
||||||
modules = {}
|
|
||||||
if modules.get("tts", None) is not None:
|
|
||||||
self.tts = modules["tts"]
|
|
||||||
if modules.get("prompt", None) is not None:
|
|
||||||
self.change_system_prompt(modules["prompt"])
|
|
||||||
private_config["prompt"] = None
|
|
||||||
return private_config
|
|
||||||
|
|
||||||
def _initialize_models(self, private_config):
|
|
||||||
init_vad, init_asr, init_llm, init_memory, init_intent = (
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
)
|
|
||||||
if private_config.get("VAD", None) is not None:
|
|
||||||
init_vad = True
|
|
||||||
self.config["VAD"] = private_config["VAD"]
|
|
||||||
self.config["selected_module"]["VAD"] = private_config["selected_module"][
|
|
||||||
"VAD"
|
|
||||||
]
|
|
||||||
if private_config.get("ASR", None) is not None:
|
|
||||||
init_asr = True
|
|
||||||
self.config["ASR"] = private_config["ASR"]
|
|
||||||
self.config["selected_module"]["ASR"] = private_config["selected_module"][
|
|
||||||
"ASR"
|
|
||||||
]
|
|
||||||
if private_config.get("LLM", None) is not None:
|
|
||||||
init_llm = True
|
|
||||||
self.config["LLM"] = private_config["LLM"]
|
|
||||||
self.config["selected_module"]["LLM"] = private_config["selected_module"][
|
|
||||||
"LLM"
|
|
||||||
]
|
|
||||||
|
|
||||||
if private_config.get("Memory", None) is not None:
|
|
||||||
init_memory = True
|
|
||||||
self.config["Memory"] = private_config["Memory"]
|
|
||||||
self.config["selected_module"]["Memory"] = private_config[
|
|
||||||
"selected_module"
|
|
||||||
]["Memory"]
|
|
||||||
if private_config.get("Intent", None) is not None:
|
|
||||||
init_intent = True
|
|
||||||
self.config["Intent"] = private_config["Intent"]
|
|
||||||
self.config["selected_module"]["Intent"] = private_config[
|
|
||||||
"selected_module"
|
|
||||||
]["Intent"]
|
|
||||||
try:
|
|
||||||
modules = initialize_modules(
|
|
||||||
self.logger,
|
|
||||||
private_config,
|
|
||||||
init_vad,
|
|
||||||
init_asr,
|
|
||||||
init_llm,
|
|
||||||
False,
|
|
||||||
init_memory,
|
|
||||||
init_intent,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
|
|
||||||
modules = {}
|
|
||||||
if modules.get("vad", None) is not None:
|
|
||||||
self.vad = modules["vad"]
|
|
||||||
if modules.get("asr", None) is not None:
|
|
||||||
self.asr = modules["asr"]
|
|
||||||
if modules.get("llm", None) is not None:
|
|
||||||
self.llm = modules["llm"]
|
|
||||||
if modules.get("intent", None) is not None:
|
|
||||||
self.intent = modules["intent"]
|
|
||||||
if modules.get("memory", None) is not None:
|
|
||||||
self.memory = modules["memory"]
|
|
||||||
|
|
||||||
def _initialize_memory(self):
|
def _initialize_memory(self):
|
||||||
"""初始化记忆模块"""
|
"""初始化记忆模块"""
|
||||||
device_id = self.headers.get("device-id", None)
|
device_id = self.headers.get("device-id", None)
|
||||||
self.memory.init_memory(device_id, self.llm)
|
self.memory.init_memory(device_id, self.llm)
|
||||||
|
|
||||||
def _initialize_intent(self):
|
def _initialize_intent(self):
|
||||||
if (
|
|
||||||
self.config["Intent"][self.config["selected_module"]["Intent"]]["type"]
|
|
||||||
== "function_call"
|
|
||||||
):
|
|
||||||
self.use_function_call_mode = True
|
|
||||||
"""初始化意图识别模块"""
|
"""初始化意图识别模块"""
|
||||||
# 获取意图识别配置
|
# 获取意图识别配置
|
||||||
intent_config = self.config["Intent"]
|
intent_config = self.config["Intent"]
|
||||||
intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][
|
intent_type = self.config["selected_module"]["Intent"]
|
||||||
"type"
|
|
||||||
]
|
|
||||||
|
|
||||||
# 如果使用 nointent,直接返回
|
# 如果使用 nointent,直接返回
|
||||||
if intent_type == "nointent":
|
if intent_type == "nointent":
|
||||||
return
|
return
|
||||||
# 使用 intent_llm 模式
|
# 使用 intent_llm 模式
|
||||||
elif intent_type == "intent_llm":
|
elif intent_type == "intent_llm":
|
||||||
intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][
|
intent_llm_name = intent_config["intent_llm"]["llm"]
|
||||||
"llm"
|
|
||||||
]
|
|
||||||
|
|
||||||
if intent_llm_name and intent_llm_name in self.config["LLM"]:
|
if intent_llm_name and intent_llm_name in self.config["LLM"]:
|
||||||
# 如果配置了专用LLM,则创建独立的LLM实例
|
# 如果配置了专用LLM,则创建独立的LLM实例
|
||||||
|
|
@ -409,16 +276,46 @@ class ConnectionHandler:
|
||||||
|
|
||||||
def change_system_prompt(self, prompt):
|
def change_system_prompt(self, prompt):
|
||||||
self.prompt = prompt
|
self.prompt = prompt
|
||||||
# 更新系统prompt至上下文
|
# 找到原来的role==system,替换原来的系统提示
|
||||||
self.dialogue.update_system_message(self.prompt)
|
for m in self.dialogue.dialogue:
|
||||||
|
if m.role == "system":
|
||||||
|
m.content = prompt
|
||||||
|
|
||||||
|
async def _check_and_broadcast_auth_code(self):
|
||||||
|
"""检查设备绑定状态并广播认证码"""
|
||||||
|
if not self.private_config.get_owner():
|
||||||
|
auth_code = self.private_config.get_auth_code()
|
||||||
|
if auth_code:
|
||||||
|
# 发送验证码语音提示
|
||||||
|
text = f"请在后台输入验证码:{' '.join(auth_code)}"
|
||||||
|
self.recode_first_last_text(text)
|
||||||
|
future = self.executor.submit(self.speak_and_play, text)
|
||||||
|
self.tts_queue.put(future)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def isNeedAuth(self):
|
||||||
|
bUsePrivateConfig = self.config.get("use_private_config", False)
|
||||||
|
if not bUsePrivateConfig:
|
||||||
|
# 如果不使用私有配置,就不需要验证
|
||||||
|
return False
|
||||||
|
return not self.is_device_verified
|
||||||
|
|
||||||
def chat(self, query):
|
def chat(self, query):
|
||||||
|
if self.isNeedAuth():
|
||||||
|
self.llm_finish_task = True
|
||||||
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
|
self._check_and_broadcast_auth_code(), self.loop
|
||||||
|
)
|
||||||
|
future.result()
|
||||||
|
return True
|
||||||
|
|
||||||
self.dialogue.put(Message(role="user", content=query))
|
self.dialogue.put(Message(role="user", content=query))
|
||||||
|
|
||||||
response_message = []
|
response_message = []
|
||||||
processed_chars = 0 # 跟踪已处理的字符位置
|
processed_chars = 0 # 跟踪已处理的字符位置
|
||||||
try:
|
try:
|
||||||
|
start_time = time.time()
|
||||||
# 使用带记忆的对话
|
# 使用带记忆的对话
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.memory.query_memory(query), self.loop
|
self.memory.query_memory(query), self.loop
|
||||||
|
|
@ -440,6 +337,9 @@ class ConnectionHandler:
|
||||||
if self.client_abort:
|
if self.client_abort:
|
||||||
break
|
break
|
||||||
|
|
||||||
|
end_time = time.time()
|
||||||
|
# self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}")
|
||||||
|
|
||||||
# 合并当前全部文本并处理未分割部分
|
# 合并当前全部文本并处理未分割部分
|
||||||
full_text = "".join(response_message)
|
full_text = "".join(response_message)
|
||||||
current_text = full_text[processed_chars:] # 从未处理的位置开始
|
current_text = full_text[processed_chars:] # 从未处理的位置开始
|
||||||
|
|
@ -491,6 +391,13 @@ class ConnectionHandler:
|
||||||
def chat_with_function_calling(self, query, tool_call=False):
|
def chat_with_function_calling(self, query, tool_call=False):
|
||||||
self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}")
|
self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}")
|
||||||
"""Chat with function calling for intent detection using streaming"""
|
"""Chat with function calling for intent detection using streaming"""
|
||||||
|
if self.isNeedAuth():
|
||||||
|
self.llm_finish_task = True
|
||||||
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
|
self._check_and_broadcast_auth_code(), self.loop
|
||||||
|
)
|
||||||
|
future.result()
|
||||||
|
return True
|
||||||
|
|
||||||
if not tool_call:
|
if not tool_call:
|
||||||
self.dialogue.put(Message(role="user", content=query))
|
self.dialogue.put(Message(role="user", content=query))
|
||||||
|
|
@ -532,18 +439,15 @@ class ConnectionHandler:
|
||||||
function_id = None
|
function_id = None
|
||||||
function_arguments = ""
|
function_arguments = ""
|
||||||
content_arguments = ""
|
content_arguments = ""
|
||||||
|
|
||||||
for response in llm_responses:
|
for response in llm_responses:
|
||||||
content, tools_call = response
|
content, tools_call = response
|
||||||
|
|
||||||
if "content" in response:
|
if "content" in response:
|
||||||
content = response["content"]
|
content = response["content"]
|
||||||
tools_call = None
|
tools_call = None
|
||||||
if content is not None and len(content) > 0:
|
if content is not None and len(content) > 0:
|
||||||
content_arguments += content
|
if len(response_message) <= 0 and (
|
||||||
|
content == "```" or "<tool_call>" in content
|
||||||
if not tool_call_flag and content_arguments.startswith("<tool_call>"):
|
):
|
||||||
# print("content_arguments", content_arguments)
|
|
||||||
tool_call_flag = True
|
tool_call_flag = True
|
||||||
|
|
||||||
if tools_call is not None:
|
if tools_call is not None:
|
||||||
|
|
@ -556,7 +460,9 @@ class ConnectionHandler:
|
||||||
function_arguments += tools_call[0].function.arguments
|
function_arguments += tools_call[0].function.arguments
|
||||||
|
|
||||||
if content is not None and len(content) > 0:
|
if content is not None and len(content) > 0:
|
||||||
if not tool_call_flag:
|
if tool_call_flag:
|
||||||
|
content_arguments += content
|
||||||
|
else:
|
||||||
response_message.append(content)
|
response_message.append(content)
|
||||||
|
|
||||||
if self.client_abort:
|
if self.client_abort:
|
||||||
|
|
@ -617,8 +523,9 @@ class ConnectionHandler:
|
||||||
self.logger.bind(tag=TAG).error(
|
self.logger.bind(tag=TAG).error(
|
||||||
f"function call error: {content_arguments}"
|
f"function call error: {content_arguments}"
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
function_arguments = json.loads(function_arguments)
|
||||||
if not bHasError:
|
if not bHasError:
|
||||||
response_message.clear()
|
|
||||||
self.logger.bind(tag=TAG).info(
|
self.logger.bind(tag=TAG).info(
|
||||||
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
|
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
|
||||||
)
|
)
|
||||||
|
|
@ -714,6 +621,7 @@ class ConnectionHandler:
|
||||||
self.tts_queue.put(future)
|
self.tts_queue.put(future)
|
||||||
self.dialogue.put(Message(role="assistant", content=text))
|
self.dialogue.put(Message(role="assistant", content=text))
|
||||||
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
|
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
|
||||||
|
|
||||||
text = result.result
|
text = result.result
|
||||||
if text is not None and len(text) > 0:
|
if text is not None and len(text) > 0:
|
||||||
function_id = function_call_data["id"]
|
function_id = function_call_data["id"]
|
||||||
|
|
@ -740,14 +648,18 @@ class ConnectionHandler:
|
||||||
Message(role="tool", tool_call_id=function_id, content=text)
|
Message(role="tool", tool_call_id=function_id, content=text)
|
||||||
)
|
)
|
||||||
self.chat_with_function_calling(text, tool_call=True)
|
self.chat_with_function_calling(text, tool_call=True)
|
||||||
elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
|
elif result.action == Action.NOTFOUND:
|
||||||
text = result.result
|
text = result.result
|
||||||
self.recode_first_last_text(text, text_index)
|
self.recode_first_last_text(text, text_index)
|
||||||
future = self.executor.submit(self.speak_and_play, text, text_index)
|
future = self.executor.submit(self.speak_and_play, text, text_index)
|
||||||
self.tts_queue.put(future)
|
self.tts_queue.put(future)
|
||||||
self.dialogue.put(Message(role="assistant", content=text))
|
self.dialogue.put(Message(role="assistant", content=text))
|
||||||
else:
|
else:
|
||||||
pass
|
text = result.result
|
||||||
|
self.recode_first_last_text(text, text_index)
|
||||||
|
future = self.executor.submit(self.speak_and_play, text, text_index)
|
||||||
|
self.tts_queue.put(future)
|
||||||
|
self.dialogue.put(Message(role="assistant", content=text))
|
||||||
|
|
||||||
def _tts_priority_thread(self):
|
def _tts_priority_thread(self):
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
|
|
@ -765,7 +677,7 @@ class ConnectionHandler:
|
||||||
opus_datas, text_index, tts_file = [], 0, None
|
opus_datas, text_index, tts_file = [], 0, None
|
||||||
try:
|
try:
|
||||||
self.logger.bind(tag=TAG).debug("正在处理TTS任务...")
|
self.logger.bind(tag=TAG).debug("正在处理TTS任务...")
|
||||||
tts_timeout = int(self.config.get("tts_timeout", 10))
|
tts_timeout = self.config.get("tts_timeout", 10)
|
||||||
tts_file, text, text_index = future.result(timeout=tts_timeout)
|
tts_file, text, text_index = future.result(timeout=tts_timeout)
|
||||||
if text is None or len(text) <= 0:
|
if text is None or len(text) <= 0:
|
||||||
self.logger.bind(tag=TAG).error(
|
self.logger.bind(tag=TAG).error(
|
||||||
|
|
@ -861,11 +773,6 @@ class ConnectionHandler:
|
||||||
|
|
||||||
async def close(self, ws=None):
|
async def close(self, ws=None):
|
||||||
"""资源清理方法"""
|
"""资源清理方法"""
|
||||||
# 取消超时任务
|
|
||||||
if self.timeout_task:
|
|
||||||
self.timeout_task.cancel()
|
|
||||||
self.timeout_task = None
|
|
||||||
|
|
||||||
# 清理MCP资源
|
# 清理MCP资源
|
||||||
if hasattr(self, "mcp_manager") and self.mcp_manager:
|
if hasattr(self, "mcp_manager") and self.mcp_manager:
|
||||||
await self.mcp_manager.cleanup_all()
|
await self.mcp_manager.cleanup_all()
|
||||||
|
|
@ -919,15 +826,3 @@ class ConnectionHandler:
|
||||||
self.close_after_chat = True
|
self.close_after_chat = True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
|
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
|
||||||
|
|
||||||
async def _check_timeout(self):
|
|
||||||
"""检查连接超时"""
|
|
||||||
try:
|
|
||||||
while not self.stop_event.is_set():
|
|
||||||
await asyncio.sleep(self.timeout_seconds)
|
|
||||||
if not self.stop_event.is_set():
|
|
||||||
self.logger.bind(tag=TAG).info("连接超时,准备关闭")
|
|
||||||
await self.close(self.websocket)
|
|
||||||
break
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
|
|
||||||
|
|
|
||||||
|
|
@ -57,9 +57,7 @@ class FunctionHandler:
|
||||||
|
|
||||||
def register_config_functions(self):
|
def register_config_functions(self):
|
||||||
"""注册配置中的函数,可以不同客户端使用不同的配置"""
|
"""注册配置中的函数,可以不同客户端使用不同的配置"""
|
||||||
for func in self.config["Intent"][self.config["selected_module"]["Intent"]].get(
|
for func in self.config["Intent"]["function_call"].get("functions", []):
|
||||||
"functions", []
|
|
||||||
):
|
|
||||||
self.function_registry.register_function(func)
|
self.function_registry.register_function(func)
|
||||||
|
|
||||||
"""home assistant需要初始化提示词"""
|
"""home assistant需要初始化提示词"""
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ import os
|
||||||
import random
|
import random
|
||||||
import time
|
import time
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
WAKEUP_CONFIG = {
|
WAKEUP_CONFIG = {
|
||||||
|
|
@ -70,19 +69,9 @@ def getWakeupWordFile(file_name):
|
||||||
|
|
||||||
|
|
||||||
async def wakeupWordsResponse(conn):
|
async def wakeupWordsResponse(conn):
|
||||||
wait_max_time = 5
|
|
||||||
while conn.llm is None or not conn.llm.response_no_stream:
|
|
||||||
await asyncio.sleep(1)
|
|
||||||
wait_max_time -= 1
|
|
||||||
if wait_max_time <= 0:
|
|
||||||
logger.bind(tag=TAG).error("连接对象没有llm")
|
|
||||||
return
|
|
||||||
|
|
||||||
"""唤醒词响应"""
|
"""唤醒词响应"""
|
||||||
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
|
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
|
||||||
result = conn.llm.response_no_stream(conn.config["prompt"], wakeup_word)
|
result = conn.llm.response_no_stream(conn.config["prompt"], wakeup_word)
|
||||||
if result is None or result == "":
|
|
||||||
return
|
|
||||||
tts_file = await asyncio.to_thread(conn.tts.to_tts, result)
|
tts_file = await asyncio.to_thread(conn.tts.to_tts, result)
|
||||||
|
|
||||||
if tts_file is not None and os.path.exists(tts_file):
|
if tts_file is not None and os.path.exists(tts_file):
|
||||||
|
|
|
||||||
|
|
@ -76,11 +76,6 @@ async def process_intent_result(conn, intent_result, original_text):
|
||||||
if function_name == "continue_chat":
|
if function_name == "continue_chat":
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if function_name == "play_music":
|
|
||||||
funcItem = conn.func_handler.get_function(function_name)
|
|
||||||
if not funcItem:
|
|
||||||
conn.func_handler.function_registry.register_function("play_music")
|
|
||||||
|
|
||||||
function_args = None
|
function_args = None
|
||||||
if "arguments" in intent_data["function_call"]:
|
if "arguments" in intent_data["function_call"]:
|
||||||
function_args = intent_data["function_call"]["arguments"]
|
function_args = intent_data["function_call"]["arguments"]
|
||||||
|
|
|
||||||
|
|
@ -144,7 +144,6 @@ class IotDescriptor:
|
||||||
self.methods = []
|
self.methods = []
|
||||||
|
|
||||||
# 根据描述创建属性
|
# 根据描述创建属性
|
||||||
if properties is not None:
|
|
||||||
for key, value in properties.items():
|
for key, value in properties.items():
|
||||||
property_item = globals()[key] = {}
|
property_item = globals()[key] = {}
|
||||||
property_item["name"] = key
|
property_item["name"] = key
|
||||||
|
|
@ -158,7 +157,6 @@ class IotDescriptor:
|
||||||
self.properties.append(property_item)
|
self.properties.append(property_item)
|
||||||
|
|
||||||
# 根据描述创建方法
|
# 根据描述创建方法
|
||||||
if methods is not None:
|
|
||||||
for key, value in methods.items():
|
for key, value in methods.items():
|
||||||
method = globals()[key] = {}
|
method = globals()[key] = {}
|
||||||
method["description"] = value["description"]
|
method["description"] = value["description"]
|
||||||
|
|
@ -271,12 +269,14 @@ def register_device_type(descriptor):
|
||||||
|
|
||||||
# 用于接受前端设备推送的搜索iot描述
|
# 用于接受前端设备推送的搜索iot描述
|
||||||
async def handleIotDescriptors(conn, descriptors):
|
async def handleIotDescriptors(conn, descriptors):
|
||||||
|
if not conn.use_function_call_mode:
|
||||||
|
return
|
||||||
wait_max_time = 5
|
wait_max_time = 5
|
||||||
while conn.func_handler is None or not conn.func_handler.finish_init:
|
while conn.func_handler is None or not conn.func_handler.finish_init:
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
wait_max_time -= 1
|
wait_max_time -= 1
|
||||||
if wait_max_time <= 0:
|
if wait_max_time <= 0:
|
||||||
logger.bind(tag=TAG).debug("连接对象没有func_handler")
|
logger.bind(tag=TAG).error("连接对象没有func_handler")
|
||||||
return
|
return
|
||||||
"""处理物联网描述"""
|
"""处理物联网描述"""
|
||||||
functions_changed = False
|
functions_changed = False
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import time
|
import time
|
||||||
import asyncio
|
|
||||||
from core.utils.util import remove_punctuation_and_length
|
from core.utils.util import remove_punctuation_and_length
|
||||||
from core.handle.sendAudioHandle import send_stt_message
|
from core.handle.sendAudioHandle import send_stt_message
|
||||||
from core.handle.intentHandler import handle_user_intent
|
from core.handle.intentHandler import handle_user_intent
|
||||||
|
|
@ -36,7 +35,9 @@ async def handleAudioMessage(conn, audio):
|
||||||
if len(conn.asr_audio) < 15:
|
if len(conn.asr_audio) < 15:
|
||||||
conn.asr_server_receive = True
|
conn.asr_server_receive = True
|
||||||
else:
|
else:
|
||||||
text, _ = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id)
|
text, file_path = await conn.asr.speech_to_text(
|
||||||
|
conn.asr_audio, conn.session_id
|
||||||
|
)
|
||||||
logger.bind(tag=TAG).info(f"识别文本: {text}")
|
logger.bind(tag=TAG).info(f"识别文本: {text}")
|
||||||
text_len, _ = remove_punctuation_and_length(text)
|
text_len, _ = remove_punctuation_and_length(text)
|
||||||
if text_len > 0:
|
if text_len > 0:
|
||||||
|
|
@ -48,9 +49,6 @@ async def handleAudioMessage(conn, audio):
|
||||||
|
|
||||||
|
|
||||||
async def startToChat(conn, text):
|
async def startToChat(conn, text):
|
||||||
if conn.need_bind:
|
|
||||||
await check_bind_device(conn)
|
|
||||||
return
|
|
||||||
# 首先进行意图分析
|
# 首先进行意图分析
|
||||||
intent_handled = await handle_user_intent(conn, text)
|
intent_handled = await handle_user_intent(conn, text)
|
||||||
|
|
||||||
|
|
@ -73,8 +71,8 @@ async def no_voice_close_connect(conn):
|
||||||
conn.client_no_voice_last_time = time.time() * 1000
|
conn.client_no_voice_last_time = time.time() * 1000
|
||||||
else:
|
else:
|
||||||
no_voice_time = time.time() * 1000 - conn.client_no_voice_last_time
|
no_voice_time = time.time() * 1000 - conn.client_no_voice_last_time
|
||||||
close_connection_no_voice_time = int(
|
close_connection_no_voice_time = conn.config.get(
|
||||||
conn.config.get("close_connection_no_voice_time", 120)
|
"close_connection_no_voice_time", 120
|
||||||
)
|
)
|
||||||
if (
|
if (
|
||||||
not conn.close_after_chat
|
not conn.close_after_chat
|
||||||
|
|
@ -87,44 +85,3 @@ async def no_voice_close_connect(conn):
|
||||||
"请你以“时间过得真快”未来头,用富有感情、依依不舍的话来结束这场对话吧。"
|
"请你以“时间过得真快”未来头,用富有感情、依依不舍的话来结束这场对话吧。"
|
||||||
)
|
)
|
||||||
await startToChat(conn, prompt)
|
await startToChat(conn, prompt)
|
||||||
|
|
||||||
|
|
||||||
async def check_bind_device(conn):
|
|
||||||
if conn.bind_code:
|
|
||||||
# 确保bind_code是6位数字
|
|
||||||
if len(conn.bind_code) != 6:
|
|
||||||
logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}")
|
|
||||||
text = "绑定码格式错误,请检查配置。"
|
|
||||||
await send_stt_message(conn, text)
|
|
||||||
return
|
|
||||||
|
|
||||||
text = f"请登录控制面板,输入{conn.bind_code},绑定设备。"
|
|
||||||
await send_stt_message(conn, text)
|
|
||||||
conn.tts_first_text_index = 0
|
|
||||||
conn.tts_last_text_index = 6
|
|
||||||
conn.llm_finish_task = True
|
|
||||||
|
|
||||||
# 播放提示音
|
|
||||||
music_path = "config/assets/bind_code.wav"
|
|
||||||
opus_packets, _ = conn.tts.audio_to_opus_data(music_path)
|
|
||||||
conn.audio_play_queue.put((opus_packets, text, 0))
|
|
||||||
|
|
||||||
# 逐个播放数字
|
|
||||||
for i in range(6): # 确保只播放6位数字
|
|
||||||
try:
|
|
||||||
digit = conn.bind_code[i]
|
|
||||||
num_path = f"config/assets/bind_code/{digit}.wav"
|
|
||||||
num_packets, _ = conn.tts.audio_to_opus_data(num_path)
|
|
||||||
conn.audio_play_queue.put((num_packets, None, i + 1))
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。"
|
|
||||||
await send_stt_message(conn, text)
|
|
||||||
conn.tts_first_text_index = 0
|
|
||||||
conn.tts_last_text_index = 0
|
|
||||||
conn.llm_finish_task = True
|
|
||||||
music_path = "config/assets/bind_not_found.wav"
|
|
||||||
opus_packets, _ = conn.tts.audio_to_opus_data(music_path)
|
|
||||||
conn.audio_play_queue.put((opus_packets, text, 0))
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import json
|
||||||
import asyncio
|
import asyncio
|
||||||
import time
|
import time
|
||||||
from core.utils.util import (
|
from core.utils.util import (
|
||||||
|
remove_punctuation_and_length,
|
||||||
get_string_no_punctuation_or_emoji,
|
get_string_no_punctuation_or_emoji,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,13 @@
|
||||||
"""MCP服务管理器"""
|
"""MCP服务管理器"""
|
||||||
|
|
||||||
import os, json
|
import os, json
|
||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
from .MCPClient import MCPClient
|
from .MCPClient import MCPClient
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from plugins_func.register import register_function, ToolType
|
from core.utils.util import get_project_dir
|
||||||
from config.config_loader import get_project_dir
|
from plugins_func.register import register_function, ActionResponse, Action, ToolType
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
class MCPManager:
|
class MCPManager:
|
||||||
"""管理多个MCP服务的集中管理器"""
|
"""管理多个MCP服务的集中管理器"""
|
||||||
|
|
||||||
|
|
@ -19,12 +17,10 @@ class MCPManager:
|
||||||
"""
|
"""
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
|
self.config_path = get_project_dir() + 'data/.mcp_server_settings.json'
|
||||||
if os.path.exists(self.config_path) == False:
|
if os.path.exists(self.config_path) == False:
|
||||||
self.config_path = ""
|
self.config_path = ""
|
||||||
self.logger.bind(tag=TAG).warning(
|
self.logger.bind(tag=TAG).warning(f"请检查mcp服务配置文件:data/.mcp_server_settings.json")
|
||||||
f"请检查mcp服务配置文件:data/.mcp_server_settings.json"
|
|
||||||
)
|
|
||||||
self.client: Dict[str, MCPClient] = {}
|
self.client: Dict[str, MCPClient] = {}
|
||||||
self.tools = []
|
self.tools = []
|
||||||
|
|
||||||
|
|
@ -37,13 +33,11 @@ class MCPManager:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(self.config_path, "r", encoding="utf-8") as f:
|
with open(self.config_path, 'r', encoding='utf-8') as f:
|
||||||
config = json.load(f)
|
config = json.load(f)
|
||||||
return config.get("mcpServers", {})
|
return config.get('mcpServers', {})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(
|
self.logger.bind(tag=TAG).error(f"Error loading MCP config from {self.config_path}: {e}")
|
||||||
f"Error loading MCP config from {self.config_path}: {e}"
|
|
||||||
)
|
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
async def initialize_servers(self) -> None:
|
async def initialize_servers(self) -> None:
|
||||||
|
|
@ -51,9 +45,7 @@ class MCPManager:
|
||||||
config = self.load_config()
|
config = self.load_config()
|
||||||
for name, srv_config in config.items():
|
for name, srv_config in config.items():
|
||||||
if not srv_config.get("command"):
|
if not srv_config.get("command"):
|
||||||
self.logger.bind(tag=TAG).warning(
|
self.logger.bind(tag=TAG).warning(f"Skipping server {name}: command not specified")
|
||||||
f"Skipping server {name}: command not specified"
|
|
||||||
)
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -65,17 +57,11 @@ class MCPManager:
|
||||||
self.tools.extend(client_tools)
|
self.tools.extend(client_tools)
|
||||||
for tool in client_tools:
|
for tool in client_tools:
|
||||||
func_name = "mcp_"+tool["function"]["name"]
|
func_name = "mcp_"+tool["function"]["name"]
|
||||||
register_function(func_name, tool, ToolType.MCP_CLIENT)(
|
register_function(func_name, tool, ToolType.MCP_CLIENT)(self.execute_tool)
|
||||||
self.execute_tool
|
self.conn.func_handler.function_registry.register_function(func_name)
|
||||||
)
|
|
||||||
self.conn.func_handler.function_registry.register_function(
|
|
||||||
func_name
|
|
||||||
)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(
|
self.logger.bind(tag=TAG).error(f"Failed to initialize MCP server {name}: {e}")
|
||||||
f"Failed to initialize MCP server {name}: {e}"
|
|
||||||
)
|
|
||||||
self.conn.func_handler.upload_functions_desc()
|
self.conn.func_handler.upload_functions_desc()
|
||||||
|
|
||||||
def get_all_tools(self) -> List[Dict[str, Any]]:
|
def get_all_tools(self) -> List[Dict[str, Any]]:
|
||||||
|
|
@ -93,10 +79,7 @@ class MCPManager:
|
||||||
bool: 是否是MCP工具
|
bool: 是否是MCP工具
|
||||||
"""
|
"""
|
||||||
for tool in self.tools:
|
for tool in self.tools:
|
||||||
if (
|
if tool.get("function") != None and tool["function"].get("name") == tool_name:
|
||||||
tool.get("function") != None
|
|
||||||
and tool["function"].get("name") == tool_name
|
|
||||||
):
|
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
@ -110,9 +93,7 @@ class MCPManager:
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: 工具未找到时抛出
|
ValueError: 工具未找到时抛出
|
||||||
"""
|
"""
|
||||||
self.logger.bind(tag=TAG).info(
|
self.logger.bind(tag=TAG).info(f"Executing tool {tool_name} with arguments: {arguments}")
|
||||||
f"Executing tool {tool_name} with arguments: {arguments}"
|
|
||||||
)
|
|
||||||
for client in self.client.values():
|
for client in self.client.values():
|
||||||
if client.has_tool(tool_name):
|
if client.has_tool(tool_name):
|
||||||
return await client.call_tool(tool_name, arguments)
|
return await client.call_tool(tool_name, arguments)
|
||||||
|
|
@ -125,7 +106,5 @@ class MCPManager:
|
||||||
await client.cleanup()
|
await client.cleanup()
|
||||||
self.logger.bind(tag=TAG).info(f"Cleaned up MCP client: {name}")
|
self.logger.bind(tag=TAG).info(f"Cleaned up MCP client: {name}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(
|
self.logger.bind(tag=TAG).error(f"Error cleaning up MCP client {name}: {e}")
|
||||||
f"Error cleaning up MCP client {name}: {e}"
|
|
||||||
)
|
|
||||||
self.client.clear()
|
self.client.clear()
|
||||||
|
|
|
||||||
|
|
@ -35,5 +35,4 @@ class LLMProviderBase(ABC):
|
||||||
"""
|
"""
|
||||||
# For providers that don't support functions, just return regular response
|
# For providers that don't support functions, just return regular response
|
||||||
for token in self.response(session_id, dialogue):
|
for token in self.response(session_id, dialogue):
|
||||||
yield token, None
|
yield {"type": "content", "content": token}
|
||||||
|
|
||||||
|
|
@ -4,11 +4,9 @@ import json
|
||||||
import re
|
import re
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
import os
|
import os
|
||||||
|
|
||||||
# official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
|
# official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
|
||||||
from cozepy import COZE_CN_BASE_URL
|
from cozepy import COZE_CN_BASE_URL
|
||||||
from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType # noqa
|
from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType # noqa
|
||||||
from core.providers.llm.system_prompt import get_system_prompt_for_function
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -17,8 +15,8 @@ logger = setup_logging()
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.personal_access_token = config.get("personal_access_token")
|
self.personal_access_token = config.get("personal_access_token")
|
||||||
self.bot_id = str(config.get("bot_id"))
|
self.bot_id = config.get("bot_id")
|
||||||
self.user_id = str(config.get("user_id"))
|
self.user_id = config.get("user_id")
|
||||||
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
|
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
|
||||||
|
|
||||||
def response(self, session_id, dialogue):
|
def response(self, session_id, dialogue):
|
||||||
|
|
@ -32,7 +30,10 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
# 如果没有找到conversation_id,则创建新的对话
|
# 如果没有找到conversation_id,则创建新的对话
|
||||||
if not conversation_id:
|
if not conversation_id:
|
||||||
conversation = coze.conversations.create(messages=[])
|
conversation = coze.conversations.create(
|
||||||
|
messages=[
|
||||||
|
]
|
||||||
|
)
|
||||||
conversation_id = conversation.id
|
conversation_id = conversation.id
|
||||||
self.session_conversation_map[session_id] = conversation_id # 更新映射
|
self.session_conversation_map[session_id] = conversation_id # 更新映射
|
||||||
|
|
||||||
|
|
@ -47,23 +48,3 @@ class LLMProvider(LLMProviderBase):
|
||||||
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
|
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
|
||||||
print(event.message.content, end="", flush=True)
|
print(event.message.content, end="", flush=True)
|
||||||
yield event.message.content
|
yield event.message.content
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
|
||||||
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
|
|
||||||
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
|
|
||||||
last_msg = dialogue[-1]["content"]
|
|
||||||
function_str = json.dumps(functions, ensure_ascii=False)
|
|
||||||
modify_msg = get_system_prompt_for_function(function_str) + last_msg
|
|
||||||
dialogue[-1]["content"] = modify_msg
|
|
||||||
|
|
||||||
# 如果最后一个是 role="tool",附加到user上
|
|
||||||
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
|
|
||||||
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
|
|
||||||
while len(dialogue) > 1 :
|
|
||||||
if dialogue[-1]["role"] == "user":
|
|
||||||
dialogue[-1]["content"] = assistant_msg + dialogue[-1]["content"]
|
|
||||||
break
|
|
||||||
dialogue.pop()
|
|
||||||
|
|
||||||
for token in self.response(session_id, dialogue):
|
|
||||||
yield token, None
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ import json
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import requests
|
import requests
|
||||||
from core.providers.llm.base import LLMProviderBase
|
from core.providers.llm.base import LLMProviderBase
|
||||||
from core.providers.llm.system_prompt import get_system_prompt_for_function
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -59,8 +58,7 @@ class LLMProvider(LLMProviderBase):
|
||||||
self.session_conversation_map[session_id] = (
|
self.session_conversation_map[session_id] = (
|
||||||
conversation_id # 更新映射
|
conversation_id # 更新映射
|
||||||
)
|
)
|
||||||
# 过滤 message_replace 事件,此事件会全量推一次
|
if event.get("answer"):
|
||||||
if event.get("event") != "message_replace" and event.get("answer"):
|
|
||||||
yield event["answer"]
|
yield event["answer"]
|
||||||
elif self.mode == "workflows/run":
|
elif self.mode == "workflows/run":
|
||||||
for line in r.iter_lines():
|
for line in r.iter_lines():
|
||||||
|
|
@ -75,30 +73,9 @@ class LLMProvider(LLMProviderBase):
|
||||||
for line in r.iter_lines():
|
for line in r.iter_lines():
|
||||||
if line.startswith(b"data: "):
|
if line.startswith(b"data: "):
|
||||||
event = json.loads(line[6:])
|
event = json.loads(line[6:])
|
||||||
# 过滤 message_replace 事件,此事件会全量推一次
|
if event.get("answer"):
|
||||||
if event.get("event") != "message_replace" and event.get("answer"):
|
|
||||||
yield event["answer"]
|
yield event["answer"]
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
||||||
yield "【服务响应异常】"
|
yield "【服务响应异常】"
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
|
||||||
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
|
|
||||||
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
|
|
||||||
last_msg = dialogue[-1]["content"]
|
|
||||||
function_str = json.dumps(functions, ensure_ascii=False)
|
|
||||||
modify_msg = get_system_prompt_for_function(function_str) + last_msg
|
|
||||||
dialogue[-1]["content"] = modify_msg
|
|
||||||
|
|
||||||
# 如果最后一个是 role="tool",附加到user上
|
|
||||||
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
|
|
||||||
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
|
|
||||||
while len(dialogue) > 1 :
|
|
||||||
if dialogue[-1]["role"] == "user":
|
|
||||||
dialogue[-1]["content"] = assistant_msg + dialogue[-1]["content"]
|
|
||||||
break
|
|
||||||
dialogue.pop()
|
|
||||||
|
|
||||||
for token in self.response(session_id, dialogue):
|
|
||||||
yield token, None
|
|
||||||
|
|
@ -4,11 +4,9 @@ from core.providers.llm.base import LLMProviderBase
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import requests
|
import requests
|
||||||
import json
|
import json
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class LLMProvider(LLMProviderBase):
|
class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
"""初始化Gemini LLM Provider"""
|
"""初始化Gemini LLM Provider"""
|
||||||
|
|
@ -64,16 +62,19 @@ class LLMProvider(LLMProviderBase):
|
||||||
role = "model" if msg["role"] == "assistant" else "user"
|
role = "model" if msg["role"] == "assistant" else "user"
|
||||||
content = msg["content"].strip()
|
content = msg["content"].strip()
|
||||||
if content:
|
if content:
|
||||||
chat_history.append({"role": role, "parts": [{"text": content}]})
|
chat_history.append({
|
||||||
|
"role": role,
|
||||||
|
"parts": [{"text":content}]
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
# 获取当前消息
|
# 获取当前消息
|
||||||
current_msg = dialogue[-1]["content"]
|
current_msg = dialogue[-1]["content"]
|
||||||
|
|
||||||
# 构建请求体
|
# 构建请求体
|
||||||
request_body = {
|
request_body = {
|
||||||
"contents": chat_history
|
"contents": chat_history + [{"role": "user", "parts": [{"text":current_msg}]}],
|
||||||
+ [{"role": "user", "parts": [{"text": current_msg}]}],
|
"generationConfig": self.generation_config
|
||||||
"generationConfig": self.generation_config,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# 构建请求URL
|
# 构建请求URL
|
||||||
|
|
@ -86,17 +87,11 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
# 发送POST请求,经测试手动 request 无法使用 stream 模式
|
# 发送POST请求,经测试手动 request 无法使用 stream 模式
|
||||||
if self.proxies:
|
if self.proxies:
|
||||||
response = requests.post(
|
response = requests.post(url, headers=headers, json=request_body, stream=False, proxies=self.proxies)
|
||||||
url,
|
|
||||||
headers=headers,
|
|
||||||
json=request_body,
|
|
||||||
stream=False,
|
|
||||||
proxies=self.proxies,
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
data = response.json() # 直接解析JSON
|
data = response.json() # 直接解析JSON
|
||||||
if "candidates" in data and data["candidates"]:
|
if 'candidates' in data and data['candidates']:
|
||||||
yield data["candidates"][0]["content"]["parts"][0]["text"]
|
yield data['candidates'][0]['content']['parts'][0]['text']
|
||||||
else:
|
else:
|
||||||
yield "未找到候选回复。"
|
yield "未找到候选回复。"
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
|
|
@ -109,11 +104,13 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
# 发送消息并获取流式响应
|
# 发送消息并获取流式响应
|
||||||
response = chat.send_message(
|
response = chat.send_message(
|
||||||
current_msg, stream=True, generation_config=self.generation_config
|
current_msg,
|
||||||
|
stream=True,
|
||||||
|
generation_config=self.generation_config
|
||||||
)
|
)
|
||||||
# 处理流式响应
|
# 处理流式响应
|
||||||
for chunk in response:
|
for chunk in response:
|
||||||
if hasattr(chunk, "text") and chunk.text:
|
if hasattr(chunk, 'text') and chunk.text:
|
||||||
yield chunk.text
|
yield chunk.text
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
@ -128,6 +125,9 @@ class LLMProvider(LLMProviderBase):
|
||||||
else:
|
else:
|
||||||
yield f"【Gemini服务响应异常: {error_msg}】"
|
yield f"【Gemini服务响应异常: {error_msg}】"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
except requests.exceptions.RequestException as e:
|
except requests.exceptions.RequestException as e:
|
||||||
yield f"请求失败:{e}"
|
yield f"请求失败:{e}"
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
|
|
|
||||||
|
|
@ -63,4 +63,4 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}")
|
logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}")
|
||||||
yield f"【Ollama服务响应异常: {str(e)}】", None
|
yield {"type": "content", "content": f"【Ollama服务响应异常: {str(e)}】"}
|
||||||
|
|
|
||||||
|
|
@ -11,19 +11,11 @@ class LLMProvider(LLMProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
self.model_name = config.get("model_name")
|
self.model_name = config.get("model_name")
|
||||||
self.api_key = config.get("api_key")
|
self.api_key = config.get("api_key")
|
||||||
if "base_url" in config:
|
if 'base_url' in config:
|
||||||
self.base_url = config.get("base_url")
|
self.base_url = config.get("base_url")
|
||||||
else:
|
else:
|
||||||
self.base_url = config.get("url")
|
self.base_url = config.get("url")
|
||||||
max_tokens = config.get("max_tokens")
|
self.max_tokens = config.get("max_tokens", 500)
|
||||||
if max_tokens is None or max_tokens == "":
|
|
||||||
max_tokens = 500
|
|
||||||
|
|
||||||
try:
|
|
||||||
max_tokens = int(max_tokens)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
max_tokens = 500
|
|
||||||
self.max_tokens = max_tokens
|
|
||||||
|
|
||||||
check_model_key("LLM", self.api_key)
|
check_model_key("LLM", self.api_key)
|
||||||
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
|
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
|
||||||
|
|
@ -41,22 +33,18 @@ class LLMProvider(LLMProviderBase):
|
||||||
for chunk in responses:
|
for chunk in responses:
|
||||||
try:
|
try:
|
||||||
# 检查是否存在有效的choice且content不为空
|
# 检查是否存在有效的choice且content不为空
|
||||||
delta = (
|
delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None
|
||||||
chunk.choices[0].delta
|
content = delta.content if hasattr(delta, 'content') else ''
|
||||||
if getattr(chunk, "choices", None)
|
|
||||||
else None
|
|
||||||
)
|
|
||||||
content = delta.content if hasattr(delta, "content") else ""
|
|
||||||
except IndexError:
|
except IndexError:
|
||||||
content = ""
|
content = ''
|
||||||
if content:
|
if content:
|
||||||
# 处理标签跨多个chunk的情况
|
# 处理标签跨多个chunk的情况
|
||||||
if "<think>" in content:
|
if '<think>' in content:
|
||||||
is_active = False
|
is_active = False
|
||||||
content = content.split("<think>")[0]
|
content = content.split('<think>')[0]
|
||||||
if "</think>" in content:
|
if '</think>' in content:
|
||||||
is_active = True
|
is_active = True
|
||||||
content = content.split("</think>")[-1]
|
content = content.split('</think>')[-1]
|
||||||
if is_active:
|
if is_active:
|
||||||
yield content
|
yield content
|
||||||
|
|
||||||
|
|
@ -66,7 +54,10 @@ class LLMProvider(LLMProviderBase):
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
try:
|
try:
|
||||||
stream = self.client.chat.completions.create(
|
stream = self.client.chat.completions.create(
|
||||||
model=self.model_name, messages=dialogue, stream=True, tools=functions
|
model=self.model_name,
|
||||||
|
messages=dialogue,
|
||||||
|
stream=True,
|
||||||
|
tools=functions
|
||||||
)
|
)
|
||||||
|
|
||||||
for chunk in stream:
|
for chunk in stream:
|
||||||
|
|
@ -74,4 +65,4 @@ class LLMProvider(LLMProviderBase):
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
|
logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
|
||||||
yield f"【OpenAI服务响应异常: {e}】", None
|
yield {"type": "content", "content": f"【OpenAI服务响应异常: {e}】"}
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ from core.utils.util import check_model_key
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
class MemoryProvider(MemoryProviderBase):
|
class MemoryProvider(MemoryProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
|
|
@ -36,12 +35,9 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
# Format the content as a message list for mem0
|
# Format the content as a message list for mem0
|
||||||
messages = [
|
messages = [
|
||||||
{"role": message.role, "content": message.content}
|
{"role": message.role, "content": message.content}
|
||||||
for message in msgs
|
for message in msgs if message.role != "system"
|
||||||
if message.role != "system"
|
|
||||||
]
|
]
|
||||||
result = self.client.add(
|
result = self.client.add(messages, user_id=self.role_id, output_format=self.api_version)
|
||||||
messages, user_id=self.role_id, output_format=self.api_version
|
|
||||||
)
|
|
||||||
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
|
||||||
|
|
@ -52,23 +48,25 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
return ""
|
return ""
|
||||||
try:
|
try:
|
||||||
results = self.client.search(
|
results = self.client.search(
|
||||||
query, user_id=self.role_id, output_format=self.api_version
|
query,
|
||||||
|
user_id=self.role_id,
|
||||||
|
output_format=self.api_version
|
||||||
)
|
)
|
||||||
if not results or "results" not in results:
|
if not results or 'results' not in results:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
# Format each memory entry with its update time up to minutes
|
# Format each memory entry with its update time up to minutes
|
||||||
memories = []
|
memories = []
|
||||||
for entry in results["results"]:
|
for entry in results['results']:
|
||||||
timestamp = entry.get("updated_at", "")
|
timestamp = entry.get('updated_at', '')
|
||||||
if timestamp:
|
if timestamp:
|
||||||
try:
|
try:
|
||||||
# Parse and reformat the timestamp
|
# Parse and reformat the timestamp
|
||||||
dt = timestamp.split(".")[0] # Remove milliseconds
|
dt = timestamp.split('.')[0] # Remove milliseconds
|
||||||
formatted_time = dt.replace("T", " ")
|
formatted_time = dt.replace('T', ' ')
|
||||||
except:
|
except:
|
||||||
formatted_time = timestamp
|
formatted_time = timestamp
|
||||||
memory = entry.get("memory", "")
|
memory = entry.get('memory', '')
|
||||||
if timestamp and memory:
|
if timestamp and memory:
|
||||||
# Store tuple of (timestamp, formatted_string) for sorting
|
# Store tuple of (timestamp, formatted_string) for sorting
|
||||||
memories.append((timestamp, f"[{formatted_time}] {memory}"))
|
memories.append((timestamp, f"[{formatted_time}] {memory}"))
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,7 @@ import time
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import yaml
|
import yaml
|
||||||
from config.config_loader import get_project_dir
|
from core.utils.util import get_project_dir
|
||||||
|
|
||||||
|
|
||||||
short_term_memory_prompt = """
|
short_term_memory_prompt = """
|
||||||
# 时空记忆编织者
|
# 时空记忆编织者
|
||||||
|
|
@ -72,7 +71,6 @@ short_term_memory_prompt = """
|
||||||
```
|
```
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def extract_json_data(json_code):
|
def extract_json_data(json_code):
|
||||||
start = json_code.find("```json")
|
start = json_code.find("```json")
|
||||||
# 从start开始找到下一个```结束
|
# 从start开始找到下一个```结束
|
||||||
|
|
@ -88,15 +86,13 @@ def extract_json_data(json_code):
|
||||||
jsonData = json_code[start+7:end]
|
jsonData = json_code[start+7:end]
|
||||||
return jsonData
|
return jsonData
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
class MemoryProvider(MemoryProviderBase):
|
class MemoryProvider(MemoryProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
self.short_momery = ""
|
self.short_momery = ""
|
||||||
self.memory_path = get_project_dir() + "data/.memory.yaml"
|
self.memory_path = get_project_dir() + 'data/.memory.yaml'
|
||||||
self.load_memory()
|
self.load_memory()
|
||||||
|
|
||||||
def init_memory(self, role_id, llm):
|
def init_memory(self, role_id, llm):
|
||||||
|
|
@ -106,7 +102,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
def load_memory(self):
|
def load_memory(self):
|
||||||
all_memory = {}
|
all_memory = {}
|
||||||
if os.path.exists(self.memory_path):
|
if os.path.exists(self.memory_path):
|
||||||
with open(self.memory_path, "r", encoding="utf-8") as f:
|
with open(self.memory_path, 'r', encoding='utf-8') as f:
|
||||||
all_memory = yaml.safe_load(f) or {}
|
all_memory = yaml.safe_load(f) or {}
|
||||||
if self.role_id in all_memory:
|
if self.role_id in all_memory:
|
||||||
self.short_momery = all_memory[self.role_id]
|
self.short_momery = all_memory[self.role_id]
|
||||||
|
|
@ -114,10 +110,10 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
def save_memory_to_file(self):
|
def save_memory_to_file(self):
|
||||||
all_memory = {}
|
all_memory = {}
|
||||||
if os.path.exists(self.memory_path):
|
if os.path.exists(self.memory_path):
|
||||||
with open(self.memory_path, "r", encoding="utf-8") as f:
|
with open(self.memory_path, 'r', encoding='utf-8') as f:
|
||||||
all_memory = yaml.safe_load(f) or {}
|
all_memory = yaml.safe_load(f) or {}
|
||||||
all_memory[self.role_id] = self.short_momery
|
all_memory[self.role_id] = self.short_momery
|
||||||
with open(self.memory_path, "w", encoding="utf-8") as f:
|
with open(self.memory_path, 'w', encoding='utf-8') as f:
|
||||||
yaml.dump(all_memory, f, allow_unicode=True)
|
yaml.dump(all_memory, f, allow_unicode=True)
|
||||||
|
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs):
|
||||||
|
|
|
||||||
|
|
@ -12,9 +12,6 @@ class TTSProvider(TTSProviderBase):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
self.model = config.get("model")
|
self.model = config.get("model")
|
||||||
self.access_token = config.get("access_token")
|
self.access_token = config.get("access_token")
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice")
|
self.voice = config.get("voice")
|
||||||
self.response_format = config.get("response_format")
|
self.response_format = config.get("response_format")
|
||||||
|
|
||||||
|
|
@ -22,10 +19,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.api_url = f"https://{self.host}/v1/audio/speech"
|
self.api_url = f"https://{self.host}/v1/audio/speech"
|
||||||
|
|
||||||
def generate_filename(self, extension=".wav"):
|
def generate_filename(self, extension=".wav"):
|
||||||
return os.path.join(
|
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||||
self.output_file,
|
|
||||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
request_json = {
|
request_json = {
|
||||||
|
|
@ -36,11 +30,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
}
|
}
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.access_token}",
|
"Authorization": f"Bearer {self.access_token}",
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
response = requests.request(
|
response = requests.request("POST", self.api_url, json=request_json, headers=headers)
|
||||||
"POST", self.api_url, json=request_json, headers=headers
|
|
||||||
)
|
|
||||||
data = response.content
|
data = response.content
|
||||||
file_to_save = open(output_file, "wb")
|
file_to_save = open(output_file, "wb")
|
||||||
file_to_save.write(data)
|
file_to_save.write(data)
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,6 @@ import requests
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from config.logger import setup_logging
|
|
||||||
|
|
||||||
TAG = __name__
|
|
||||||
logger = setup_logging()
|
|
||||||
|
|
||||||
|
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
|
|
@ -18,31 +14,25 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.appid = config.get("appid")
|
self.appid = config.get("appid")
|
||||||
self.access_token = config.get("access_token")
|
self.access_token = config.get("access_token")
|
||||||
self.cluster = config.get("cluster")
|
self.cluster = config.get("cluster")
|
||||||
|
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice")
|
self.voice = config.get("voice")
|
||||||
|
|
||||||
self.api_url = config.get("api_url")
|
self.api_url = config.get("api_url")
|
||||||
self.authorization = config.get("authorization")
|
self.authorization = config.get("authorization")
|
||||||
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
|
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
|
||||||
check_model_key("TTS", self.access_token)
|
check_model_key("TTS", self.access_token)
|
||||||
|
|
||||||
def generate_filename(self, extension=".wav"):
|
def generate_filename(self, extension=".wav"):
|
||||||
return os.path.join(
|
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||||
self.output_file,
|
|
||||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
request_json = {
|
request_json = {
|
||||||
"app": {
|
"app": {
|
||||||
"appid": f"{self.appid}",
|
"appid": f"{self.appid}",
|
||||||
"token": "access_token",
|
"token": "access_token",
|
||||||
"cluster": self.cluster,
|
"cluster": self.cluster
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"uid": "1"
|
||||||
},
|
},
|
||||||
"user": {"uid": "1"},
|
|
||||||
"audio": {
|
"audio": {
|
||||||
"voice_type": self.voice,
|
"voice_type": self.voice,
|
||||||
"encoding": "wav",
|
"encoding": "wav",
|
||||||
|
|
@ -56,21 +46,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
"text_type": "plain",
|
"text_type": "plain",
|
||||||
"operation": "query",
|
"operation": "query",
|
||||||
"with_frontend": 1,
|
"with_frontend": 1,
|
||||||
"frontend_type": "unitTson",
|
"frontend_type": "unitTson"
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
resp = requests.post(
|
resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
|
||||||
self.api_url, json.dumps(request_json), headers=self.header
|
|
||||||
)
|
|
||||||
if "data" in resp.json():
|
if "data" in resp.json():
|
||||||
data = resp.json()["data"]
|
data = resp.json()["data"]
|
||||||
file_to_save = open(output_file, "wb")
|
file_to_save = open(output_file, "wb")
|
||||||
file_to_save.write(base64.b64decode(data))
|
file_to_save.write(base64.b64decode(data))
|
||||||
else:
|
else:
|
||||||
raise Exception(
|
raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
|
||||||
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise Exception(f"{__name__} error: {e}")
|
raise Exception(f"{__name__} error: {e}")
|
||||||
|
|
|
||||||
|
|
@ -8,26 +8,20 @@ from core.providers.tts.base import TTSProviderBase
|
||||||
class TTSProvider(TTSProviderBase):
|
class TTSProvider(TTSProviderBase):
|
||||||
def __init__(self, config, delete_audio_file):
|
def __init__(self, config, delete_audio_file):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
if config.get("private_voice"):
|
|
||||||
self.voice = config.get("private_voice")
|
|
||||||
else:
|
|
||||||
self.voice = config.get("voice")
|
self.voice = config.get("voice")
|
||||||
|
|
||||||
def generate_filename(self, extension=".mp3"):
|
def generate_filename(self, extension=".mp3"):
|
||||||
return os.path.join(
|
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||||
self.output_file,
|
|
||||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
communicate = edge_tts.Communicate(text, voice=self.voice)
|
communicate = edge_tts.Communicate(text, voice=self.voice)
|
||||||
# 确保目录存在并创建空文件
|
# 确保目录存在并创建空文件
|
||||||
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
||||||
with open(output_file, "wb") as f:
|
with open(output_file, 'wb') as f:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 流式写入音频数据
|
# 流式写入音频数据
|
||||||
with open(output_file, "ab") as f: # 改为追加模式避免覆盖
|
with open(output_file, 'ab') as f: # 改为追加模式避免覆盖
|
||||||
async for chunk in communicate.stream():
|
async for chunk in communicate.stream():
|
||||||
if chunk["type"] == "audio": # 只处理音频数据块
|
if chunk["type"] == "audio": # 只处理音频数据块
|
||||||
f.write(chunk["data"])
|
f.write(chunk["data"])
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ from pydantic import BaseModel, Field, conint, model_validator
|
||||||
from typing_extensions import Annotated
|
from typing_extensions import Annotated
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
from core.utils.util import check_model_key, parse_string_to_list
|
from core.utils.util import check_model_key
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
|
@ -86,35 +86,28 @@ class TTSProvider(TTSProviderBase):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.reference_id = config.get("reference_id")
|
self.reference_id = config.get("reference_id")
|
||||||
self.reference_audio = parse_string_to_list(config.get("reference_audio"))
|
self.reference_audio = config.get("reference_audio", [])
|
||||||
self.reference_text = parse_string_to_list(config.get("reference_text"))
|
self.reference_text = config.get("reference_text", [])
|
||||||
self.format = config.get("format", "wav")
|
self.format = config.get("format", "wav")
|
||||||
self.channels = int(config.get("channels", 1))
|
self.channels = config.get("channels", 1)
|
||||||
self.rate = int(config.get("rate", 44100))
|
self.rate = config.get("rate", 44100)
|
||||||
self.api_key = config.get("api_key", "YOUR_API_KEY")
|
self.api_key = config.get("api_key", "YOUR_API_KEY")
|
||||||
have_key = check_model_key("FishSpeech TTS", self.api_key)
|
have_key = check_model_key("FishSpeech TTS", self.api_key)
|
||||||
if not have_key:
|
if not have_key:
|
||||||
return
|
return
|
||||||
self.normalize = config.get("normalize", True)
|
self.normalize = config.get("normalize", True)
|
||||||
self.max_new_tokens = int(config.get("max_new_tokens", 1024))
|
self.max_new_tokens = config.get("max_new_tokens", 1024)
|
||||||
self.chunk_length = int(config.get("chunk_length", 200))
|
self.chunk_length = config.get("chunk_length", 200)
|
||||||
self.top_p = float(config.get("top_p", 0.7))
|
self.top_p = config.get("top_p", 0.7)
|
||||||
self.repetition_penalty = float(config.get("repetition_penalty", 1.2))
|
self.repetition_penalty = config.get("repetition_penalty", 1.2)
|
||||||
self.temperature = float(config.get("temperature", 0.7))
|
self.temperature = config.get("temperature", 0.7)
|
||||||
self.streaming = str(config.get("streaming", False)).lower() in (
|
self.streaming = config.get("streaming", False)
|
||||||
"true",
|
|
||||||
"1",
|
|
||||||
"yes",
|
|
||||||
)
|
|
||||||
self.use_memory_cache = config.get("use_memory_cache", "on")
|
self.use_memory_cache = config.get("use_memory_cache", "on")
|
||||||
self.seed = config.get("seed") or None
|
self.seed = config.get("seed")
|
||||||
self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts")
|
self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts")
|
||||||
|
|
||||||
def generate_filename(self, extension=".wav"):
|
def generate_filename(self, extension=".wav"):
|
||||||
return os.path.join(
|
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||||
self.output_file,
|
|
||||||
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def text_to_speak(self, text, output_file):
|
async def text_to_speak(self, text, output_file):
|
||||||
# Prepare reference data
|
# Prepare reference data
|
||||||
|
|
@ -124,7 +117,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
data = {
|
data = {
|
||||||
"text": text,
|
"text": text,
|
||||||
"references": [
|
"references": [
|
||||||
ServeReferenceAudio(audio=audio if audio else b"", text=text)
|
ServeReferenceAudio(
|
||||||
|
audio=audio if audio else b"", text=text
|
||||||
|
)
|
||||||
for text, audio in zip(ref_texts, byte_audios)
|
for text, audio in zip(ref_texts, byte_audios)
|
||||||
],
|
],
|
||||||
"reference_id": self.reference_id,
|
"reference_id": self.reference_id,
|
||||||
|
|
@ -144,9 +139,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
self.api_url,
|
self.api_url,
|
||||||
data=ormsgpack.packb(
|
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
|
||||||
pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
|
|
||||||
),
|
|
||||||
headers={
|
headers={
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
"Content-Type": "application/msgpack",
|
"Content-Type": "application/msgpack",
|
||||||
|
|
@ -159,6 +152,8 @@ class TTSProvider(TTSProviderBase):
|
||||||
with open(output_file, "wb") as audio_file:
|
with open(output_file, "wb") as audio_file:
|
||||||
audio_file.write(audio_content)
|
audio_file.write(audio_content)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print(f"Request failed with status code {response.status_code}")
|
print(f"Request failed with status code {response.status_code}")
|
||||||
print(response.json())
|
print(response.json())
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue