Merge branch 'stable2' into railwaysql

This commit is contained in:
rahulpscraftech360 2025-08-14 11:16:10 +05:30 committed by GitHub
commit 04594a7e23
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
338 changed files with 42468 additions and 19448 deletions

View file

@ -293,9 +293,11 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
### VAD 语音活动检测 ### VAD 语音活动检测
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | | 类型 | 平台名称 | 使用方式 | 收费模式 | 平台支持 | 备注 |
|:---:|:---------:|:----:|:----:|:--:| |:---:|:---------:|:----:|:----:|:----:|:--:|
| VAD | SileroVAD | 本地使用 | 免费 | | | VAD | SileroVAD | 本地使用 | 免费 | Windows, Linux, macOS | |
| VAD | TenVAD | 本地使用 | 免费 | Linux | 高性能语音活动检测 |
| VAD | TenVAD_ONNX | 本地使用 | 免费 | Windows, Linux, macOS | 跨平台高性能VAD |
--- ---

57
README2.md Normal file
View file

@ -0,0 +1,57 @@
Commands to start the servers:
Backend (Spring Boot):
cd main/manager-api
mvn spring-boot:run
Frontend (Vue.js):
cd main/manager-web
npm run serve
The backend runs on port 8002 at http://localhost:8002/xiaozhi
The frontend runs on port 8001 at http://localhost:8001/
The backend requires Java 21.
Update(main/manager-api/pom.xml)
⎿ Updated main/manager-api/pom.xml with 1 addition and 1 removal
17 <properties>
18 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
19 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
20 - <java.version>21</java.version>
20 + <java.version>17</java.version>
The getFirst() method is a Java 21 feature.
fix both files to use Java 17 compatible code:
⏺ Update(main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java)
⎿ Updated main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java with 1 addition and 1 removal
66 // 同类固件只保留最新的一条
67 List<OtaEntity> otaList = baseDao.selectList(queryWrapper);
68 if (otaList != null && otaList.size() > 0) {
69 - OtaEntity otaBefore = otaList.getFirst();
69 + OtaEntity otaBefore = otaList.get(0);
There's a syntax error in the Liquibase configuration file. Let me check and fix it:
⏺ Read(main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml)
⎿ Read 249 lines (ctrl+r to expand)
⏺ I see the issue - there's a duplicate id field at line 243. Let me fix this:
⏺ Update(main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml)
⎿ Updated main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml with 2 additions and 1 removal
240 - sqlFile:
241 encoding: utf8
242 path: classpath:db/changelog/202506261637.sql
243 - id: 202506152342
243 + - changeSet:
244 + id: 202507051233
245 author: marlonz
246 changes:
247 - sqlFile:
restart the backend

View file

@ -0,0 +1,851 @@
# Agent Base Prompt System Documentation
## Overview
The Xiaozhi server uses a sophisticated prompt system that combines user configuration with a template-based enhancement system. The `agent-base-prompt.txt` file serves as a template that wraps around user-defined prompts from configuration files, adding personality, behavior rules, and dynamic context. This document explains how the entire prompt system works, its architecture, and how it integrates with the configuration system.
## Architecture Overview
```
Configuration Loading (data/.config.yaml + config.yaml)
↓
User Prompt Extraction (prompt field)
↓
Template Processing (agent-base-prompt.txt)
↓
Dynamic Context Injection (time, weather, location)
↓
PromptManager (Enhanced Prompt Generation)
↓
Dialogue System (Integration)
↓
AI Assistant (Behavior)
```
## Configuration System Integration
### Configuration File Priority
The system uses a **two-tier configuration approach**:
1. **Primary Configuration**: `data/.config.yaml` (user customizations)
2. **Default Configuration**: `config.yaml` (system defaults)
3. **Merge Strategy**: User config overrides defaults using recursive merge
### Configuration Loading Process
**Location**: `main/xiaozhi-server/config/config_loader.py`
```python
def load_config():
default_config_path = get_project_dir() + "config.yaml"
custom_config_path = get_project_dir() + "data/.config.yaml"
# Load both configurations
default_config = read_config(default_config_path)
custom_config = read_config(custom_config_path)
# Merge with custom taking precedence
config = merge_configs(default_config, custom_config)
return config
```
### User Prompt Integration
The `prompt` field from your configuration becomes the foundation:
**From `data/.config.yaml`**:
```yaml
prompt: |
You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+.
You talk in short, clear, and fun sentences.
# ... your custom prompt content
```
This prompt becomes the `{{base_prompt}}` variable in the template system.
## File Structure and Purpose
### Location
- **File Path**: `main/xiaozhi-server/agent-base-prompt.txt`
- **Type**: Jinja2 Template
- **Encoding**: UTF-8
### Template Variables
The prompt template uses Jinja2 syntax with the following dynamic variables:
| Variable | Description | Source | Cached |
|----------|-------------|---------|---------|
| `{{base_prompt}}` | User's custom prompt from config | Configuration | ✓ |
| `{{current_time}}` | Current timestamp | System time | ✗ |
| `{{today_date}}` | Today's date (YYYY-MM-DD) | System time | ✗ |
| `{{today_weekday}}` | Day of week in Chinese | System time | ✗ |
| `{{lunar_date}}` | Chinese lunar calendar date | cnlunar library | ✗ |
| `{{local_address}}` | User's location based on IP | IP geolocation API | ✓ |
| `{{weather_info}}` | 7-day weather forecast | Weather API | ✓ |
| `{{emojiList}}` | Allowed emoji list | Static configuration | ✓ |
## System Components
### 1. PromptManager Class
**Location**: `main/xiaozhi-server/core/utils/prompt_manager.py`
**Key Methods**:
- `_load_base_template()`: Loads and caches the template file
- `get_quick_prompt()`: Fast initialization with basic prompt
- `build_enhanced_prompt()`: Creates full prompt with dynamic data
- `update_context_info()`: Updates cached context information
**Caching Strategy**:
```python
# Cache types used
CacheType.CONFIG # Template and device prompts
CacheType.LOCATION # IP-based location data
CacheType.WEATHER # Weather forecast data
CacheType.DEVICE_PROMPT # Device-specific enhanced prompts
```
### 2. Connection Integration
**Location**: `main/xiaozhi-server/core/connection.py`
**Initialization Flow**:
1. **Quick Start**: Uses `get_quick_prompt()` for immediate response capability
2. **Enhancement**: Calls `build_enhanced_prompt()` for full context
3. **Update**: Uses `change_system_prompt()` to apply to dialogue system
### 3. Dialogue System Integration
**Location**: `main/xiaozhi-server/core/utils/dialogue.py`
**Integration Method**:
- `update_system_message()`: Updates or creates system message in dialogue
- System prompt becomes the foundation for all AI responses
- Maintains conversation context with enhanced prompt
## Prompt Template Structure
### Core Sections
#### 1. Identity Section
```xml
<identity>
{{base_prompt}}
</identity>
```
- Contains user's custom prompt from configuration
- Defines the AI's basic role and personality
#### 2. Emotion Section
```xml
<emotion>
【Core Goal】You are not a cold machine! Please keenly perceive user emotions...
</emotion>
```
- Defines emotional response patterns
- Specifies emoji usage rules
- Sets tone for interactions
#### 3. Communication Style
```xml
<communication_style>
【Core Goal】Use **natural, warm, conversational** human dialogue style...
</communication_style>
```
- Establishes conversation patterns
- Defines language style and formality
- Sets response format requirements
#### 4. Length Constraints
```xml
<communication_length_constraint>
【Core Goal】All long text content output... **single reply length must not exceed 300 characters**
</communication_length_constraint>
```
- Enforces response length limits
- Defines segmentation strategies
- Guides content delivery approach
#### 5. Speaker Recognition
```xml
<speaker_recognition>
- **Recognition Prefix:** When user format is `{"speaker":"someone","content":"xxx"}`...
</speaker_recognition>
```
- Handles voice recognition integration
- Defines personalization rules
- Sets name-calling behavior
#### 6. Tool Calling Rules
```xml
<tool_calling>
【Core Principle】Prioritize using `<context>` information, **only call tools when necessary**...
</tool_calling>
```
- Defines when and how to use available functions
- Sets priority for context vs. tool usage
- Establishes calling patterns
#### 7. Dynamic Context
```xml
<context>
【Important! The following information is provided in real-time...】
- **Current Time:** {{current_time}}
- **Today's Date:** {{today_date}} ({{today_weekday}})
- **Today's Lunar Calendar:** {{lunar_date}}
- **User's City:** {{local_address}}
- **Local 7-day Weather Forecast:** {{weather_info}}
</context>
```
- Provides real-time contextual information
- Updates automatically with fresh data
- Eliminates need for certain tool calls
#### 8. Memory Section
```xml
<memory>
</memory>
```
- Placeholder for conversation history
- Populated by dialogue system
- Maintains conversation continuity
## Complete Processing Flow
### Stage 1: Configuration Loading
1. **File Reading**: System loads both `config.yaml` and `data/.config.yaml`
2. **Merging**: Custom config overrides defaults using `merge_configs()`
3. **Caching**: Merged configuration stored in CONFIG cache
4. **User Prompt Extraction**: `config["prompt"]` becomes the base prompt
### Stage 2: Template Loading
1. **Template Reading**: `PromptManager` loads `agent-base-prompt.txt`
2. **Template Caching**: Template stored in CONFIG cache for reuse
3. **Validation**: Checks file existence and readability
### Stage 3: Quick Initialization (Fast Startup)
```python
# Fast startup process - uses user prompt directly
user_prompt = config["prompt"] # From data/.config.yaml
prompt = prompt_manager.get_quick_prompt(user_prompt)
connection.change_system_prompt(prompt)
```
### Stage 4: Context Enhancement (Full Integration)
```python
# Gather dynamic context data
prompt_manager.update_context_info(connection, client_ip)
# Build enhanced prompt with template
enhanced_prompt = prompt_manager.build_enhanced_prompt(
user_prompt, # Your prompt from data/.config.yaml
device_id,
client_ip
)
# Apply enhanced prompt
connection.change_system_prompt(enhanced_prompt)
```
### Stage 5: Template Processing
```python
# Jinja2 template rendering
template = Template(agent_base_prompt_template)
enhanced_prompt = template.render(
base_prompt=user_prompt, # Your custom prompt
current_time="{{current_time}}",
today_date=today_date,
today_weekday=today_weekday,
lunar_date=lunar_date,
local_address=local_address,
weather_info=weather_info,
emojiList=EMOJI_List
)
```
### Stage 6: Dialogue Integration
```python
# System message update
dialogue.update_system_message(enhanced_prompt)
```
## Caching Strategy
### Cache Levels
1. **Template Cache** (CONFIG)
- Stores the raw template file
- Persistent until manual invalidation
- Shared across all connections
2. **Device Cache** (DEVICE_PROMPT)
- Stores device-specific enhanced prompts
- Includes personalization data
- Per-device isolation
3. **Context Cache** (LOCATION, WEATHER)
- Location data cached by IP address
- Weather data cached by location
- Time-based expiration
### Cache Keys
```python
f"prompt_template:{template_path}" # Template cache
f"device_prompt:{device_id}" # Device-specific prompt
f"{client_ip}" # Location cache
f"{location}" # Weather cache
```
## Configuration Integration
### Configuration File Relationship
#### `data/.config.yaml` (User Configuration - Priority 1)
```yaml
# Your custom configuration - overrides defaults
prompt: |
You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+.
You talk in short, clear, and fun sentences.
# ... your custom personality and behavior
selected_module:
LLM: GroqLLM
TTS: elevenlabs
VAD: TenVAD_ONNX
ASR: SherpaASR
LLM:
GroqLLM:
api_key: your_groq_api_key
model_name: openai/gpt-oss-20b
plugins:
play_music:
music_dir: "./music"
get_weather:
api_key: "your_weather_api_key"
```
#### `config.yaml` (Default Configuration - Priority 2)
```yaml
# System defaults - used when not overridden
prompt: |
你是小智/小志,来自中国台湾省的00后女生...
# Default personality
selected_module:
VAD: SileroVAD
ASR: FunASR
LLM: ChatGLMLLM
TTS: EdgeTTS
# ... extensive default configurations
```
#### `agent-base-prompt.txt` (Template - Enhancement Layer)
```xml
<identity>
{{base_prompt}} <!-- Your prompt from data/.config.yaml -->
</identity>
<emotion>
【Core Goal】You are not a cold machine! Please keenly perceive user emotions...
</emotion>
<context>
- **Current Time:** {{current_time}}
- **Today's Date:** {{today_date}} ({{today_weekday}})
- **User's City:** {{local_address}}
- **Local 7-day Weather Forecast:** {{weather_info}}
</context>
```
### Configuration Merge Process
```python
# config_loader.py
def merge_configs(default_config, custom_config):
"""
Recursively merges configurations
custom_config takes precedence over default_config
"""
merged = dict(default_config)
for key, value in custom_config.items():
if key in merged and isinstance(merged[key], Mapping):
merged[key] = merge_configs(merged[key], value)
else:
merged[key] = value # Custom overrides default
return merged
```
### Environment Variables and API Keys
- Weather API keys (configured in `data/.config.yaml`)
- LLM API keys (GroqLLM, ChatGLM, etc.)
- TTS service keys (ElevenLabs, etc.)
- Cache settings and timeouts
## Error Handling
### Common Issues and Solutions
1. **Missing Template File**
```python
# Fallback to user prompt only
if not os.path.exists(template_path):
logger.warning("未找到agent-base-prompt.txt文件")
return user_prompt
```
2. **Template Rendering Errors**
```python
# Graceful degradation
except Exception as e:
logger.error(f"构建增强提示词失败: {e}")
return user_prompt
```
3. **Context Data Failures**
```python
# Default values for missing context
local_address = cache_manager.get(CacheType.LOCATION, client_ip) or "未知位置"
weather_info = cache_manager.get(CacheType.WEATHER, local_address) or "天气信息获取失败"
```
## Performance Considerations
### Optimization Strategies
1. **Template Caching**: Template loaded once and reused
2. **Context Caching**: Location and weather data cached with TTL
3. **Device Caching**: Enhanced prompts cached per device
4. **Lazy Loading**: Context data fetched asynchronously
### Memory Usage
- Template: ~2-5KB per instance
- Enhanced prompt: ~5-15KB per device
- Context cache: ~1KB per location/weather entry
## Customization Guide
### Modifying Your AI's Personality
#### Option 1: Update User Configuration (Recommended)
1. **Edit `data/.config.yaml`**: Modify the `prompt` field
2. **Keep Template**: Leave `agent-base-prompt.txt` unchanged
3. **Restart Server**: Changes take effect on restart
4. **Benefits**: Your changes persist through updates
**Example**:
```yaml
# data/.config.yaml
prompt: |
You are Alex, a tech-savvy assistant who loves explaining complex topics simply.
You use analogies and real-world examples.
You're enthusiastic about helping users learn new things.
```
#### Option 2: Modify the Template (Advanced)
1. **Edit Template File**: Modify `agent-base-prompt.txt`
2. **Clear Cache**: Restart server or clear CONFIG cache
3. **Test Changes**: Verify with new connections
4. **Warning**: Changes may be lost during system updates
### Adding New Template Variables
1. **Update Template**: Add `{{new_variable}}` placeholder in `agent-base-prompt.txt`
2. **Modify PromptManager**: Add variable to `build_enhanced_prompt()` method
3. **Update Context**: Add data source for the new variable
4. **Test Integration**: Verify variable substitution works
**Example**:
```python
# In prompt_manager.py
enhanced_prompt = template.render(
base_prompt=user_prompt,
# ... existing variables
new_variable=get_new_data(), # Add your new variable
)
```
### Custom Template Sections
You can add custom sections to the template:
```xml
<custom_behavior>
- Always ask follow-up questions to keep conversations engaging
- Use emojis from the approved list: {{emojiList}}
- Adapt your language complexity based on user responses
</custom_behavior>
<domain_expertise>
When discussing {{domain_topic}}:
- Provide practical examples
- Reference current best practices
- Suggest hands-on exercises
</domain_expertise>
```
### Configuration-Based Customization
#### Response Length Control
```yaml
# data/.config.yaml
response_constraints:
max_words: 50
enforce_limit: true
```
#### Module Selection
```yaml
# data/.config.yaml
selected_module:
LLM: GroqLLM # Fast inference
TTS: elevenlabs # High-quality voice
VAD: TenVAD_ONNX # Cross-platform VAD
ASR: SherpaASR # Local speech recognition
```
#### Plugin Configuration
```yaml
# data/.config.yaml
plugins:
play_music:
music_dir: "./my_music"
music_ext: [".mp3", ".wav", ".flac"]
get_weather:
api_key: "your_api_key"
default_location: "New York"
```
## Troubleshooting
### Debug Commands
```python
# Check template loading
logger.debug("Template loaded successfully")
# Verify variable substitution
logger.info(f"Enhanced prompt length: {len(enhanced_prompt)}")
# Monitor cache usage
cache_manager.get_stats()
```
### Common Problems
1. **Variables Not Substituting**: Check Jinja2 syntax
2. **Context Data Missing**: Verify API keys and network
3. **Cache Issues**: Clear relevant cache types
4. **Performance Problems**: Check cache hit rates
## Best Practices
### Template Design
- Keep sections focused and clear
- Use consistent formatting
- Document all variables
- Test with various scenarios
### Performance
- Cache frequently used data
- Minimize API calls
- Use appropriate cache TTLs
- Monitor memory usage
### Maintenance
- Regular template reviews
- Cache cleanup procedures
- Performance monitoring
- Error log analysis
## Special Case: Function Calling for Non-Native LLM Providers
### System Prompt for Function Calls
Some LLM providers (Dify, Coze) don't support native OpenAI-style function calling. For these providers, the system uses a separate mechanism:
**File**: `main/xiaozhi-server/core/providers/llm/system_prompt.py`
#### How It Works
1. **Detection**: When using Dify or Coze LLM providers with functions available
2. **Injection**: Function calling instructions are appended to the **user message** (not system prompt)
3. **Template**: Provides detailed JSON formatting instructions for tool usage
#### Example Flow
```python
# For Dify/Coze providers only
if len(dialogue) == 2 and functions is not None:
last_msg = dialogue[-1]["content"] # User message
function_str = json.dumps(functions, ensure_ascii=False)
# Append function instructions to user message
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
```
#### Function Call Format Taught to AI
```xml
<tool_call>
{
"name": "function_name",
"arguments": {
"param1": "value1",
"param2": "value2"
}
}
</tool_call>
```
### Prompt System Architecture (Complete)
```
Configuration Loading (data/.config.yaml + config.yaml)
↓
User Prompt Extraction (prompt field)
↓
Template Processing (agent-base-prompt.txt)
↓
Dynamic Context Injection (time, weather, location)
↓
PromptManager (Enhanced Prompt Generation)
↓
LLM Provider Check
↓
┌─────────────────────┬─────────────────────┐
│ Native Function │ Non-Native │
│ Calling LLMs │ Function LLMs │
│ (OpenAI, etc.) │ (Dify, Coze) │
│ │ │
│ System Prompt │ System Prompt + │
│ Only │ Function Instructions│
│ │ in User Message │
└─────────────────────┴─────────────────────┘
↓
Dialogue System (Integration)
↓
AI Assistant (Behavior)
```
## Key Insights
### Why This Multi-Layer System?
1. **Flexibility**: Users can customize AI personality without touching system files
2. **Consistency**: Template ensures all AIs have proper behavior guidelines
3. **Context Awareness**: Dynamic data injection keeps responses relevant
4. **Maintainability**: System updates don't overwrite user customizations
5. **Performance**: Caching at multiple levels ensures fast response times
6. **LLM Compatibility**: Handles both native and non-native function calling providers
### Best Practices
#### For Users
- **Always edit `data/.config.yaml`** for customizations
- **Keep backups** of your configuration file
- **Test changes** with simple conversations first
- **Use version control** for your config files
#### For Developers
- **Never modify user config files** programmatically
- **Use the cache system** for performance
- **Handle missing context gracefully**
- **Document new template variables**
### Common Misconceptions
❌ **"The system only uses agent-base-prompt.txt"**
✅ **Reality**: Your `data/.config.yaml` prompt is the foundation, template enhances it
❌ **"I need to edit the template for personality changes"**
✅ **Reality**: Edit the `prompt` field in `data/.config.yaml`
❌ **"Configuration changes require code modifications"**
✅ **Reality**: Most changes only require config file updates
❌ **"All LLM providers work the same way"**
✅ **Reality**: Some providers (Dify, Coze) use special function calling instructions
❌ **"Function calling instructions go in the system prompt"**
✅ **Reality**: For non-native providers, they're appended to user messages
## Related Files
### Core System Files
- `main/xiaozhi-server/config/config_loader.py` - Configuration loading and merging
- `main/xiaozhi-server/core/utils/prompt_manager.py` - Core prompt management
- `main/xiaozhi-server/core/connection.py` - Connection integration
- `main/xiaozhi-server/core/utils/dialogue.py` - Dialogue system
- `main/xiaozhi-server/core/utils/cache/manager.py` - Cache management
- `main/xiaozhi-server/core/providers/llm/system_prompt.py` - Function calling instructions for specific LLM providers
### Configuration Files
- `main/xiaozhi-server/data/.config.yaml` - **User configuration (Priority 1)**
- `main/xiaozhi-server/config.yaml` - Default configuration (Priority 2)
- `main/xiaozhi-server/agent-base-prompt.txt` - Prompt template
- `main/xiaozhi-server/core/providers/llm/system_prompt.py` - Function calling instructions template
### Related Documentation
- `docs/Deployment.md` - Configuration setup guide
- `main/xiaozhi-server/README.md` - General setup instructions
## Troubleshooting
### Common Issues
#### 1. **My prompt changes aren't taking effect**
**Solution**:
- Verify you're editing `data/.config.yaml`, not `config.yaml`
- Restart the server to clear caches
- Check for YAML syntax errors
#### 2. **Template variables showing as literal text**
**Solution**:
- Check Jinja2 syntax in `agent-base-prompt.txt`
- Verify variable names match those in `prompt_manager.py`
- Ensure template file encoding is UTF-8
#### 3. **Context data not updating**
**Solution**:
- Check API keys for weather/location services
- Verify network connectivity
- Clear relevant cache types manually
#### 4. **Configuration merge not working**
**Solution**:
- Ensure proper YAML indentation
- Check for duplicate keys
- Validate YAML syntax with online tools
#### 5. **Function calling not working with Dify/Coze**
**Solution**:
- Verify `system_prompt.py` exists and is accessible
- Check that functions are properly formatted in JSON
- Ensure the LLM provider is correctly identified as Dify or Coze
- Verify the function instructions are being appended to user messages
### Debug Commands
```python
# Check configuration loading
logger.debug("Configuration loaded successfully")
# Verify prompt enhancement
logger.info(f"Enhanced prompt length: {len(enhanced_prompt)}")
# Monitor cache usage
cache_manager.get_stats()
# Check template rendering
logger.debug(f"Template variables: {template_vars}")
```
### Performance Monitoring
#### Cache Hit Rates
- **Template Cache**: Should be near 100% after first load
- **Device Cache**: High hit rate indicates good personalization
- **Context Cache**: Monitor TTL effectiveness
#### Memory Usage
- **Template**: ~2-5KB per instance
- **Enhanced Prompt**: ~5-15KB per device
- **Context Cache**: ~1KB per location/weather entry
## Example: Complete Flow
### 1. User Configuration
```yaml
# data/.config.yaml
prompt: |
You are Jamie, a helpful coding mentor who explains things step by step.
You use practical examples and encourage best practices.
selected_module:
LLM: GroqLLM # Native function calling support
```
### 2. Template Processing
```xml
<!-- agent-base-prompt.txt -->
<identity>
You are Jamie, a helpful coding mentor who explains things step by step.
You use practical examples and encourage best practices.
</identity>
<emotion>
【Core Goal】You are not a cold machine! Please keenly perceive user emotions...
</emotion>
<context>
- **Current Time:** 2025-01-13 14:30:00
- **Today's Date:** 2025-01-13 (Monday)
- **User's City:** San Francisco
- **Local 7-day Weather Forecast:** Sunny, 72°F...
</context>
```
### 3. Final Enhanced Prompt
The system combines your custom personality with behavioral guidelines, emotional intelligence, and real-time context to create a comprehensive system prompt that guides the AI's responses.
### 4. LLM Provider-Specific Handling
#### For Native Function Calling LLMs (OpenAI, Groq, etc.)
```
System Prompt: [Enhanced prompt from above]
User Message: "Can you help me debug this Python code?"
Functions: [Available as separate function definitions]
```
#### For Non-Native Function Calling LLMs (Dify, Coze)
```
System Prompt: [Enhanced prompt from above]
User Message: [Function calling instructions from system_prompt.py] + "Can you help me debug this Python code?"
Functions: [Embedded in the instruction template]
```
**Example of function instructions appended to user message:**
```
====
TOOL USE
You have access to a set of tools that are executed upon the user's approval...
<tool_call>
{
"name": "function_name",
"arguments": {
"param1": "value1"
}
}
</tool_call>
# Tools
[Function definitions in JSON format]
====
USER CHAT CONTENT
Can you help me debug this Python code?
```
## Version History
- **v1.0**: Initial template system
- **v1.1**: Added caching layer
- **v1.2**: Enhanced context integration
- **v1.3**: Device-specific prompts
- **v1.4**: Performance optimizations
- **v2.0**: **Configuration system integration** (Current)
- Added `data/.config.yaml` priority system
- Implemented configuration merging
- Enhanced user customization capabilities
---
*This documentation reflects the current dual-configuration system where user prompts from `data/.config.yaml` are enhanced by the `agent-base-prompt.txt` template. Please update when making changes to either the configuration or prompt systems.*

File diff suppressed because it is too large Load diff

View file

@ -1,104 +1,100 @@
# MCP 接入点部署使用指南 # MCP Endpoint Deployment and Usage Guide
本教程包含2个部分 This tutorial contains 2 parts:
- 1、如何开启mcp接入点 - 1. How to enable the MCP endpoint
- 2、如何为智能体接入一个简单的mcp功能,如计算器功能 - 2. How to integrate a simple MCP function for the AI agent, such as calculator functionality
部署的前提条件: Prerequisites for deployment:
- 1、你已经部署了全模块,因为mcp接入点需要全模块中的智控台功能 - 1. You have deployed the full module suite, as the MCP endpoint requires the management console functionality from the full module
- 2、你想在不修改xiaozhi-server项目的前提下,扩展小智的功能 - 2. You want to extend Xiaozhi's functionality without modifying the xiaozhi-server project
# 如何开启mcp接入点 # How to Enable the MCP Endpoint
## 第一步,下载mcp接入点项目源码 ## Step 1: Download the MCP Endpoint Project Source Code
浏览器打开[mcp接入点项目地址](https://github.com/xinnan-tech/mcp-endpoint-server) Open the [MCP endpoint project repository](https://github.com/xinnan-tech/mcp-endpoint-server) in your browser.
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。 Once opened, find the green button labeled `Code` on the page, click it, and you'll see the `Download ZIP` button.
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`mcp-endpoint-server-main` Click it to download the project source code archive. After downloading to your computer, extract it. The folder name might be `mcp-endpoint-server-main`, which you need to rename to `mcp-endpoint-server`.
你需要把它重命名成`mcp-endpoint-server`。
## 第二步,启动程序 ## Step 2: Start the Program
这个项目是一个很简单的项目,建议使用docker运行。不过如果你不想使用docker运行,你可以参考[这个页面](https://github.com/xinnan-tech/mcp-endpoint-server/blob/main/README_dev.md)使用源码运行。以下是docker运行的方法 This is a simple project, and it's recommended to run it using Docker. However, if you don't want to use Docker, you can refer to [this page](https://github.com/xinnan-tech/mcp-endpoint-server/blob/main/README_dev.md) to run from source code. Here's how to run with Docker:
``` ```bash
# 进入本项目源码根目录 # Enter the project source code root directory
cd mcp-endpoint-server cd mcp-endpoint-server
# 清除缓存 # Clear cache
docker compose -f docker-compose.yml down docker compose -f docker-compose.yml down
docker stop mcp-endpoint-server docker stop mcp-endpoint-server
docker rm mcp-endpoint-server docker rm mcp-endpoint-server
docker rmi ghcr.nju.edu.cn/xinnan-tech/mcp-endpoint-server:latest docker rmi ghcr.nju.edu.cn/xinnan-tech/mcp-endpoint-server:latest
# 启动docker容器 # Start docker container
docker compose -f docker-compose.yml up -d docker compose -f docker-compose.yml up -d
# 查看日志 # View logs
docker logs -f mcp-endpoint-server docker logs -f mcp-endpoint-server
``` ```
此时,日志里会输出类似以下的日志 At this point, the logs will output something similar to:
``` ```
====================================================== ======================================================
接口地址: http://172.1.1.1:8004/mcp_endpoint/health?key=xxxx Interface URL: http://172.1.1.1:8004/mcp_endpoint/health?key=xxxx
=======上面的地址是MCP接入点地址,请勿泄露给任何人============ =======The above URL is the MCP endpoint address, do not share with anyone============
``` ```
请你把接口地址复制出来: Please copy the interface URL:
由于你是docker部署,切不可直接使用上面的地址! **Important: Since you're using Docker deployment, DO NOT use the above address directly!**
由于你是docker部署,切不可直接使用上面的地址! **Important: Since you're using Docker deployment, DO NOT use the above address directly!**
由于你是docker部署,切不可直接使用上面的地址! **Important: Since you're using Docker deployment, DO NOT use the above address directly!**
你先把地址复制出来,放在一个草稿里,你要知道你的电脑的局域网ip是什么,例如我的电脑局域网ip是`192.168.1.25`,那么 First copy the address and save it in a draft. You need to know your computer's local network IP. For example, if my computer's local IP is `192.168.1.25`, then the original interface address:
原来我的接口地址
``` ```
http://172.1.1.1:8004/mcp_endpoint/health?key=xxxx http://172.1.1.1:8004/mcp_endpoint/health?key=xxxx
``` ```
就要改成 should be changed to:
``` ```
http://192.168.1.25:8004/mcp_endpoint/health?key=xxxx http://192.168.1.25:8004/mcp_endpoint/health?key=xxxx
``` ```
改好后,请使用浏览器直接访问这个接口。当浏览器出现类似这样的代码,说明是成功了。 After making the change, please access this interface directly using your browser. When the browser displays code similar to this, it means success:
``` ```
{"result":{"status":"success","connections":{"tool_connections":0,"robot_connections":0,"total_connections":0}},"error":null,"id":null,"jsonrpc":"2.0"} {"result":{"status":"success","connections":{"tool_connections":0,"robot_connections":0,"total_connections":0}},"error":null,"id":null,"jsonrpc":"2.0"}
``` ```
请你保留好这个`接口地址`,下一步要用到。 Please keep this `interface URL` safe, as you'll need it in the next step.
## 第三步,配置智控台 ## Step 3: Configure the Management Console
使用管理员账号,登录智控台,点击顶部`参数字典`,选择`参数管理`功能。 Log in to the management console using an administrator account, click on `Parameter Dictionary` at the top, and select the `Parameter Management` function.
然后搜索参数`server.mcp_endpoint`,此时,它的值应该是`null`值。 Then search for the parameter `server.mcp_endpoint`. At this point, its value should be `null`.
点击修改按钮,把上一步得来的`接口地址`粘贴到`参数值`里。然后保存。 Click the modify button and paste the `interface URL` from the previous step into the `Parameter Value` field. Then save.
如果能保存成功,说明一切顺利,你可以去智能体查看效果了。如果不成功,说明智控台无法访问mcp接入点,很大概率是网络防火墙,或者没有填写正确的局域网ip。 If you can save successfully, everything is going smoothly, and you can go to the AI agent to see the effects. If unsuccessful, it means the management console cannot access the MCP endpoint, most likely due to network firewall issues or incorrect local network IP configuration.
# 如何为智能体接入一个简单的mcp功能,如计算器功能 # How to Integrate a Simple MCP Function for the AI Agent, Such as Calculator Functionality
如果以上步骤顺利,你可以进入智能体管理,点击`配置角色`,在`意图识别`的右边,有一个`编辑功能`的按钮。 If the above steps went smoothly, you can enter AI agent management, click `Configure Role`, and on the right side of `Intent Recognition`, there's an `Edit Functions` button.
点击这个按钮。在弹出的页面里,位于底部,会有`MCP接入点`,正常来说,会显示这个智能体的`MCP接入点地址`,接下来,我们来给这个智能体扩展一个基于MCP技术的计算器的功能。 Click this button. In the popup page, at the bottom, there will be `MCP Endpoint`. Normally, it will display this AI agent's `MCP Endpoint Address`. Next, we'll extend this AI agent with calculator functionality based on MCP technology.
这个`MCP接入点地址`很重要,你等一下会用到。 This `MCP Endpoint Address` is important - you'll need it shortly.
## 第一步 下载虾哥MCP计算器项目代码 ## Step 1: Download the MCP Calculator Project Code
浏览器打开虾哥写的[计算器项目](https://github.com/78/mcp-calculator), Open the [calculator project](https://github.com/78/mcp-calculator) in your browser.
打开完,找到页面中一个绿色的按钮,写着`Code`的按钮,点开它,然后你就看到`Download ZIP`的按钮。 Once opened, find the green button labeled `Code` on the page, click it, and you'll see the `Download ZIP` button.
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`mcp-calculatorr-main`
你需要把它重命名成`mcp-calculator`。接下来,我们用命令行进入项目目录即安装依赖
Click it to download the project source code archive. After downloading to your computer, extract it. The folder name might be `mcp-calculator-main`, which you need to rename to `mcp-calculator`. Next, we'll use the command line to enter the project directory and install dependencies:
```bash ```bash
# 进入项目目录 # Enter project directory
cd mcp-calculator cd mcp-calculator
conda remove -n mcp-calculator --all -y conda remove -n mcp-calculator --all -y
@ -108,27 +104,26 @@ conda activate mcp-calculator
pip install -r requirements.txt pip install -r requirements.txt
``` ```
## 第二步 启动 ## Step 2: Launch
启动前,先从你的智控台的智能体里,复制到了MCP接入点的地址。 Before launching, first copy the MCP endpoint address from your AI agent in the management console.
例如我的智能体的mcp地址是 For example, if my AI agent's MCP address is:
``` ```
ws://192.168.4.7:8004/mcp_endpoint/mcp/?token=abc ws://192.168.4.7:8004/mcp_endpoint/mcp/?token=abc
``` ```
开始输入命令 Start by entering the command:
```bash ```bash
export MCP_ENDPOINT=ws://192.168.4.7:8004/mcp_endpoint/mcp/?token=abc export MCP_ENDPOINT=ws://192.168.4.7:8004/mcp_endpoint/mcp/?token=abc
``` ```
输入完后,启动程序 After entering this, start the program:
```bash ```bash
python mcp_pipe.py calculator.py python mcp_pipe.py calculator.py
``` ```
After startup, go back to the management console and click refresh on the MCP connection status. You'll then see the list of extended functions you've added.
启动完后,你再进入智控台,点击刷新MCP的接入状态,就会看到你扩展的功能列表了。

View file

@ -17,7 +17,7 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>21</java.version> <java.version>17</java.version>
<junit.version>5.10.1</junit.version> <junit.version>5.10.1</junit.version>
<druid.version>1.2.20</druid.version> <druid.version>1.2.20</druid.version>
<mybatisplus.version>3.5.5</mybatisplus.version> <mybatisplus.version>3.5.5</mybatisplus.version>

View file

@ -66,7 +66,7 @@ public class OtaServiceImpl extends BaseServiceImpl<OtaDao, OtaEntity> implement
// 同类固件只保留最新的一条 // 同类固件只保留最新的一条
List<OtaEntity> otaList = baseDao.selectList(queryWrapper); List<OtaEntity> otaList = baseDao.selectList(queryWrapper);
if (otaList != null && otaList.size() > 0) { if (otaList != null && otaList.size() > 0) {
OtaEntity otaBefore = otaList.getFirst(); OtaEntity otaBefore = otaList.get(0);
entity.setId(otaBefore.getId()); entity.setId(otaBefore.getId());
baseDao.updateById(entity); baseDao.updateById(entity);
return true; return true;

View file

@ -56,7 +56,7 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
if (users == null || users.isEmpty()) { if (users == null || users.isEmpty()) {
return null; return null;
} }
SysUserEntity entity = users.getFirst(); SysUserEntity entity = users.get(0);
return ConvertUtils.sourceToTarget(entity, SysUserDTO.class); return ConvertUtils.sourceToTarget(entity, SysUserDTO.class);
} }

View file

@ -241,7 +241,10 @@ databaseChangeLog:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202506261637.sql path: classpath:db/changelog/202506261637.sql
- changeSet: - changeSet:
id: 202506152342
id: 202507051233
author: marlonz author: marlonz
changes: changes:
- sqlFile: - sqlFile:

View file

@ -1,19 +0,0 @@
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"baseUrl": "./",
"moduleResolution": "node",
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,9 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="zh-CN"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>离线模式 - 小智控制台</title> <title>Offline Mode - XiaoZhi Console</title>
<style> <style>
body { body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
@ -54,14 +54,14 @@
<body> <body>
<div class="container"> <div class="container">
<div class="icon">📶</div> <div class="icon">📶</div>
<h1>您当前处于离线模式</h1> <h1>You are currently offline</h1>
<p>看起来您的网络连接有问题,无法连接到小智控制台服务器。</p> <p>It looks like there's a problem with your network connection. Unable to connect to XiaoZhi console server.</p>
<p>部分已缓存的内容和静态资源可能仍然可用,但功能可能受到限制。</p> <p>Some cached content and static resources may still be available, but functionality may be limited.</p>
<button class="btn" onclick="window.location.reload()">重新尝试连接</button> <button class="btn" onclick="window.location.reload()">Try to Reconnect</button>
</div> </div>
<script> <script>
// 检测网络状态变化 // Detect network status changes
window.addEventListener('online', () => { window.addEventListener('online', () => {
window.location.reload(); window.location.reload();
}); });

View file

@ -60,102 +60,102 @@ export default {
}; };
}, },
mounted() { mounted() {
// 只有在启用CDN时才添加相关事件和功能 // Only add related events and features when CDN is enabled
if (this.isCDNEnabled) { if (this.isCDNEnabled) {
// 添加全局快捷键Alt+C用于显示缓存查看器 // Add global shortcut Alt+C to show cache viewer
document.addEventListener('keydown', this.handleKeyDown); document.addEventListener('keydown', this.handleKeyDown);
// 在全局对象上添加缓存检查方法,便于调试 // Add cache check method to global object for debugging
window.checkCDNCacheStatus = () => { window.checkCDNCacheStatus = () => {
this.showCacheViewer = true; this.showCacheViewer = true;
}; };
// 在控制台输出提示信息 // Output hint information to console
console.info( console.info(
'%c[小智服务] CDN缓存检查工具已加载', '%c[XiaoZhi Service] CDN cache check tool loaded',
'color: #409EFF; font-weight: bold;' 'color: #409EFF; font-weight: bold;'
); );
console.info( console.info(
'按下 Alt+C 组合键或在控制台运行 checkCDNCacheStatus() 可以查看CDN缓存状态' 'Press Alt+C key combination or run checkCDNCacheStatus() in console to check CDN cache status'
); );
// 检查Service Worker状态 // Check Service Worker status
this.checkServiceWorkerStatus(); this.checkServiceWorkerStatus();
} else { } else {
console.info( console.info(
'%c[小智服务] CDN模式已禁用,使用本地打包资源', '%c[XiaoZhi Service] CDN mode disabled, using local packaged resources',
'color: #67C23A; font-weight: bold;' 'color: #67C23A; font-weight: bold;'
); );
} }
}, },
beforeDestroy() { beforeDestroy() {
// 只有在启用CDN时才需要移除事件监听 // Only need to remove event listeners when CDN is enabled
if (this.isCDNEnabled) { if (this.isCDNEnabled) {
document.removeEventListener('keydown', this.handleKeyDown); document.removeEventListener('keydown', this.handleKeyDown);
} }
}, },
methods: { methods: {
handleKeyDown(e) { handleKeyDown(e) {
// Alt+C 快捷键 // Alt+C shortcut key
if (e.altKey && e.key === 'c') { if (e.altKey && e.key === 'c') {
this.showCacheViewer = true; this.showCacheViewer = true;
} }
}, },
async checkServiceWorkerStatus() { async checkServiceWorkerStatus() {
// 检查Service Worker是否已注册 // Check if Service Worker is registered
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
try { try {
const registrations = await navigator.serviceWorker.getRegistrations(); const registrations = await navigator.serviceWorker.getRegistrations();
if (registrations.length > 0) { if (registrations.length > 0) {
console.info( console.info(
'%c[小智服务] Service Worker已注册', '%c[XiaoZhi Service] Service Worker registered',
'color: #67C23A; font-weight: bold;' 'color: #67C23A; font-weight: bold;'
); );
// 输出缓存状态到控制台 // Output cache status to console
setTimeout(async () => { setTimeout(async () => {
const hasCaches = await logCacheStatus(); const hasCaches = await logCacheStatus();
if (!hasCaches) { if (!hasCaches) {
console.info( console.info(
'%c[小智服务] 还未检测到缓存,请刷新页面或等待缓存建立', '%c[XiaoZhi Service] No cache detected yet, please refresh page or wait for cache to be built',
'color: #E6A23C; font-weight: bold;' 'color: #E6A23C; font-weight: bold;'
); );
// 开发环境下提供额外提示 // Provide additional hints in development environment
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
console.info( console.info(
'%c[小智服务] 在开发环境中,Service Worker可能无法正常初始化缓存', '%c[XiaoZhi Service] In development environment, Service Worker may not initialize cache properly',
'color: #E6A23C; font-weight: bold;' 'color: #E6A23C; font-weight: bold;'
); );
console.info('请尝试以下方法检查Service Worker是否生效:'); console.info('Please try the following methods to check if Service Worker is effective:');
console.info('1. 在开发者工具的Application/Application标签页中查看Service Worker状态'); console.info('1. Check Service Worker status in the Application/Application tab of developer tools');
console.info('2. 在开发者工具的Application/Cache/Cache Storage中查看缓存内容'); console.info('2. Check cache content in Application/Cache/Cache Storage of developer tools');
console.info('3. 使用生产构建(npm run build)并通过HTTP服务器访问以测试完整功能'); console.info('3. Use production build (npm run build) and access via HTTP server to test full functionality');
} }
} }
}, 2000); }, 2000);
} else { } else {
console.info( console.info(
'%c[小智服务] Service Worker未注册,CDN资源可能无法缓存', '%c[XiaoZhi Service] Service Worker not registered, CDN resources may not be cached',
'color: #F56C6C; font-weight: bold;' 'color: #F56C6C; font-weight: bold;'
); );
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
console.info( console.info(
'%c[小智服务] 在开发环境中,这是正常现象', '%c[XiaoZhi Service] This is normal in development environment',
'color: #E6A23C; font-weight: bold;' 'color: #E6A23C; font-weight: bold;'
); );
console.info('Service Worker通常只在生产环境中生效'); console.info('Service Worker usually only works in production environment');
console.info('要测试Service Worker功能:'); console.info('To test Service Worker functionality:');
console.info('1. 运行npm run build构建生产版本'); console.info('1. Run npm run build to build production version');
console.info('2. 通过HTTP服务器访问构建后的页面'); console.info('2. Access the built page via HTTP server');
} }
} }
} catch (error) { } catch (error) {
console.error('检查Service Worker状态失败:', error); console.error('Check Service Worker status failed:', error);
} }
} else { } else {
console.warn('当前浏览器不支持Service Worker,CDN资源缓存功能不可用'); console.warn('Current browser does not support Service Worker, CDN resource caching is unavailable');
} }
} }
} }

12
main/manager-web/src/apis/api.js Executable file → Normal file
View file

@ -1,4 +1,4 @@
// 引入各个模块的请求 // Import requests from various modules
import admin from './module/admin.js' import admin from './module/admin.js'
import agent from './module/agent.js' import agent from './module/agent.js'
import device from './module/device.js' import device from './module/device.js'
@ -9,21 +9,21 @@ import timbre from "./module/timbre.js"
import user from './module/user.js' import user from './module/user.js'
/** /**
* 接口地址 * API address
* 开发时自动读取使用.env.development文件 * Automatically read .env.development file during development
* 编译时自动读取使用.env.production文件 * Automatically read .env.production file during compilation
*/ */
const DEV_API_SERVICE = process.env.VUE_APP_API_BASE_URL const DEV_API_SERVICE = process.env.VUE_APP_API_BASE_URL
/** /**
* 根据开发环境返回接口url * Return API URL based on development environment
* @returns {string} * @returns {string}
*/ */
export function getServiceUrl() { export function getServiceUrl() {
return DEV_API_SERVICE return DEV_API_SERVICE
} }
/** request服务封装 */ /** Request service wrapper */
export default { export default {
getServiceUrl, getServiceUrl,
user, user,

22
main/manager-web/src/apis/httpRequest.js Executable file → Normal file
View file

@ -1,10 +1,10 @@
import Fly from 'flyio/dist/npm/fly'; import Fly from 'flyio/dist/npm/fly.js';
import store from '../store/index'; import store from '../store/index';
import Constant from '../utils/constant'; import Constant from '../utils/constant';
import { goToPage, isNotNull, showDanger, showWarning } from '../utils/index'; import { goToPage, isNotNull, showDanger, showWarning } from '../utils/index';
const fly = new Fly() const fly = new Fly()
// 设置超时 // Set timeout
fly.config.timeout = 30000 fly.config.timeout = 30000
/** /**
@ -25,13 +25,13 @@ function sendRequest() {
_data: {}, _data: {},
_header: { 'content-type': 'application/json; charset=utf-8' }, _header: { 'content-type': 'application/json; charset=utf-8' },
_url: '', _url: '',
_responseType: undefined, // 新增响应类型字段 _responseType: undefined, // Added response type field
'send'() { 'send'() {
if (isNotNull(store.getters.getToken)) { if (isNotNull(store.getters.getToken)) {
this._header.Authorization = 'Bearer ' + (JSON.parse(store.getters.getToken)).token this._header.Authorization = 'Bearer ' + (JSON.parse(store.getters.getToken)).token
} }
// 打印请求信息 // Log request information
fly.request(this._url, this._data, { fly.request(this._url, this._data, {
method: this._method, method: this._method,
headers: this._header, headers: this._header,
@ -46,7 +46,7 @@ function sendRequest() {
this._sucCallback(res) this._sucCallback(res)
} }
}).catch((res) => { }).catch((res) => {
// 打印失败响应 // Log failed response
console.log('catch', res) console.log('catch', res)
httpHandlerError(res, this._failCallback, this._networkFailCallback) httpHandlerError(res, this._failCallback, this._networkFailCallback)
}) })
@ -90,7 +90,7 @@ function sendRequest() {
'async'(flag) { 'async'(flag) {
this.async = flag this.async = flag
}, },
// 新增类型设置方法 // Added type setting method
'type'(responseType) { 'type'(responseType) {
this._responseType = responseType; this._responseType = responseType;
return this; return this;
@ -99,14 +99,14 @@ function sendRequest() {
} }
/** /**
* Info 请求完成后返回信息 * Info information returned after request completion
* failCallback 回调函数 * failCallback 回调函数
* networkFailCallback 回调函数 * networkFailCallback 回调函数
*/ */
// 在错误处理函数中添加日志 // 在错误处理函数中添加日志
function httpHandlerError(info, failCallback, networkFailCallback) { function httpHandlerError(info, failCallback, networkFailCallback) {
/** 请求成功,退出该函数 可以根据项目需求来判断是否请求成功。这里判断的是status为200的时候是成功 */ /** Request successful, exit function. Success can be determined based on project requirements. Here, status 200 indicates success */
let networkError = false let networkError = false
if (info.status === 200) { if (info.status === 200) {
if (info.data.code === 'success' || info.data.code === 0 || info.data.code === undefined) { if (info.data.code === 'success' || info.data.code === 0 || info.data.code === undefined) {
@ -127,7 +127,7 @@ function httpHandlerError(info, failCallback, networkFailCallback) {
if (networkFailCallback) { if (networkFailCallback) {
networkFailCallback(info) networkFailCallback(info)
} else { } else {
showDanger(`网络请求出现了错误【${info.status}】`) showDanger(`Network request error [${info.status}]`)
} }
return true return true
} }
@ -142,9 +142,9 @@ function reAjaxFun(fn) {
} }
let ajaxIndex = parseInt((nowTimeSec - requestTime) / reAjaxSec) let ajaxIndex = parseInt((nowTimeSec - requestTime) / reAjaxSec)
if (ajaxIndex > 10) { if (ajaxIndex > 10) {
showWarning('似乎无法连接服务器') showWarning('Unable to connect to server')
} else { } else {
showWarning('正在连接服务器(' + ajaxIndex + ')') showWarning('Connecting to server (' + ajaxIndex + ')')
} }
if (ajaxIndex < 10 && fn) { if (ajaxIndex < 10 && fn) {
setTimeout(() => { setTimeout(() => {

View file

@ -3,7 +3,7 @@ import RequestService from '../httpRequest';
export default { export default {
// 用户列表 // User list
getUserList(params, callback) { getUserList(params, callback) {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
page: params.page, page: params.page,
@ -19,13 +19,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('请求失败:', err) console.error('Request failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getUserList(callback) this.getUserList(callback)
}) })
}).send() }).send()
}, },
// 删除用户 // Delete user
deleteUser(id, callback) { deleteUser(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/users/${id}`) .url(`${getServiceUrl()}/admin/users/${id}`)
@ -35,13 +35,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('删除失败:', err) console.error('Delete failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteUser(id, callback) this.deleteUser(id, callback)
}) })
}).send() }).send()
}, },
// 重置用户密码 // Reset user password
resetUserPassword(id, callback) { resetUserPassword(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/users/${id}`) .url(`${getServiceUrl()}/admin/users/${id}`)
@ -51,13 +51,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('重置密码失败:', err) console.error('Reset password failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.resetUserPassword(id, callback) this.resetUserPassword(id, callback)
}) })
}).send() }).send()
}, },
// 获取参数列表 // Get parameters list
getParamsList(params, callback) { getParamsList(params, callback) {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
page: params.page, page: params.page,
@ -73,13 +73,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取参数列表失败:', err) console.error('Get parameters list failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getParamsList(params, callback) this.getParamsList(params, callback)
}) })
}).send() }).send()
}, },
// 保存 // Save
addParam(data, callback) { addParam(data, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/params`) .url(`${getServiceUrl()}/admin/params`)
@ -90,13 +90,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('添加参数失败:', err) console.error('Add parameter failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.addParam(data, callback) this.addParam(data, callback)
}) })
}).send() }).send()
}, },
// 修改 // Update
updateParam(data, callback) { updateParam(data, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/params`) .url(`${getServiceUrl()}/admin/params`)
@ -107,13 +107,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('更新参数失败:', err) console.error('Update parameter failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateParam(data, callback) this.updateParam(data, callback)
}) })
}).send() }).send()
}, },
// 删除 // Delete
deleteParam(ids, callback) { deleteParam(ids, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/params/delete`) .url(`${getServiceUrl()}/admin/params/delete`)
@ -124,13 +124,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('删除参数失败:', err) console.error('Delete parameter failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteParam(ids, callback) this.deleteParam(ids, callback)
}) })
}).send() }).send()
}, },
// 获取ws服务端列表 // Get WS server list
getWsServerList(params, callback) { getWsServerList(params, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/server/server-list`) .url(`${getServiceUrl()}/admin/server/server-list`)
@ -140,13 +140,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取ws服务端列表失败:', err) console.error('Get WS server list failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getWsServerList(params, callback) this.getWsServerList(params, callback)
}) })
}).send(); }).send();
}, },
// 发送ws服务器动作指令 // Send WS server action command
sendWsServerAction(data, callback) { sendWsServerAction(data, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/server/emit-action`) .url(`${getServiceUrl()}/admin/server/emit-action`)

View file

@ -3,7 +3,7 @@ import RequestService from '../httpRequest';
export default { export default {
// 获取智能体列表 // Get agent list
getAgentList(callback) { getAgentList(callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/list`) .url(`${getServiceUrl()}/agent/list`)
@ -18,7 +18,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 添加智能体 // Add agent
addAgent(agentName, callback) { addAgent(agentName, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent`) .url(`${getServiceUrl()}/agent`)
@ -34,7 +34,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 删除智能体 // Delete agent
deleteAgent(agentId, callback) { deleteAgent(agentId, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/${agentId}`) .url(`${getServiceUrl()}/agent/${agentId}`)
@ -49,7 +49,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 获取智能体配置 // Get agent configuration
getDeviceConfig(agentId, callback) { getDeviceConfig(agentId, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/${agentId}`) .url(`${getServiceUrl()}/agent/${agentId}`)
@ -59,13 +59,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取配置失败:', err); console.error('Get configuration failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getDeviceConfig(agentId, callback); this.getDeviceConfig(agentId, callback);
}); });
}).send(); }).send();
}, },
// 配置智能体 // Configure agent
updateAgentConfig(agentId, configData, callback) { updateAgentConfig(agentId, configData, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/${agentId}`) .url(`${getServiceUrl()}/agent/${agentId}`)
@ -81,8 +81,8 @@ export default {
}); });
}).send(); }).send();
}, },
// 新增方法:获取智能体模板 // New method: Get agent template
getAgentTemplate(callback) { // 移除templateName参数 getAgentTemplate(callback) { // Remove templateName parameter
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/template`) .url(`${getServiceUrl()}/agent/template`)
.method('GET') .method('GET')
@ -91,13 +91,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取模板失败:', err); console.error('Get template failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getAgentTemplate(callback); this.getAgentTemplate(callback);
}); });
}).send(); }).send();
}, },
// 获取智能体会话列表 // Get agent sessions list
getAgentSessions(agentId, params, callback) { getAgentSessions(agentId, params, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/${agentId}/sessions`) .url(`${getServiceUrl()}/agent/${agentId}/sessions`)
@ -113,7 +113,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 获取智能体聊天记录 // Get agent chat history
getAgentChatHistory(agentId, sessionId, callback) { getAgentChatHistory(agentId, sessionId, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/${agentId}/chat-history/${sessionId}`) .url(`${getServiceUrl()}/agent/${agentId}/chat-history/${sessionId}`)
@ -128,7 +128,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 获取音频下载ID // Get audio download ID
getAudioId(audioId, callback) { getAudioId(audioId, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/audio/${audioId}`) .url(`${getServiceUrl()}/agent/audio/${audioId}`)
@ -143,7 +143,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 获取智能体的MCP接入点地址 // Get agent MCP access address
getAgentMcpAccessAddress(agentId, callback) { getAgentMcpAccessAddress(agentId, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/mcp/address/${agentId}`) .url(`${getServiceUrl()}/agent/mcp/address/${agentId}`)
@ -158,7 +158,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 获取智能体的MCP工具列表 // Get agent MCP tools list
getAgentMcpToolsList(agentId, callback) { getAgentMcpToolsList(agentId, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/mcp/tools/${agentId}`) .url(`${getServiceUrl()}/agent/mcp/tools/${agentId}`)

View file

@ -2,7 +2,7 @@ import { getServiceUrl } from '../api';
import RequestService from '../httpRequest'; import RequestService from '../httpRequest';
export default { export default {
// 已绑设备 // Bound devices
getAgentBindDevices(agentId, callback) { getAgentBindDevices(agentId, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/device/bind/${agentId}`) .url(`${getServiceUrl()}/device/bind/${agentId}`)
@ -12,13 +12,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取设备列表失败:', err); console.error('Get device list failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getAgentBindDevices(agentId, callback); this.getAgentBindDevices(agentId, callback);
}); });
}).send(); }).send();
}, },
// 解绑设备 // Unbind device
unbindDevice(device_id, callback) { unbindDevice(device_id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/device/unbind`) .url(`${getServiceUrl()}/device/unbind`)
@ -29,13 +29,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('解绑设备失败:', err); console.error('Unbind device failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.unbindDevice(device_id, callback); this.unbindDevice(device_id, callback);
}); });
}).send(); }).send();
}, },
// 绑定设备 // Bind device
bindDevice(agentId, deviceCode, callback) { bindDevice(agentId, deviceCode, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/device/bind/${agentId}/${deviceCode}`) .url(`${getServiceUrl()}/device/bind/${agentId}/${deviceCode}`)
@ -45,7 +45,7 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('绑定设备失败:', err); console.error('Bind device failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.bindDevice(agentId, deviceCode, callback); this.bindDevice(agentId, deviceCode, callback);
}); });
@ -61,14 +61,14 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('更新OTA状态失败:', err) console.error('Update OTA status failed:', err)
this.$message.error(err.msg || '更新OTA状态失败') this.$message.error(err.msg || 'Update OTA status failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateDeviceInfo(id, payload, callback) this.updateDeviceInfo(id, payload, callback)
}) })
}).send() }).send()
}, },
// 手动添加设备 // Manually add device
manualAddDevice(params, callback) { manualAddDevice(params, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/device/manual-add`) .url(`${getServiceUrl()}/device/manual-add`)
@ -79,7 +79,7 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('手动添加设备失败:', err); console.error('Manually add device failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.manualAddDevice(params, callback); this.manualAddDevice(params, callback);
}); });

View file

@ -2,7 +2,7 @@ import { getServiceUrl } from '../api';
import RequestService from '../httpRequest'; import RequestService from '../httpRequest';
export default { export default {
// 获取字典类型列表 // Get dictionary type list
getDictTypeList(params, callback) { getDictTypeList(params, callback) {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
dictType: params.dictType || '', dictType: params.dictType || '',
@ -19,15 +19,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取字典类型列表失败:', err) console.error('Get dictionary type list failed:', err)
this.$message.error(err.msg || '获取字典类型列表失败') this.$message.error(err.msg || 'Get dictionary type list failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getDictTypeList(params, callback) this.getDictTypeList(params, callback)
}) })
}).send() }).send()
}, },
// 获取字典类型详情 // Get dictionary type details
getDictTypeDetail(id, callback) { getDictTypeDetail(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/type/${id}`) .url(`${getServiceUrl()}/admin/dict/type/${id}`)
@ -37,15 +37,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取字典类型详情失败:', err) console.error('Get dictionary type details failed:', err)
this.$message.error(err.msg || '获取字典类型详情失败') this.$message.error(err.msg || 'Get dictionary type details failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getDictTypeDetail(id, callback) this.getDictTypeDetail(id, callback)
}) })
}).send() }).send()
}, },
// 新增字典类型 // Add dictionary type
addDictType(data, callback) { addDictType(data, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/type/save`) .url(`${getServiceUrl()}/admin/dict/type/save`)
@ -56,15 +56,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('新增字典类型失败:', err) console.error('Add dictionary type failed:', err)
this.$message.error(err.msg || '新增字典类型失败') this.$message.error(err.msg || 'Add dictionary type failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.addDictType(data, callback) this.addDictType(data, callback)
}) })
}).send() }).send()
}, },
// 更新字典类型 // Update dictionary type
updateDictType(data, callback) { updateDictType(data, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/type/update`) .url(`${getServiceUrl()}/admin/dict/type/update`)
@ -75,15 +75,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('更新字典类型失败:', err) console.error('Update dictionary type failed:', err)
this.$message.error(err.msg || '更新字典类型失败') this.$message.error(err.msg || 'Update dictionary type failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateDictType(data, callback) this.updateDictType(data, callback)
}) })
}).send() }).send()
}, },
// 删除字典类型 // Delete dictionary type
deleteDictType(ids, callback) { deleteDictType(ids, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/type/delete`) .url(`${getServiceUrl()}/admin/dict/type/delete`)
@ -94,15 +94,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('删除字典类型失败:', err) console.error('Delete dictionary type failed:', err)
this.$message.error(err.msg || '删除字典类型失败') this.$message.error(err.msg || 'Delete dictionary type failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteDictType(ids, callback) this.deleteDictType(ids, callback)
}) })
}).send() }).send()
}, },
// 获取字典数据列表 // Get dictionary data list by type
getDictDataList(params, callback) { getDictDataList(params, callback) {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
dictTypeId: params.dictTypeId, dictTypeId: params.dictTypeId,
@ -128,7 +128,7 @@ export default {
}).send() }).send()
}, },
// 获取字典数据详情 // Get dictionary data details
getDictDataDetail(id, callback) { getDictDataDetail(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/data/${id}`) .url(`${getServiceUrl()}/admin/dict/data/${id}`)
@ -138,15 +138,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取字典数据详情失败:', err) console.error('Get dictionary data details failed:', err)
this.$message.error(err.msg || '获取字典数据详情失败') this.$message.error(err.msg || 'Get dictionary data details failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getDictDataDetail(id, callback) this.getDictDataDetail(id, callback)
}) })
}).send() }).send()
}, },
// 新增字典数据 // Add dictionary data
addDictData(data, callback) { addDictData(data, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/data/save`) .url(`${getServiceUrl()}/admin/dict/data/save`)
@ -157,15 +157,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('新增字典数据失败:', err) console.error('Add dictionary data failed:', err)
this.$message.error(err.msg || '新增字典数据失败') this.$message.error(err.msg || 'Add dictionary data failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.addDictData(data, callback) this.addDictData(data, callback)
}) })
}).send() }).send()
}, },
// 更新字典数据 // Update dictionary data
updateDictData(data, callback) { updateDictData(data, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/data/update`) .url(`${getServiceUrl()}/admin/dict/data/update`)
@ -176,15 +176,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('更新字典数据失败:', err) console.error('Update dictionary data failed:', err)
this.$message.error(err.msg || '更新字典数据失败') this.$message.error(err.msg || 'Update dictionary data failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateDictData(data, callback) this.updateDictData(data, callback)
}) })
}).send() }).send()
}, },
// 删除字典数据 // Delete dictionary data
deleteDictData(ids, callback) { deleteDictData(ids, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/admin/dict/data/delete`) .url(`${getServiceUrl()}/admin/dict/data/delete`)
@ -195,15 +195,15 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('删除字典数据失败:', err) console.error('Delete dictionary data failed:', err)
this.$message.error(err.msg || '删除字典数据失败') this.$message.error(err.msg || 'Delete dictionary data failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteDictData(ids, callback) this.deleteDictData(ids, callback)
}) })
}).send() }).send()
}, },
// 获取字典数据列表 // Get dictionary data list by type
getDictDataByType(dictType) { getDictDataByType(dictType) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
RequestService.sendRequest() RequestService.sendRequest()
@ -214,11 +214,11 @@ export default {
if (res.data && res.data.code === 0) { if (res.data && res.data.code === 0) {
resolve(res.data) resolve(res.data)
} else { } else {
reject(new Error(res.data?.msg || '获取字典数据列表失败')) reject(new Error(res.data?.msg || 'Get dictionary data list failed'))
} }
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取字典数据列表失败:', err) console.error('Get dictionary data list failed:', err)
reject(err) reject(err)
}).send() }).send()
}) })

View file

@ -2,7 +2,7 @@ import { getServiceUrl } from '../api';
import RequestService from '../httpRequest'; import RequestService from '../httpRequest';
export default { export default {
// 获取模型配置列表 // Get model configuration list
getModelList(params, callback) { getModelList(params, callback) {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
modelType: params.modelType, modelType: params.modelType,
@ -19,13 +19,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取模型列表失败:', err) console.error('Get model list failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getModelList(params, callback) this.getModelList(params, callback)
}) })
}).send() }).send()
}, },
// 获取模型供应器列表 // Get model provider list
getModelProviders(modelType, callback) { getModelProviders(modelType, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/${modelType}/provideTypes`) .url(`${getServiceUrl()}/models/${modelType}/provideTypes`)
@ -35,15 +35,15 @@ export default {
callback(res.data?.data || []) callback(res.data?.data || [])
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取供应器列表失败:', err) console.error('Get provider list failed:', err)
this.$message.error('获取供应器列表失败') this.$message.error('Get provider list failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getModelProviders(modelType, callback) this.getModelProviders(modelType, callback)
}) })
}).send() }).send()
}, },
// 新增模型配置 // Add model configuration
addModel(params, callback) { addModel(params, callback) {
const { modelType, provideCode, formData } = params; const { modelType, provideCode, formData } = params;
const postData = { const postData = {
@ -66,14 +66,14 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('新增模型失败:', err) console.error('Add model failed:', err)
this.$message.error(err.msg || '新增模型失败') this.$message.error(err.msg || 'Add model failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.addModel(params, callback) this.addModel(params, callback)
}) })
}).send() }).send()
}, },
// 删除模型配置 // Delete model configuration
deleteModel(id, callback) { deleteModel(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/${id}`) .url(`${getServiceUrl()}/models/${id}`)
@ -83,14 +83,14 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('删除模型失败:', err) console.error('Delete model failed:', err)
this.$message.error(err.msg || '删除模型失败') this.$message.error(err.msg || 'Delete model failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteModel(id, callback) this.deleteModel(id, callback)
}) })
}).send() }).send()
}, },
// 获取模型名称列表 // Get model name list
getModelNames(modelType, modelName, callback) { getModelNames(modelType, modelName, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/names`) .url(`${getServiceUrl()}/models/names`)
@ -106,7 +106,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 获取模型音色列表 // Get model voice list
getModelVoices(modelId, voiceName, callback) { getModelVoices(modelId, voiceName, callback) {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
voiceName: voiceName || '' voiceName: voiceName || ''
@ -124,7 +124,7 @@ export default {
}); });
}).send(); }).send();
}, },
// 获取单个模型配置 // Get single model configuration
getModelConfig(id, callback) { getModelConfig(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/${id}`) .url(`${getServiceUrl()}/models/${id}`)
@ -134,14 +134,14 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取模型配置失败:', err) console.error('Get model configuration failed:', err)
this.$message.error(err.msg || '获取模型配置失败') this.$message.error(err.msg || 'Get model configuration failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getModelConfig(id, callback) this.getModelConfig(id, callback)
}) })
}).send() }).send()
}, },
// 启用/禁用模型状态 // Enable/Disable model status
updateModelStatus(id, status, callback) { updateModelStatus(id, status, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/enable/${id}/${status}`) .url(`${getServiceUrl()}/models/enable/${id}/${status}`)
@ -151,14 +151,14 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('更新模型状态失败:', err) console.error('Update model status failed:', err)
this.$message.error(err.msg || '更新模型状态失败') this.$message.error(err.msg || 'Update model status failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateModelStatus(id, status, callback) this.updateModelStatus(id, status, callback)
}) })
}).send() }).send()
}, },
// 更新模型配置 // Update model configuration
updateModel(params, callback) { updateModel(params, callback) {
const { modelType, provideCode, id, formData } = params; const { modelType, provideCode, id, formData } = params;
const payload = { const payload = {
@ -174,14 +174,14 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('更新模型失败:', err); console.error('Update model failed:', err);
this.$message.error(err.msg || '更新模型失败'); this.$message.error(err.msg || 'Update model failed');
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateModel(params, callback); this.updateModel(params, callback);
}); });
}).send(); }).send();
}, },
// 设置默认模型 // Set default model
setDefaultModel(id, callback) { setDefaultModel(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/default/${id}`) .url(`${getServiceUrl()}/models/default/${id}`)
@ -191,8 +191,8 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('设置默认模型失败:', err) console.error('Set default model failed:', err)
this.$message.error(err.msg || '设置默认模型失败') this.$message.error(err.msg || 'Set default model failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.setDefaultModel(id, callback) this.setDefaultModel(id, callback)
}) })
@ -200,9 +200,9 @@ export default {
}, },
/** /**
* 获取模型配置列表(支持查询参数) * Get model configuration list (supports query parameters)
* @param {Object} params - 查询参数对象,例如 { name: 'test', modelType: 1 } * @param {Object} params - Query parameter object, e.g., { name: 'test', modelType: 1 }
* @param {Function} callback - 回调函数 * @param {Function} callback - Callback function
*/ */
getModelProvidersPage(params, callback) { getModelProvidersPage(params, callback) {
// 构建查询参数 // 构建查询参数
@ -220,7 +220,7 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
this.$message.error(err.msg || '获取供应器列表失败'); this.$message.error(err.msg || 'Get provider list failed');
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getModelProviders(params, callback); this.getModelProviders(params, callback);
}); });
@ -228,9 +228,9 @@ export default {
}, },
/** /**
* 新增模型供应器配置 * Add model provider configuration
* @param {Object} params - 请求参数对象,例如 { modelType: '1', providerCode: '1', name: '1', fields: '1', sort: 1 } * @param {Object} params - Request parameter object, e.g., { modelType: '1', providerCode: '1', name: '1', fields: '1', sort: 1 }
* @param {Function} callback - 成功回调函数 * @param {Function} callback - Success callback function
*/ */
addModelProvider(params, callback) { addModelProvider(params, callback) {
const postData = { const postData = {
@ -250,8 +250,8 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('新增模型供应器失败:', err) console.error('Add model provider failed:', err)
this.$message.error(err.msg || '新增模型供应器失败') this.$message.error(err.msg || 'Add model provider failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.addModelProvider(params, callback); this.addModelProvider(params, callback);
}); });
@ -259,9 +259,9 @@ export default {
}, },
/** /**
* 更新模型供应器配置 * Update model provider configuration
* @param {Object} params - 请求参数对象,例如 { id: '111', modelType: '1', providerCode: '1', name: '1', fields: '1', sort: 1 } * @param {Object} params - Request parameter object, e.g., { id: '111', modelType: '1', providerCode: '1', name: '1', fields: '1', sort: 1 }
* @param {Function} callback - 成功回调函数 * @param {Function} callback - Success callback function
*/ */
updateModelProvider(params, callback) { updateModelProvider(params, callback) {
const putData = { const putData = {
@ -282,13 +282,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
this.$message.error(err.msg || '更新模型供应器失败') this.$message.error(err.msg || 'Update model provider failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateModelProvider(params, callback); this.updateModelProvider(params, callback);
}); });
}).send(); }).send();
}, },
// 删除 // Delete
deleteModelProviderByIds(ids, callback) { deleteModelProviderByIds(ids, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/provider/delete`) .url(`${getServiceUrl()}/models/provider/delete`)
@ -299,13 +299,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
this.$message.error(err.msg || '删除模型供应器失败') this.$message.error(err.msg || 'Delete model provider failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteModelProviderByIds(ids, callback) this.deleteModelProviderByIds(ids, callback)
}) })
}).send() }).send()
}, },
// 获取插件列表 // Get plugin list
getPluginFunctionList(params, callback) { getPluginFunctionList(params, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/provider/plugin/names`) .url(`${getServiceUrl()}/models/provider/plugin/names`)
@ -315,7 +315,7 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
this.$message.error(err.msg || '获取插件列表失败') this.$message.error(err.msg || 'Get plugin list failed')
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getPluginFunctionList(params, callback) this.getPluginFunctionList(params, callback)
}) })

View file

@ -2,7 +2,7 @@ import { getServiceUrl } from '../api';
import RequestService from '../httpRequest'; import RequestService from '../httpRequest';
export default { export default {
// 分页查询OTA固件信息 // Paginated query OTA firmware information
getOtaList(params, callback) { getOtaList(params, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/otaMag`) .url(`${getServiceUrl()}/otaMag`)
@ -13,13 +13,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取OTA固件列表失败:', err); console.error('Get OTA firmware list failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getOtaList(params, callback); this.getOtaList(params, callback);
}); });
}).send(); }).send();
}, },
// 获取单个OTA固件信息 // Get single OTA firmware information
getOtaInfo(id, callback) { getOtaInfo(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/otaMag/${id}`) .url(`${getServiceUrl()}/otaMag/${id}`)
@ -29,13 +29,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取OTA固件信息失败:', err); console.error('Get OTA firmware information failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getOtaInfo(id, callback); this.getOtaInfo(id, callback);
}); });
}).send(); }).send();
}, },
// 保存OTA固件信息 // Save OTA firmware information
saveOta(entity, callback) { saveOta(entity, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/otaMag`) .url(`${getServiceUrl()}/otaMag`)
@ -46,13 +46,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('保存OTA固件信息失败:', err); console.error('Save OTA firmware information failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.saveOta(entity, callback); this.saveOta(entity, callback);
}); });
}).send(); }).send();
}, },
// 更新OTA固件信息 // Update OTA firmware information
updateOta(id, entity, callback) { updateOta(id, entity, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/otaMag/${id}`) .url(`${getServiceUrl()}/otaMag/${id}`)
@ -63,13 +63,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('更新OTA固件信息失败:', err); console.error('Update OTA firmware information failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateOta(id, entity, callback); this.updateOta(id, entity, callback);
}); });
}).send(); }).send();
}, },
// 删除OTA固件 // Delete OTA firmware
deleteOta(id, callback) { deleteOta(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/otaMag/${id}`) .url(`${getServiceUrl()}/otaMag/${id}`)
@ -79,13 +79,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('删除OTA固件失败:', err); console.error('Delete OTA firmware failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteOta(id, callback); this.deleteOta(id, callback);
}); });
}).send(); }).send();
}, },
// 上传固件文件 // Upload firmware file
uploadFirmware(file, callback) { uploadFirmware(file, callback) {
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
@ -98,13 +98,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('上传固件文件失败:', err); console.error('Upload firmware file failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.uploadFirmware(file, callback); this.uploadFirmware(file, callback);
}); });
}).send(); }).send();
}, },
// 获取固件下载链接 // Get firmware download link
getDownloadUrl(id, callback) { getDownloadUrl(id, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/otaMag/getDownloadUrl/${id}`) .url(`${getServiceUrl()}/otaMag/getDownloadUrl/${id}`)
@ -114,7 +114,7 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取下载链接失败:', err); console.error('Get download link failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getDownloadUrl(id, callback); this.getDownloadUrl(id, callback);
}); });

View file

@ -2,7 +2,7 @@ import { getServiceUrl } from '../api';
import RequestService from '../httpRequest'; import RequestService from '../httpRequest';
export default { export default {
// 获取音色 // Get voice list
getVoiceList(params, callback) { getVoiceList(params, callback) {
const queryParams = new URLSearchParams({ const queryParams = new URLSearchParams({
ttsModelId: params.ttsModelId, ttsModelId: params.ttsModelId,
@ -19,13 +19,13 @@ export default {
callback(res.data || []); callback(res.data || []);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取音色列表失败:', err); console.error('Get voice list failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getVoiceList(params, callback); this.getVoiceList(params, callback);
}); });
}).send(); }).send();
}, },
// 音色保存 // Save voice
saveVoice(params, callback) { saveVoice(params, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/ttsVoice`) .url(`${getServiceUrl()}/ttsVoice`)
@ -45,13 +45,13 @@ export default {
callback(res.data); callback(res.data);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('保存音色失败:', err); console.error('Save voice failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.saveVoice(params, callback); this.saveVoice(params, callback);
}); });
}).send(); }).send();
}, },
// 音色删除 // Delete voice
deleteVoice(ids, callback) { deleteVoice(ids, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/ttsVoice/delete`) .url(`${getServiceUrl()}/ttsVoice/delete`)
@ -62,13 +62,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('删除音色失败:', err); console.error('Delete voice failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.deleteVoice(ids, callback); this.deleteVoice(ids, callback);
}); });
}).send(); }).send();
}, },
// 音色修改 // Update voice
updateVoice(params, callback) { updateVoice(params, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/ttsVoice/${params.id}`) .url(`${getServiceUrl()}/ttsVoice/${params.id}`)
@ -87,7 +87,7 @@ export default {
callback(res.data); callback(res.data);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('修改音色失败:', err); console.error('Update voice failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.updateVoice(params, callback); this.updateVoice(params, callback);
}); });

30
main/manager-web/src/apis/module/user.js Executable file → Normal file
View file

@ -3,7 +3,7 @@ import RequestService from '../httpRequest'
export default { export default {
// 登录 // Login
login(loginForm, callback, failCallback) { login(loginForm, callback, failCallback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/login`) .url(`${getServiceUrl()}/user/login`)
@ -23,7 +23,7 @@ export default {
}) })
}).send() }).send()
}, },
// 获取验证码 // Get verification code
getCaptcha(uuid, callback) { getCaptcha(uuid, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/captcha?uuid=${uuid}`) .url(`${getServiceUrl()}/user/captcha?uuid=${uuid}`)
@ -38,11 +38,11 @@ export default {
RequestService.clearRequestTime(); RequestService.clearRequestTime();
callback(res); callback(res);
}) })
.networkFail((err) => { // 添加错误参数 .networkFail((err) => { // Add error parameter
}).send() }).send()
}, },
// 发送短信验证码 // Send SMS verification code
sendSmsVerification(data, callback, failCallback) { sendSmsVerification(data, callback, failCallback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/smsVerification`) .url(`${getServiceUrl()}/user/smsVerification`)
@ -62,7 +62,7 @@ export default {
}) })
}).send() }).send()
}, },
// 注册账号 // Register account
register(registerForm, callback, failCallback) { register(registerForm, callback, failCallback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/register`) .url(`${getServiceUrl()}/user/register`)
@ -82,7 +82,7 @@ export default {
}) })
}).send() }).send()
}, },
// 保存设备配置 // Save device configuration
saveDeviceConfig(device_id, configData, callback) { saveDeviceConfig(device_id, configData, callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/configDevice/${device_id}`) .url(`${getServiceUrl()}/user/configDevice/${device_id}`)
@ -93,13 +93,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('保存配置失败:', err); console.error('Save configuration failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.saveDeviceConfig(device_id, configData, callback); this.saveDeviceConfig(device_id, configData, callback);
}); });
}).send(); }).send();
}, },
// 用户信息获取 // Get user information
getUserInfo(callback) { getUserInfo(callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/info`) .url(`${getServiceUrl()}/user/info`)
@ -109,13 +109,13 @@ export default {
callback(res) callback(res)
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('接口请求失败:', err) console.error('API request failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getUserInfo(callback) this.getUserInfo(callback)
}) })
}).send() }).send()
}, },
// 修改用户密码 // Change user password
changePassword(oldPassword, newPassword, successCallback, errorCallback) { changePassword(oldPassword, newPassword, successCallback, errorCallback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/change-password`) .url(`${getServiceUrl()}/user/change-password`)
@ -135,7 +135,7 @@ export default {
}) })
.send(); .send();
}, },
// 修改用户状态 // Change user status
changeUserStatus(status, userIds, successCallback) { changeUserStatus(status, userIds, successCallback) {
console.log(555, userIds) console.log(555, userIds)
RequestService.sendRequest() RequestService.sendRequest()
@ -147,13 +147,13 @@ export default {
successCallback(res); successCallback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('修改用户状态失败:', err) console.error('Change user status failed:', err)
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.changeUserStatus(status, userIds) this.changeUserStatus(status, userIds)
}) })
}).send() }).send()
}, },
// 获取公共配置 // Get public configuration
getPubConfig(callback) { getPubConfig(callback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/pub-config`) .url(`${getServiceUrl()}/user/pub-config`)
@ -163,13 +163,13 @@ export default {
callback(res); callback(res);
}) })
.networkFail((err) => { .networkFail((err) => {
console.error('获取公共配置失败:', err); console.error('Get public configuration failed:', err);
RequestService.reAjaxFun(() => { RequestService.reAjaxFun(() => {
this.getPubConfig(callback); this.getPubConfig(callback);
}); });
}).send(); }).send();
}, },
// 找回用户密码 // Retrieve user password
retrievePassword(passwordData, callback, failCallback) { retrievePassword(passwordData, callback, failCallback) {
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/user/retrieve-password`) .url(`${getServiceUrl()}/user/retrieve-password`)

View file

@ -6,24 +6,24 @@
style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;"> style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
<img src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" /> <img src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" />
</div> </div>
添加设备 Add Device
</div> </div>
<div style="height: 1px;background: #e8f0ff;" /> <div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;"> <div style="margin: 22px 15px;">
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> <div style="color: red;display: inline-block;">*</div>
<span style="font-size: 11px"> 验证码:</span> <span style="font-size: 11px"> Verification Code:</span>
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input placeholder="请输入设备播报的6位数验证码.." v-model="deviceCode" @keyup.enter.native="confirm" /> <el-input placeholder="Please enter the 6-digit verification code announced by the device.." v-model="deviceCode" @keyup.enter.native="confirm" />
</div> </div>
</div> </div>
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="confirm"> <div class="dialog-btn" @click="confirm">
确定 Confirm
</div> </div>
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel"> <div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel">
取消 Cancel
</div> </div>
</div> </div>
</el-dialog> </el-dialog>
@ -47,7 +47,7 @@ export default {
methods: { methods: {
confirm() { confirm() {
if (!/^\d{6}$/.test(this.deviceCode)) { if (!/^\d{6}$/.test(this.deviceCode)) {
this.$message.error('请输入6位数字验证码'); this.$message.error('Please enter a 6-digit verification code');
return; return;
} }
this.loading = true; this.loading = true;
@ -58,13 +58,13 @@ export default {
if (data.code === 0) { if (data.code === 0) {
this.$emit('refresh'); this.$emit('refresh');
this.$message.success({ this.$message.success({
message: '设备绑定成功', message: 'Device binding successful',
showClose: true showClose: true
}); });
this.closeDialog(); this.closeDialog();
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '绑定失败', message: data.msg || 'Binding failed',
showClose: true showClose: true
}); });
} }

View file

@ -3,7 +3,7 @@
custom-class="custom-dialog" :show-close="false" class="center-dialog"> custom-class="custom-dialog" :show-close="false" class="center-dialog">
<div style="margin: 0 18px; text-align: left; padding: 10px; border-radius: 10px;"> <div style="margin: 0 18px; text-align: left; padding: 10px; border-radius: 10px;">
<div style="font-size: 30px; color: #3d4566; margin-top: -10px; margin-bottom: 10px; text-align: center;"> <div style="font-size: 30px; color: #3d4566; margin-top: -10px; margin-bottom: 10px; text-align: center;">
添加模型 Add Model
</div> </div>
<button class="custom-close-btn" @click="handleClose"> <button class="custom-close-btn" @click="handleClose">
@ -12,14 +12,14 @@
<!-- 模型信息部分 --> <!-- 模型信息部分 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div style="font-size: 20px; font-weight: bold; color: #3d4566;">模型信息</div> <div style="font-size: 20px; font-weight: bold; color: #3d4566;">Model Information</div>
<div style="display: flex; align-items: center; gap: 20px;"> <div style="display: flex; align-items: center; gap: 20px;">
<div style="display: flex; align-items: center;"> <div style="display: flex; align-items: center;">
<span style="margin-right: 8px;">是否启用</span> <span style="margin-right: 8px;">Enable</span>
<el-switch v-model="formData.isEnabled" class="custom-switch"></el-switch> <el-switch v-model="formData.isEnabled" class="custom-switch"></el-switch>
</div> </div>
<div style="display: none; align-items: center;"> <div style="display: none; align-items: center;">
<span style="margin-right: 8px;">设为默认</span> <span style="margin-right: 8px;">Set as Default</span>
<el-switch v-model="formData.isDefault" class="custom-switch"></el-switch> <el-switch v-model="formData.isDefault" class="custom-switch"></el-switch>
</div> </div>
</div> </div>
@ -28,38 +28,38 @@
<div style="height: 2px; background: #e9e9e9; margin-bottom: 22px;"></div> <div style="height: 2px; background: #e9e9e9; margin-bottom: 22px;"></div>
<el-form :model="formData" label-width="100px" label-position="left" class="custom-form"> <el-form :model="formData" label-width="100px" label-position="left" class="custom-form">
<div style="display: flex; gap: 20px; margin-bottom: 0;"> <div style="display: flex; gap: 20px; margin-bottom: 0;">
<el-form-item label="模型名称" prop="modelName" style="flex: 1;"> <el-form-item label="Model Name" prop="modelName" style="flex: 1;">
<el-input v-model="formData.modelName" placeholder="请输入模型名称" class="custom-input-bg"></el-input> <el-input v-model="formData.modelName" placeholder="Please enter model name" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="模型编码" prop="modelCode" style="flex: 1;"> <el-form-item label="Model Code" prop="modelCode" style="flex: 1;">
<el-input v-model="formData.modelCode" placeholder="请输入模型编码" class="custom-input-bg"></el-input> <el-input v-model="formData.modelCode" placeholder="Please enter model code" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
</div> </div>
<div style="display: flex; gap: 20px; margin-bottom: 0;"> <div style="display: flex; gap: 20px; margin-bottom: 0;">
<el-form-item label="供应器" prop="supplier" style="flex: 1;"> <el-form-item label="Provider" prop="supplier" style="flex: 1;">
<el-select v-model="formData.supplier" placeholder="请选择" class="custom-select custom-input-bg" <el-select v-model="formData.supplier" placeholder="Please select" class="custom-select custom-input-bg"
style="width: 100%;" @focus="loadProviders" filterable> style="width: 100%;" @focus="loadProviders" filterable>
<el-option v-for="item in providers" :key="item.value" :label="item.label" :value="item.value" /> <el-option v-for="item in providers" :key="item.value" :label="item.label" :value="item.value" />
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="排序号" prop="sortOrder" style="flex: 1;"> <el-form-item label="Sort Order" prop="sortOrder" style="flex: 1;">
<el-input v-model="formData.sort" type="number" placeholder="请输入排序号" class="custom-input-bg"></el-input> <el-input v-model="formData.sort" type="number" placeholder="Please enter sort order" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
</div> </div>
<el-form-item label="文档地址" prop="docLink" style="margin-bottom: 27px;"> <el-form-item label="Document URL" prop="docLink" style="margin-bottom: 27px;">
<el-input v-model="formData.docLink" placeholder="请输入文档地址" class="custom-input-bg"></el-input> <el-input v-model="formData.docLink" placeholder="Please enter document URL" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="备注" prop="remark" class="prop-remark"> <el-form-item label="Remarks" prop="remark" class="prop-remark">
<el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入模型备注" :autosize="{ minRows: 3, maxRows: 5 }" <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="Please enter model remarks" :autosize="{ minRows: 3, maxRows: 5 }"
class="custom-input-bg"></el-input> class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
<div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;">调用信息</div> <div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;">API Configuration</div>
<div style="height: 2px; background: #e9e9e9; margin-bottom: 22px;"></div> <div style="height: 2px; background: #e9e9e9; margin-bottom: 22px;"></div>
<el-form :model="formData.configJson" label-width="auto" label-position="left" class="custom-form"> <el-form :model="formData.configJson" label-width="auto" label-position="left" class="custom-form">
@ -83,7 +83,7 @@
class="save-btn" class="save-btn"
:loading="saving" :loading="saving"
:disabled="saving"> :disabled="saving">
保存 Save
</el-button> </el-button>
</div> </div>
</el-dialog> </el-dialog>
@ -159,7 +159,7 @@ export default {
label: f.label, label: f.label,
prop: f.key, prop: f.key,
type: f.type === 'password' ? 'password' : 'text', type: f.type === 'password' ? 'password' : 'text',
placeholder: `请输入${f.label}` placeholder: `Please enter ${f.label}`
})) }))
})) }))
this.providersLoaded = true this.providersLoaded = true
@ -195,7 +195,7 @@ export default {
this.saving = true; this.saving = true;
if (!this.formData.supplier) { if (!this.formData.supplier) {
this.$message.error('请选择供应器'); this.$message.error('Please select a provider');
this.saving = false; this.saving = false;
return; return;
} }
@ -239,10 +239,10 @@ export default {
isDefault: true, isDefault: true,
configJson: {} configJson: {}
}; };
// 重置加载状态 // Reset loading state
this.providers = []; this.providers = [];
this.providersLoaded = false; this.providersLoaded = false;
// 重置字段配置 // Reset field configuration
this.providerFields = []; this.providerFields = [];
this.currentProvider = null; this.currentProvider = null;
}, },

View file

@ -6,23 +6,23 @@
style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;"> style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
<img loading="lazy" src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" /> <img loading="lazy" src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" />
</div> </div>
添加智能体 Add Agent
</div> </div>
<div style="height: 1px;background: #e8f0ff;" /> <div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;"> <div style="margin: 22px 15px;">
<div style="font-weight: 400;text-align: left;color: #3d4566;"> <div style="font-weight: 400;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> 智能体名称: <div style="color: red;display: inline-block;">*</div> Agent Name:
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input ref="inputRef" placeholder="请输入智能体名称.." v-model="wisdomBodyName" @keyup.enter.native="confirm" /> <el-input ref="inputRef" placeholder="Please enter agent name.." v-model="wisdomBodyName" @keyup.enter.native="confirm" />
</div> </div>
</div> </div>
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="confirm"> <div class="dialog-btn" @click="confirm">
确定 Confirm
</div> </div>
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel"> <div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel">
取消 Cancel
</div> </div>
</div> </div>
</el-dialog> </el-dialog>
@ -50,12 +50,12 @@ export default {
}, },
confirm() { confirm() {
if (!this.wisdomBodyName.trim()) { if (!this.wisdomBodyName.trim()) {
this.$message.error('请输入智能体名称'); this.$message.error('Please enter agent name');
return; return;
} }
Api.agent.addAgent(this.wisdomBodyName, (res) => { Api.agent.addAgent(this.wisdomBodyName, (res) => {
this.$message.success({ this.$message.success({
message: '添加成功', message: 'Added successfully',
showClose: true showClose: true
}); });
this.$emit('confirm', res); this.$emit('confirm', res);

View file

@ -1,60 +1,60 @@
<template> <template>
<el-dialog <el-dialog
title="CDN资源缓存状态" title="CDN Resource Cache Status"
:visible.sync="visible" :visible.sync="visible"
width="70%" width="70%"
:before-close="handleClose" :before-close="handleClose"
> >
<div v-if="isLoading" class="loading-container"> <div v-if="isLoading" class="loading-container">
<p>正在加载缓存信息...</p> <p>Loading cache information...</p>
</div> </div>
<div v-else> <div v-else>
<div v-if="!cacheAvailable" class="no-cache-message"> <div v-if="!cacheAvailable" class="no-cache-message">
<i class="el-icon-warning-outline"></i> <i class="el-icon-warning-outline"></i>
<p>您的浏览器不支持Cache API或Service Worker未安装</p> <p>Your browser does not support the Cache API or Service Worker is not installed</p>
<el-button type="primary" @click="refreshPage">刷新页面</el-button> <el-button type="primary" @click="refreshPage">Refresh Page</el-button>
</div> </div>
<div v-else> <div v-else>
<el-alert <el-alert
v-if="cacheData.totalCached === 0" v-if="cacheData.totalCached === 0"
title="未发现缓存的CDN资源" title="No Cached CDN Resources Found"
type="warning" type="warning"
:closable="false" :closable="false"
show-icon show-icon
> >
<p>Service Worker可能尚未完成初始化或缓存尚未建立。请刷新页面或等待一会后再试。</p> <p>Service Worker may not have finished initialization or cache has not been established. Please refresh the page or wait a moment and try again.</p>
</el-alert> </el-alert>
<div v-else> <div v-else>
<el-alert <el-alert
title="CDN资源缓存状态" title="CDN Resource Cache Status"
type="success" type="success"
:closable="false" :closable="false"
show-icon show-icon
> >
共发现 {{ cacheData.totalCached }} 个缓存资源 Found {{ cacheData.totalCached }} cached resources in total
</el-alert> </el-alert>
<h3>JavaScript 资源 ({{ cacheData.js.length }})</h3> <h3>JavaScript Resources ({{ cacheData.js.length }})</h3>
<el-table :data="cacheData.js" stripe style="width: 100%"> <el-table :data="cacheData.js" stripe style="width: 100%">
<el-table-column prop="url" label="URL" width="auto" show-overflow-tooltip /> <el-table-column prop="url" label="URL" width="auto" show-overflow-tooltip />
<el-table-column prop="cached" label="状态" width="100"> <el-table-column prop="cached" label="Status" width="100">
<template slot-scope="scope"> <template slot-scope="scope">
<el-tag type="success" v-if="scope.row.cached">已缓存</el-tag> <el-tag type="success" v-if="scope.row.cached">Cached</el-tag>
<el-tag type="danger" v-else>未缓存</el-tag> <el-tag type="danger" v-else>Not Cached</el-tag>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
<h3>CSS 资源 ({{ cacheData.css.length }})</h3> <h3>CSS Resources ({{ cacheData.css.length }})</h3>
<el-table :data="cacheData.css" stripe style="width: 100%"> <el-table :data="cacheData.css" stripe style="width: 100%">
<el-table-column prop="url" label="URL" width="auto" show-overflow-tooltip /> <el-table-column prop="url" label="URL" width="auto" show-overflow-tooltip />
<el-table-column prop="cached" label="状态" width="100"> <el-table-column prop="cached" label="Status" width="100">
<template slot-scope="scope"> <template slot-scope="scope">
<el-tag type="success" v-if="scope.row.cached">已缓存</el-tag> <el-tag type="success" v-if="scope.row.cached">Cached</el-tag>
<el-tag type="danger" v-else>未缓存</el-tag> <el-tag type="danger" v-else>Not Cached</el-tag>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -63,9 +63,9 @@
</div> </div>
<span slot="footer" class="dialog-footer"> <span slot="footer" class="dialog-footer">
<el-button @click="handleClose">关闭</el-button> <el-button @click="handleClose">Close</el-button>
<el-button type="primary" @click="refreshCache">刷新缓存状态</el-button> <el-button type="primary" @click="refreshCache">Refresh Cache Status</el-button>
<el-button type="danger" @click="clearCache">清除缓存</el-button> <el-button type="danger" @click="clearCache">Clear Cache</el-button>
</span> </span>
</el-dialog> </el-dialog>
</template> </template>
@ -129,8 +129,8 @@ export default {
await logCacheStatus(); await logCacheStatus();
} }
} catch (error) { } catch (error) {
console.error('加载缓存数据失败:', error); console.error('Failed to load cache data:', error);
this.$message.error('加载缓存数据失败'); this.$message.error('Failed to load cache data');
} finally { } finally {
this.isLoading = false; this.isLoading = false;
} }
@ -138,29 +138,29 @@ export default {
async refreshCache() { async refreshCache() {
this.loadCacheData(); this.loadCacheData();
this.$message.success('正在刷新缓存状态'); this.$message.success('Refreshing cache status');
}, },
async clearCache() { async clearCache() {
this.$confirm('确定要清除所有缓存吗?', '警告', { this.$confirm('Are you sure you want to clear all cache?', 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(async () => { }).then(async () => {
try { try {
const success = await clearAllCaches(); const success = await clearAllCaches();
if (success) { if (success) {
this.$message.success('缓存已清除'); this.$message.success('Cache cleared');
await this.loadCacheData(); await this.loadCacheData();
} else { } else {
this.$message.error('清除缓存失败'); this.$message.error('Failed to clear cache');
} }
} catch (error) { } catch (error) {
console.error('清除缓存失败:', error); console.error('Failed to clear cache:', error);
this.$message.error('清除缓存失败'); this.$message.error('Failed to clear cache');
} }
}).catch(() => { }).catch(() => {
this.$message.info('已取消清除'); this.$message.info('Clear operation cancelled');
}); });
}, },

View file

@ -8,38 +8,38 @@
<img loading="lazy" src="@/assets/login/shield.png" alt="" <img loading="lazy" src="@/assets/login/shield.png" alt=""
style="width: 19px;height: 23px; filter: brightness(0) invert(1);" /> style="width: 19px;height: 23px; filter: brightness(0) invert(1);" />
</div> </div>
修改密码 Change Password
</div> </div>
<div style="height: 1px;background: #e8f0ff;" /> <div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;"> <div style="margin: 22px 15px;">
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> <div style="color: red;display: inline-block;">*</div>
旧密码: Old Password:
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input placeholder="请输入旧密码" v-model="oldPassword" type="password" show-password /> <el-input placeholder="Please enter old password" v-model="oldPassword" type="password" show-password />
</div> </div>
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;margin-top: 12px;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;margin-top: 12px;">
<div style="color: red;display: inline-block;">*</div> <div style="color: red;display: inline-block;">*</div>
新密码: New Password:
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input placeholder="请输入新密码" v-model="newPassword" type="password" show-password /> <el-input placeholder="Please enter new password" v-model="newPassword" type="password" show-password />
</div> </div>
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;margin-top: 12px;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;margin-top: 12px;">
<div style="color: red;display: inline-block;">*</div> <div style="color: red;display: inline-block;">*</div>
确认新密码: Confirm New Password:
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input placeholder="请再次输入新密码" v-model="confirmNewPassword" type="password" show-password /> <el-input placeholder="Please enter new password again" v-model="confirmNewPassword" type="password" show-password />
</div> </div>
</div> </div>
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="confirm"> <div class="dialog-btn" @click="confirm">
确定 Confirm
</div> </div>
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel"> <div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel">
取消 Cancel
</div> </div>
</div> </div>
</el-dialog> </el-dialog>
@ -75,26 +75,26 @@ export default {
} }
}, },
methods: { methods: {
...mapActions(['logout']), // 引入Vuex的logout action ...mapActions(['logout']), // Import Vuex logout action
confirm() { confirm() {
if (!this.oldPassword.trim() || !this.newPassword.trim() || !this.confirmNewPassword.trim()) { if (!this.oldPassword.trim() || !this.newPassword.trim() || !this.confirmNewPassword.trim()) {
this.$message.error('请填写所有字段'); this.$message.error('Please fill in all fields');
return; return;
} }
if (this.newPassword !== this.confirmNewPassword) { if (this.newPassword !== this.confirmNewPassword) {
this.$message.error('两次输入的新密码不一致'); this.$message.error('The new passwords entered do not match');
return; return;
} }
if (this.newPassword === this.oldPassword) { if (this.newPassword === this.oldPassword) {
this.$message.error('新密码不能与旧密码相同'); this.$message.error('New password cannot be the same as old password');
return; return;
} }
// 修改后的接口调用 // Modified API call
userApi.changePassword(this.oldPassword, this.newPassword, (res) => { userApi.changePassword(this.oldPassword, this.newPassword, (res) => {
if (res.data.code === 0) { if (res.data.code === 0) {
this.$message.success({ this.$message.success({
message: '密码修改成功,请重新登录', message: 'Password changed successfully, please login again',
showClose: true showClose: true
}); });
this.logout().then(() => { this.logout().then(() => {
@ -102,10 +102,10 @@ export default {
this.$emit('update:visible', false); this.$emit('update:visible', false);
}); });
} else { } else {
this.$message.error(res.data.msg || '密码修改失败'); this.$message.error(res.data.msg || 'Password change failed');
} }
}, (err) => { }, (err) => {
this.$message.error(err.msg || '密码修改失败'); this.$message.error(err.msg || 'Password change failed');
}); });
this.$emit('input', false); this.$emit('input', false);
}, },

View file

@ -1,5 +1,5 @@
<template> <template>
<el-dialog :title="'与' + agentName + '的聊天记录' + (currentMacAddress ? '[' + currentMacAddress + ']' : '')" <el-dialog :title="'Chat History with ' + agentName + (currentMacAddress ? ' [' + currentMacAddress + ']' : '')"
:visible.sync="dialogVisible" width="80%" :before-close="handleClose" custom-class="chat-history-dialog"> :visible.sync="dialogVisible" width="80%" :before-close="handleClose" custom-class="chat-history-dialog">
<div class="chat-container"> <div class="chat-container">
<div class="session-list" @scroll="handleScroll"> <div class="session-list" @scroll="handleScroll">
@ -11,8 +11,8 @@
<div class="message-count">{{ session.chatCount > 99 ? '99' : session.chatCount }}</div> <div class="message-count">{{ session.chatCount > 99 ? '99' : session.chatCount }}</div>
</div> </div>
</div> </div>
<div v-if="loading" class="loading">加载中...</div> <div v-if="loading" class="loading">Loading...</div>
<div v-if="!hasMore" class="no-more">没有更多记录了</div> <div v-if="!hasMore" class="no-more">No more records</div>
</div> </div>
<div class="chat-content"> <div class="chat-content">
<div v-if="currentSessionId" class="messages"> <div v-if="currentSessionId" class="messages">
@ -32,7 +32,7 @@
</div> </div>
</div> </div>
<div v-else class="no-session-selected"> <div v-else class="no-session-selected">
请选择会话查看聊天记录 Please select a session to view chat history
</div> </div>
</div> </div>
</div> </div>
@ -94,9 +94,9 @@ export default {
if (!this.messages || this.messages.length === 0) return []; if (!this.messages || this.messages.length === 0) return [];
const result = []; const result = [];
const TIME_INTERVAL = 60 * 1000; // 1分钟的时间间隔(毫秒) const TIME_INTERVAL = 60 * 1000; // 1 minute time interval (milliseconds)
// 添加第一条消息的时间标记 // Add time marker for the first message
if (this.messages[0]) { if (this.messages[0]) {
result.push({ result.push({
type: 'time', type: 'time',
@ -105,12 +105,12 @@ export default {
}); });
} }
// 处理消息列表 // Process message list
for (let i = 0; i < this.messages.length; i++) { for (let i = 0; i < this.messages.length; i++) {
const currentMessage = this.messages[i]; const currentMessage = this.messages[i];
result.push(currentMessage); result.push(currentMessage);
// 检查是否需要添加时间标记 // Check if time marker needs to be added
if (i < this.messages.length - 1) { if (i < this.messages.length - 1) {
const currentTime = new Date(currentMessage.createdAt).getTime(); const currentTime = new Date(currentMessage.createdAt).getTime();
const nextTime = new Date(this.messages[i + 1].createdAt).getTime(); const nextTime = new Date(this.messages[i + 1].createdAt).getTime();
@ -187,7 +187,7 @@ export default {
this.scrollTimer = setTimeout(() => { this.scrollTimer = setTimeout(() => {
const { scrollTop, scrollHeight, clientHeight } = e.target; const { scrollTop, scrollHeight, clientHeight } = e.target;
// 当滚动到底部时加载更多 // Load more when scrolled to bottom
if (scrollHeight - scrollTop <= clientHeight + 50) { if (scrollHeight - scrollTop <= clientHeight + 50) {
this.loadSessions(); this.loadSessions();
} }
@ -204,9 +204,9 @@ export default {
const minutes = date.getMinutes().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0');
if (date >= today) { if (date >= today) {
return `今天 ${hours}:${minutes}`; return `Today ${hours}:${minutes}`;
} else if (date >= yesterday) { } else if (date >= yesterday) {
return `昨天 ${hours}:${minutes}`; return `Yesterday ${hours}:${minutes}`;
} else { } else {
const year = date.getFullYear(); const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); const month = (date.getMonth() + 1).toString().padStart(2, '0');
@ -222,7 +222,7 @@ export default {
}, },
playAudio(message) { playAudio(message) {
if (this.playingAudioId === message.audioId) { if (this.playingAudioId === message.audioId) {
// 如果正在播放当前音频,则停止播放 // If currently playing this audio, stop it
if (this.audioElement) { if (this.audioElement) {
this.audioElement.pause(); this.audioElement.pause();
this.audioElement = null; this.audioElement = null;
@ -231,17 +231,17 @@ export default {
return; return;
} }
// 停止当前正在播放的音频 // Stop currently playing audio
if (this.audioElement) { if (this.audioElement) {
this.audioElement.pause(); this.audioElement.pause();
this.audioElement = null; this.audioElement = null;
} }
// 先获取音频下载ID // First get audio download ID
this.playingAudioId = message.audioId; this.playingAudioId = message.audioId;
Api.agent.getAudioId(message.audioId, (res) => { Api.agent.getAudioId(message.audioId, (res) => {
if (res.data && res.data.data) { if (res.data && res.data.data) {
// 使用获取到的下载ID播放音频 // Use the obtained download ID to play audio
this.audioElement = new Audio(Api.getServiceUrl() + `/agent/play/${res.data.data}`); this.audioElement = new Audio(Api.getServiceUrl() + `/agent/play/${res.data.data}`);
this.audioElement.onended = () => { this.audioElement.onended = () => {
@ -254,17 +254,17 @@ export default {
}); });
}, },
getUserAvatar(sessionId) { getUserAvatar(sessionId) {
// 从 sessionId 中提取所有数字 // Extract all digits from sessionId
const numbers = sessionId.match(/\d+/g); const numbers = sessionId.match(/\d+/g);
if (!numbers) return require('@/assets/user-avatar1.png'); if (!numbers) return require('@/assets/user-avatar1.png');
// 将所有数字相加 // Sum all digits
const sum = numbers.reduce((acc, num) => acc + parseInt(num), 0); const sum = numbers.reduce((acc, num) => acc + parseInt(num), 0);
// 计算模5并加1,得到1-5之间的数字 // Calculate modulo 5 and add 1 to get a number between 1-5
const avatarIndex = (sum % 5) + 1; const avatarIndex = (sum % 5) + 1;
// 返回对应的头像图片 // Return corresponding avatar image
return require(`@/assets/user-avatar${avatarIndex}.png`); return require(`@/assets/user-avatar${avatarIndex}.png`);
} }
} }
@ -319,7 +319,7 @@ export default {
height: 30px; height: 30px;
line-height: 30px; line-height: 30px;
width: calc(100% - 30px); width: calc(100% - 30px);
/* 为消息数量留出空间 */ /* Leave space for message count */
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
@ -442,6 +442,6 @@ export default {
padding: 0; padding: 0;
overflow: hidden; overflow: hidden;
height: calc(90vh - 54px); height: calc(90vh - 54px);
/* 减去标题栏的高度 */ /* Subtract title bar height */
} }
</style> </style>

View file

@ -14,28 +14,28 @@
</div> </div>
</div> </div>
<div class="device-name"> <div class="device-name">
语言模型:{{ device.llmModelName }} Language Model: {{ device.llmModelName }}
</div> </div>
<div class="device-name"> <div class="device-name">
音色模型:{{ device.ttsModelName }} ({{ device.ttsVoiceName }}) Voice Model: {{ device.ttsModelName }} ({{ device.ttsVoiceName }})
</div> </div>
<div style="display: flex;gap: 10px;align-items: center;"> <div style="display: flex;gap: 10px;align-items: center;">
<div class="settings-btn" @click="handleConfigure"> <div class="settings-btn" @click="handleConfigure">
配置角色 Configure Role
</div> </div>
<div class="settings-btn" @click="handleDeviceManage"> <div class="settings-btn" @click="handleDeviceManage">
设备管理({{ device.deviceCount }}) Device Management ({{ device.deviceCount }})
</div> </div>
<div class="settings-btn" @click="handleChatHistory" <div class="settings-btn" @click="handleChatHistory"
:class="{ 'disabled-btn': device.memModelId === 'Memory_nomem' }"> :class="{ 'disabled-btn': device.memModelId === 'Memory_nomem' }">
<el-tooltip v-if="device.memModelId === 'Memory_nomem'" content="请先在“配置角色”界面开启记忆" placement="top"> <el-tooltip v-if="device.memModelId === 'Memory_nomem'" content="Please enable memory in the 'Configure Role' interface first" placement="top">
<span>聊天记录</span> <span>Chat History</span>
</el-tooltip> </el-tooltip>
<span v-else>聊天记录</span> <span v-else>Chat History</span>
</div> </div>
</div> </div>
<div class="version-info"> <div class="version-info">
<div>最近对话:{{ formattedLastConnectedTime }}</div> <div>Last Conversation: {{ formattedLastConnectedTime }}</div>
</div> </div>
</div> </div>
</template> </template>
@ -51,20 +51,20 @@ export default {
}, },
computed: { computed: {
formattedLastConnectedTime() { formattedLastConnectedTime() {
if (!this.device.lastConnectedAt) return '暂未对话'; if (!this.device.lastConnectedAt) return 'No conversation yet';
const lastTime = new Date(this.device.lastConnectedAt); const lastTime = new Date(this.device.lastConnectedAt);
const now = new Date(); const now = new Date();
const diffMinutes = Math.floor((now - lastTime) / (1000 * 60)); const diffMinutes = Math.floor((now - lastTime) / (1000 * 60));
if (diffMinutes <= 1) { if (diffMinutes <= 1) {
return '刚刚'; return 'Just now';
} else if (diffMinutes < 60) { } else if (diffMinutes < 60) {
return `${diffMinutes}分钟前`; return `${diffMinutes} minutes ago`;
} else if (diffMinutes < 24 * 60) { } else if (diffMinutes < 24 * 60) {
const hours = Math.floor(diffMinutes / 60); const hours = Math.floor(diffMinutes / 60);
const minutes = diffMinutes % 60; const minutes = diffMinutes % 60;
return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}前`; return `${hours} hours${minutes > 0 ? ' ' + minutes + ' minutes' : ''} ago`;
} else { } else {
return this.device.lastConnectedAt; return this.device.lastConnectedAt;
} }

View file

@ -1,19 +1,19 @@
<template> <template>
<el-dialog :title="title" :visible.sync="dialogVisible" width="30%" @close="handleClose"> <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" @close="handleClose">
<el-form :model="form" :rules="rules" ref="form" label-width="100px"> <el-form :model="form" :rules="rules" ref="form" label-width="100px">
<el-form-item label="字典标签" prop="dictLabel"> <el-form-item label="Dictionary Label" prop="dictLabel">
<el-input v-model="form.dictLabel" placeholder="请输入字典标签"></el-input> <el-input v-model="form.dictLabel" placeholder="Please enter dictionary label"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="字典值" prop="dictValue"> <el-form-item label="Dictionary Value" prop="dictValue">
<el-input v-model="form.dictValue" placeholder="请输入字典值"></el-input> <el-input v-model="form.dictValue" placeholder="Please enter dictionary value"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="排序" prop="sort"> <el-form-item label="Sort" prop="sort">
<el-input-number v-model="form.sort" :min="0" :max="999" style="width: 100%;"></el-input-number> <el-input-number v-model="form.sort" :min="0" :max="999" style="width: 100%;"></el-input-number>
</el-form-item> </el-form-item>
</el-form> </el-form>
<div slot="footer" class="dialog-footer"> <div slot="footer" class="dialog-footer">
<el-button @click="handleClose">取 消</el-button> <el-button @click="handleClose">Cancel</el-button>
<el-button type="primary" @click="handleSave">确 定</el-button> <el-button type="primary" @click="handleSave">Confirm</el-button>
</div> </div>
</el-dialog> </el-dialog>
</template> </template>
@ -28,7 +28,7 @@ export default {
}, },
title: { title: {
type: String, type: String,
default: '新增字典数据' default: 'Add Dictionary Data'
}, },
dictData: { dictData: {
type: Object, type: Object,
@ -50,8 +50,8 @@ export default {
sort: 0 sort: 0
}, },
rules: { rules: {
dictLabel: [{ required: true, message: '请输入字典标签', trigger: 'blur' }], dictLabel: [{ required: true, message: 'Please enter dictionary label', trigger: 'blur' }],
dictValue: [{ required: true, message: '请输入字典值', trigger: 'blur' }] dictValue: [{ required: true, message: 'Please enter dictionary value', trigger: 'blur' }]
} }
} }
}, },

View file

@ -1,16 +1,16 @@
<template> <template>
<el-dialog :title="title" :visible.sync="dialogVisible" width="30%" @close="handleClose"> <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" @close="handleClose">
<el-form :model="form" :rules="rules" ref="form" label-width="120px"> <el-form :model="form" :rules="rules" ref="form" label-width="120px">
<el-form-item label="字典类型名称" prop="dictName"> <el-form-item label="Dictionary Type Name" prop="dictName">
<el-input v-model="form.dictName" placeholder="请输入字典类型名称"></el-input> <el-input v-model="form.dictName" placeholder="Please enter dictionary type name"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="字典类型编码" prop="dictType"> <el-form-item label="Dictionary Type Code" prop="dictType">
<el-input v-model="form.dictType" placeholder="请输入字典类型编码"></el-input> <el-input v-model="form.dictType" placeholder="Please enter dictionary type code"></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
<div slot="footer" class="dialog-footer"> <div slot="footer" class="dialog-footer">
<el-button @click="handleClose">取 消</el-button> <el-button @click="handleClose">Cancel</el-button>
<el-button type="primary" @click="handleSave">确 定</el-button> <el-button type="primary" @click="handleSave">Confirm</el-button>
</div> </div>
</el-dialog> </el-dialog>
</template> </template>
@ -25,7 +25,7 @@ export default {
}, },
title: { title: {
type: String, type: String,
default: '新增字典类型' default: 'Add Dictionary Type'
}, },
dictTypeData: { dictTypeData: {
type: Object, type: Object,
@ -41,8 +41,8 @@ export default {
dictType: '' dictType: ''
}, },
rules: { rules: {
dictName: [{ required: true, message: '请输入字典类型名称', trigger: 'blur' }], dictName: [{ required: true, message: 'Please enter dictionary type name', trigger: 'blur' }],
dictType: [{ required: true, message: '请输入字典类型编码', trigger: 'blur' }] dictType: [{ required: true, message: 'Please enter dictionary type code', trigger: 'blur' }]
} }
} }
}, },

View file

@ -3,31 +3,31 @@
<el-form :model="voiceForm" :rules="rules" ref="voiceForm" label-width="80px"> <el-form :model="voiceForm" :rules="rules" ref="voiceForm" label-width="80px">
<el-row :gutter="20"> <el-row :gutter="20">
<el-col :span="12"> <el-col :span="12">
<el-form-item label="音色编码" prop="voiceCode"> <el-form-item label="Voice Code" prop="voiceCode">
<el-input v-model="voiceForm.voiceCode" placeholder="请输入内容" class="compact-input"></el-input> <el-input v-model="voiceForm.voiceCode" placeholder="Please enter content" class="compact-input"></el-input>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-form-item label="音色名称" prop="voiceName"> <el-form-item label="Voice Name" prop="voiceName">
<el-input v-model="voiceForm.voiceName" placeholder="请输入内容" class="compact-input"></el-input> <el-input v-model="voiceForm.voiceName" placeholder="Please enter content" class="compact-input"></el-input>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
<el-row :gutter="20"> <el-row :gutter="20">
<el-col :span="12"> <el-col :span="12">
<el-form-item label="语言类型" prop="languageType"> <el-form-item label="Language Type" prop="languageType">
<el-input v-model="voiceForm.languageType" placeholder="请输入内容" class="compact-input"></el-input> <el-input v-model="voiceForm.languageType" placeholder="Please enter content" class="compact-input"></el-input>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-form-item label="排序号" prop="sortNumber"> <el-form-item label="Sort Number" prop="sortNumber">
<el-input-number v-model="voiceForm.sortNumber" :min="1" :controls="false" class="compact-number"></el-input-number> <el-input-number v-model="voiceForm.sortNumber" :min="1" :controls="false" class="compact-number"></el-input-number>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
<el-form-item label="备注" prop="remark"> <el-form-item label="Remarks" prop="remark">
<el-input v-model="voiceForm.remark" type="textarea" :rows="2" placeholder="请输入内容" class="compact-textarea" <el-input v-model="voiceForm.remark" type="textarea" :rows="2" placeholder="Please enter content" class="compact-textarea"
></el-input> ></el-input>
<div class="audio-controls"> <div class="audio-controls">
<div class="audio-player"> <div class="audio-player">
@ -38,14 +38,14 @@
class="custom-audio" class="custom-audio"
></audio> ></audio>
</div> </div>
<el-button type="primary" size="mini" class="preview-btn">生成试听</el-button> <el-button type="primary" size="mini" class="preview-btn">Generate Preview</el-button>
</div> </div>
</el-form-item> </el-form-item>
</el-form> </el-form>
<div slot="footer" class="dialog-footer"> <div slot="footer" class="dialog-footer">
<el-button type="primary" @click="handleSave">保存</el-button> <el-button type="primary" @click="handleSave">Save</el-button>
<el-button type="primary" @click="handleClose">关闭</el-button> <el-button type="primary" @click="handleClose">Close</el-button>
</div> </div>
</el-dialog> </el-dialog>
</template> </template>
@ -59,8 +59,8 @@ export default {
type: Object, type: Object,
default: () => ({ default: () => ({
voiceCode: 'wawaxiaohe', voiceCode: 'wawaxiaohe',
voiceName: '湾湾小何', voiceName: 'Wawa Xiaohe',
languageType: '中文', languageType: 'Chinese',
sortNumber: 123 sortNumber: 123
}) })
} }
@ -72,8 +72,8 @@ export default {
audioUrl: 'http://music.163.com/song/media/outer/url?id=447925558.mp3', audioUrl: 'http://music.163.com/song/media/outer/url?id=447925558.mp3',
generatedAudio: null, generatedAudio: null,
rules: { rules: {
voiceCode: [{ required: true, message: '请输入音色编码', trigger: 'blur' }], voiceCode: [{ required: true, message: 'Please enter voice code', trigger: 'blur' }],
voiceName: [{ required: true, message: '请输入音色名称', trigger: 'blur' }] voiceName: [{ required: true, message: 'Please enter voice name', trigger: 'blur' }]
} }
} }
}, },

View file

@ -1,37 +1,37 @@
<template> <template>
<el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" @close="handleClose" @open="handleOpen"> <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" @close="handleClose" @open="handleOpen">
<el-form ref="form" :model="form" :rules="rules" label-width="100px"> <el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="固件名称" prop="firmwareName"> <el-form-item label="Firmware Name" prop="firmwareName">
<el-input v-model="form.firmwareName" placeholder="请输入固件名称(板子+版本号)"></el-input> <el-input v-model="form.firmwareName" placeholder="Please enter firmware name (board + version)"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="固件类型" prop="type"> <el-form-item label="Firmware Type" prop="type">
<el-select v-model="form.type" placeholder="请选择固件类型" style="width: 100%;" filterable :disabled="isTypeDisabled"> <el-select v-model="form.type" placeholder="Please select firmware type" style="width: 100%;" filterable :disabled="isTypeDisabled">
<el-option v-for="item in firmwareTypes" :key="item.key" :label="item.name" :value="item.key"></el-option> <el-option v-for="item in firmwareTypes" :key="item.key" :label="item.name" :value="item.key"></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="版本号" prop="version"> <el-form-item label="Version" prop="version">
<el-input v-model="form.version" placeholder="请输入版本号(x.x.x格式)"></el-input> <el-input v-model="form.version" placeholder="Please enter version (x.x.x format)"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="固件文件" prop="firmwarePath"> <el-form-item label="Firmware File" prop="firmwarePath">
<el-upload ref="upload" class="upload-demo" action="#" :http-request="handleUpload" <el-upload ref="upload" class="upload-demo" action="#" :http-request="handleUpload"
:before-upload="beforeUpload" :accept="'.bin,.apk'" :limit="1" :multiple="false" :auto-upload="true" :before-upload="beforeUpload" :accept="'.bin,.apk'" :limit="1" :multiple="false" :auto-upload="true"
:on-remove="handleRemove"> :on-remove="handleRemove">
<el-button size="small" type="primary">点击上传</el-button> <el-button size="small" type="primary">Click to Upload</el-button>
<div slot="tip" class="el-upload__tip">只能上传固件文件(.bin/.apk),且不超过100MB</div> <div slot="tip" class="el-upload__tip">Only firmware files (.bin/.apk) can be uploaded, and must not exceed 100MB</div>
</el-upload> </el-upload>
<el-progress v-if="isUploading || uploadStatus === 'success'" :percentage="uploadProgress" <el-progress v-if="isUploading || uploadStatus === 'success'" :percentage="uploadProgress"
:status="uploadStatus"></el-progress> :status="uploadStatus"></el-progress>
<div class="hint-text"> <div class="hint-text">
<span>温馨提示:请上传合并前的xiaozhi.bin文件,而不是合并后的merged-binary.bin文件</span> <span>Warm Reminder: Please upload the pre-merge xiaozhi.bin file, not the post-merge merged-binary.bin file</span>
</div> </div>
</el-form-item> </el-form-item>
<el-form-item label="备注" prop="remark"> <el-form-item label="Remarks" prop="remark">
<el-input type="textarea" v-model="form.remark" placeholder="请输入备注信息"></el-input> <el-input type="textarea" v-model="form.remark" placeholder="Please enter remarks information"></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
<div slot="footer" class="dialog-footer"> <div slot="footer" class="dialog-footer">
<el-button @click="handleCancel">取 消</el-button> <el-button @click="handleCancel">Cancel</el-button>
<el-button type="primary" @click="handleSubmit">确 定</el-button> <el-button type="primary" @click="handleSubmit">Confirm</el-button>
</div> </div>
</el-dialog> </el-dialog>
</template> </template>
@ -68,29 +68,29 @@ export default {
dialogVisible: this.visible, dialogVisible: this.visible,
rules: { rules: {
firmwareName: [ firmwareName: [
{ required: true, message: '请输入固件名称(板子+版本号)', trigger: 'blur' } { required: true, message: 'Please enter firmware name (board + version)', trigger: 'blur' }
], ],
type: [ type: [
{ required: true, message: '请选择固件类型', trigger: 'change' } { required: true, message: 'Please select firmware type', trigger: 'change' }
], ],
version: [ version: [
{ required: true, message: '请输入版本号', trigger: 'blur' }, { required: true, message: 'Please enter version', trigger: 'blur' },
{ pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式不正确,请输入x.x.x格式', trigger: 'blur' } { pattern: /^\d+\.\d+\.\d+$/, message: 'Incorrect version format, please enter x.x.x format', trigger: 'blur' }
], ],
firmwarePath: [ firmwarePath: [
{ required: false, message: '请上传固件文件', trigger: 'change' } { required: false, message: 'Please upload firmware file', trigger: 'change' }
] ]
} }
} }
}, },
computed: { computed: {
isTypeDisabled() { isTypeDisabled() {
// 如果有id,说明是编辑模式,禁用类型选择 // If there is an id, it means edit mode, disable type selection
return !!this.form.id return !!this.form.id
} }
}, },
created() { created() {
// 移除 getDictDataByType 调用 // Remove getDictDataByType call
}, },
watch: { watch: {
visible(val) { visible(val) {
@ -101,7 +101,7 @@ export default {
}, },
}, },
methods: { methods: {
// 移除 getFirmwareTypes 方法 // Remove getFirmwareTypes method
handleClose() { handleClose() {
this.dialogVisible = false; this.dialogVisible = false;
this.$emit('cancel'); this.$emit('cancel');
@ -113,12 +113,12 @@ export default {
handleSubmit() { handleSubmit() {
this.$refs.form.validate(valid => { this.$refs.form.validate(valid => {
if (valid) { if (valid) {
// 如果是新增模式且没有上传文件,则提示错误 // If it's add mode and no file uploaded, show error
if (!this.form.id && !this.form.firmwarePath) { if (!this.form.id && !this.form.firmwarePath) {
this.$message.error('请上传固件文件') this.$message.error('Please upload firmware file')
return return
} }
// 提交成功后将关闭对话框的逻辑交给父组件处理 // Leave closing dialog logic to parent component after successful submission
this.$emit('submit', this.form) this.$emit('submit', this.form)
} }
}) })
@ -128,11 +128,11 @@ export default {
const isValidType = ['.bin', '.apk'].some(ext => file.name.toLowerCase().endsWith(ext)) const isValidType = ['.bin', '.apk'].some(ext => file.name.toLowerCase().endsWith(ext))
if (!isValidType) { if (!isValidType) {
this.$message.error('只能上传.bin/.apk格式的固件文件!') this.$message.error('Only .bin/.apk format firmware files can be uploaded!')
return false return false
} }
if (!isValidSize) { if (!isValidSize) {
this.$message.error('固件文件大小不能超过100MB!') this.$message.error('Firmware file size cannot exceed 100MB!')
return false return false
} }
return true return true
@ -143,39 +143,39 @@ export default {
this.uploadStatus = '' this.uploadStatus = ''
this.isUploading = true this.isUploading = true
// 使用setTimeout实现简单的0-50%过渡 // Use setTimeout to implement simple 0-50% transition
const timer = setTimeout(() => { const timer = setTimeout(() => {
if (this.uploadProgress < 50) { // 只有当进度小于50%时才设置 if (this.uploadProgress < 50) { // Only set when progress is less than 50%
this.uploadProgress = 50 this.uploadProgress = 50
} }
}, 1000) }, 1000)
Api.ota.uploadFirmware(file, (res) => { Api.ota.uploadFirmware(file, (res) => {
clearTimeout(timer) // 清除定时器 clearTimeout(timer) // Clear timer
res = res.data res = res.data
if (res.code === 0) { if (res.code === 0) {
this.form.firmwarePath = res.data this.form.firmwarePath = res.data
this.form.size = file.size this.form.size = file.size
this.uploadProgress = 100 this.uploadProgress = 100
this.uploadStatus = 'success' this.uploadStatus = 'success'
this.$message.success('固件文件上传成功') this.$message.success('Firmware file uploaded successfully')
// 延迟2秒后隐藏进度条 // Hide progress bar after 2 seconds delay
setTimeout(() => { setTimeout(() => {
this.isUploading = false this.isUploading = false
}, 2000) }, 2000)
} else { } else {
this.uploadStatus = 'exception' this.uploadStatus = 'exception'
this.$message.error(res.msg || '文件上传失败') this.$message.error(res.msg || 'File upload failed')
this.isUploading = false this.isUploading = false
} }
}, (progressEvent) => { }, (progressEvent) => {
if (progressEvent.total) { if (progressEvent.total) {
const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total) const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
// 只有当进度大于50%时才更新 // Only update when progress is greater than 50%
if (progress > 50) { if (progress > 50) {
this.uploadProgress = progress this.uploadProgress = progress
} }
// 如果上传完成但还没收到成功响应,保持进度条显示 // If upload is complete but no success response yet, keep progress bar visible
if (progress === 100) { if (progress === 100) {
this.uploadStatus = '' this.uploadStatus = ''
} }
@ -190,16 +190,16 @@ export default {
this.isUploading = false this.isUploading = false
}, },
handleOpen() { handleOpen() {
// 重置上传相关状态 // Reset upload related states
this.uploadProgress = 0 this.uploadProgress = 0
this.uploadStatus = '' this.uploadStatus = ''
this.isUploading = false this.isUploading = false
// 重置表单中的文件相关字段 // Reset file related fields in form
if (!this.form.id) { // 只在新增时重置 if (!this.form.id) { // Only reset when adding new
this.form.firmwarePath = '' this.form.firmwarePath = ''
this.form.size = 0 this.form.size = 0
} }
// 无论是否编辑模式,都重置上传组件 // Reset upload component regardless of edit mode
this.$nextTick(() => { this.$nextTick(() => {
if (this.$refs.upload) { if (this.$refs.upload) {
this.$refs.upload.clearFiles() this.$refs.upload.clearFiles()

View file

@ -3,7 +3,7 @@
<!-- 自定义标题区域 --> <!-- 自定义标题区域 -->
<div class="custom-header"> <div class="custom-header">
<div class="header-left"> <div class="header-left">
<h3 class="bold-title">功能管理</h3> <h3 class="bold-title">Function Management</h3>
</div> </div>
<button class="custom-close-btn" @click="closeDialog">×</button> <button class="custom-close-btn" @click="closeDialog">×</button>
</div> </div>
@ -12,8 +12,8 @@
<!-- 左侧:未选功能 --> <!-- 左侧:未选功能 -->
<div class="function-column"> <div class="function-column">
<div class="column-header"> <div class="column-header">
<h4 class="column-title">未选功能</h4> <h4 class="column-title">Unselected Functions</h4>
<el-button type="text" @click="selectAll" class="select-all-btn">全选</el-button> <el-button type="text" @click="selectAll" class="select-all-btn">Select All</el-button>
</div> </div>
<div class="function-list"> <div class="function-list">
<div v-if="unselected.length"> <div v-if="unselected.length">
@ -27,7 +27,7 @@
</div> </div>
</div> </div>
<div v-else style="display: flex; justify-content: center; align-items: center;"> <div v-else style="display: flex; justify-content: center; align-items: center;">
<el-empty description="没有更多的插件了" /> <el-empty description="No more plugins available" />
</div> </div>
</div> </div>
</div> </div>
@ -35,8 +35,8 @@
<!-- 中间:已选功能 --> <!-- 中间:已选功能 -->
<div class="function-column"> <div class="function-column">
<div class="column-header"> <div class="column-header">
<h4 class="column-title">已选功能</h4> <h4 class="column-title">Selected Functions</h4>
<el-button type="text" @click="deselectAll" class="select-all-btn">全选</el-button> <el-button type="text" @click="deselectAll" class="select-all-btn">Select All</el-button>
</div> </div>
<div class="function-list"> <div class="function-list">
<div v-if="selectedList.length > 0"> <div v-if="selectedList.length > 0">
@ -50,19 +50,19 @@
</div> </div>
</div> </div>
<div v-else style="display: flex; justify-content: center; align-items: center;"> <div v-else style="display: flex; justify-content: center; align-items: center;">
<el-empty description="请选择插件功能" /> <el-empty description="Please select plugin functions" />
</div> </div>
</div> </div>
</div> </div>
<!-- 右侧:参数配置 --> <!-- 右侧:参数配置 -->
<div class="params-column"> <div class="params-column">
<h4 v-if="currentFunction" class="column-title">参数配置 - {{ currentFunction.name }}</h4> <h4 v-if="currentFunction" class="column-title">Parameter Configuration - {{ currentFunction.name }}</h4>
<div v-if="currentFunction" class="params-container"> <div v-if="currentFunction" class="params-container">
<el-form :model="currentFunction" class="param-form"> <el-form :model="currentFunction" class="param-form">
<!-- 遍历 fieldsMeta,而不是 params 的 keys --> <!-- 遍历 fieldsMeta,而不是 params 的 keys -->
<div v-if="currentFunction.fieldsMeta.length == 0"> <div v-if="currentFunction.fieldsMeta.length == 0">
<el-empty :description="currentFunction.name + ' 无需配置参数'" /> <el-empty :description="currentFunction.name + ' requires no parameter configuration'" />
</div> </div>
<el-form-item v-for="field in currentFunction.fieldsMeta" :key="field.key" :label="field.label" <el-form-item v-for="field in currentFunction.fieldsMeta" :key="field.key" :label="field.label"
class="param-item" :class="{ 'textarea-field': field.type === 'array' || field.type === 'json' }"> class="param-item" :class="{ 'textarea-field': field.type === 'array' || field.type === 'json' }">
@ -77,7 +77,7 @@
@change="val => handleParamChange(currentFunction, field.key, val)" /> @change="val => handleParamChange(currentFunction, field.key, val)" />
<!-- JSON --> <!-- JSON -->
<el-input v-else-if="field.type === 'json'" type="textarea" :rows="6" placeholder="请输入合法的 JSON" <el-input v-else-if="field.type === 'json'" type="textarea" :rows="6" placeholder="Please enter valid JSON"
v-model="textCache[field.key]" @blur="flushJson(field)" /> v-model="textCache[field.key]" @blur="flushJson(field)" />
<!-- number --> <!-- number -->
@ -95,7 +95,7 @@
</el-form-item> </el-form-item>
</el-form> </el-form>
</div> </div>
<div v-else class="empty-tip">请选择已配置的功能进行参数设置</div> <div v-else class="empty-tip">Please select a configured function for parameter settings</div>
</div> </div>
</div> </div>
@ -105,19 +105,19 @@
<!-- 左侧区域 --> <!-- 左侧区域 -->
<div class="mcp-left"> <div class="mcp-left">
<div class="mcp-header"> <div class="mcp-header">
<h3 class="bold-title">MCP接入点</h3> <h3 class="bold-title">MCP Access Point</h3>
</div> </div>
<div class="url-header"> <div class="url-header">
<div class="address-desc"> <div class="address-desc">
<span>以下是智能体的MCP接入点地址。</span> <span>Below is the MCP access point address for the agent.</span>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mcp-endpoint-integration.md" <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mcp-endpoint-integration.md"
target="_blank" class="doc-link">查看接入点使用文档</a> target="_blank" class="doc-link">View Access Point Usage Documentation</a>
</div> </div>
</div> </div>
<el-input v-model="mcpUrl" readonly class="url-input"> <el-input v-model="mcpUrl" readonly class="url-input">
<template #suffix> <template #suffix>
<el-button @click="copyUrl" class="inner-copy-btn" icon="el-icon-document-copy"> <el-button @click="copyUrl" class="inner-copy-btn" icon="el-icon-document-copy">
复制 Copy
</el-button> </el-button>
</template> </template>
</el-input> </el-input>
@ -126,17 +126,17 @@
<!-- 右侧区域 --> <!-- 右侧区域 -->
<div class="mcp-right"> <div class="mcp-right">
<div class="mcp-header"> <div class="mcp-header">
<h3 class="bold-title">接入点状态</h3> <h3 class="bold-title">Access Point Status</h3>
</div> </div>
<div class="status-container"> <div class="status-container">
<span class="status-indicator" :class="mcpStatus"></span> <span class="status-indicator" :class="mcpStatus"></span>
<span class="status-text">{{ <span class="status-text">{{
mcpStatus === 'connected' ? '已连接' : mcpStatus === 'connected' ? 'Connected' :
mcpStatus === 'loading' ? '加载中...' : '未连接' mcpStatus === 'loading' ? 'Loading...' : 'Disconnected'
}}</span> }}</span>
<button class="refresh-btn" @click="refreshStatus"> <button class="refresh-btn" @click="refreshStatus">
<span class="refresh-icon">↻</span> <span class="refresh-icon">↻</span>
<span>刷新</span> <span>Refresh</span>
</button> </button>
</div> </div>
<div class="mcp-tools-list"> <div class="mcp-tools-list">
@ -146,7 +146,7 @@
</el-button> </el-button>
</div> </div>
<div v-else class="no-tools"> <div v-else class="no-tools">
<span>暂无可用工具</span> <span>No tools available</span>
</div> </div>
</div> </div>
</div> </div>
@ -154,8 +154,8 @@
</div> </div>
<div class="drawer-footer"> <div class="drawer-footer">
<el-button @click="closeDialog">取消</el-button> <el-button @click="closeDialog">Cancel</el-button>
<el-button type="primary" @click="saveSelection">保存配置</el-button> <el-button type="primary" @click="saveSelection">Save Configuration</el-button>
</div> </div>
</el-drawer> </el-drawer>
</template> </template>
@ -262,13 +262,13 @@ export default {
try { try {
const successful = document.execCommand('copy'); const successful = document.execCommand('copy');
if (successful) { if (successful) {
this.$message.success('已复制到剪贴板'); this.$message.success('Copied to clipboard');
} else { } else {
this.$message.error('复制失败,请手动复制'); this.$message.error('Copy failed, please copy manually');
} }
} catch (err) { } catch (err) {
this.$message.error('复制失败,请手动复制'); this.$message.error('复制失败,请手动复制');
console.error('复制失败:', err); console.error('Copy failed:', err);
} finally { } finally {
document.body.removeChild(textarea); document.body.removeChild(textarea);
} }
@ -286,7 +286,7 @@ export default {
this.mcpUrl = res.data.data || ""; this.mcpUrl = res.data.data || "";
} else { } else {
this.mcpUrl = ""; this.mcpUrl = "";
console.error('获取MCP地址失败:', res.data.msg); console.error('Failed to get MCP address:', res.data.msg);
} }
}); });
}, },
@ -301,7 +301,7 @@ export default {
} else { } else {
this.mcpTools = []; this.mcpTools = [];
this.mcpStatus = "disconnected"; this.mcpStatus = "disconnected";
console.error('获取MCP工具列表失败:', res.data.msg); console.error('Failed to get MCP tool list:', res.data.msg);
} }
}); });
}, },
@ -325,7 +325,7 @@ export default {
const obj = JSON.parse(text); const obj = JSON.parse(text);
this.handleParamChange(this.currentFunction, key, obj); this.handleParamChange(this.currentFunction, key, obj);
} catch { } catch {
this.$message.error(`${this.currentFunction.name}的${key}字段格式错误:JSON格式有误`); this.$message.error(`${this.currentFunction.name}'s ${key} field format error: Invalid JSON format`);
} }
}, },
handleFunctionClick(func) { handleFunctionClick(func) {

View file

@ -1,38 +1,38 @@
<template> <template>
<el-header class="header"> <el-header class="header">
<div class="header-container"> <div class="header-container">
<!-- 左侧元素 --> <!-- Left side elements -->
<div class="header-left" @click="goHome"> <div class="header-left" @click="goHome">
<img loading="lazy" alt="" src="@/assets/xiaozhi-logo.png" class="logo-img" /> <img loading="lazy" alt="" src="@/assets/xiaozhi-logo.png" class="logo-img" />
<img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" class="brand-img" /> <img loading="lazy" alt="" src="@/assets/xiaozhi-ai.png" class="brand-img" />
</div> </div>
<!-- 中间导航菜单 --> <!-- Center navigation menu -->
<div class="header-center"> <div class="header-center">
<div class="equipment-management" <div class="equipment-management"
:class="{ 'active-tab': $route.path === '/home' || $route.path === '/role-config' || $route.path === '/device-management' }" :class="{ 'active-tab': $route.path === '/home' || $route.path === '/role-config' || $route.path === '/device-management' }"
@click="goHome"> @click="goHome">
<img loading="lazy" alt="" src="@/assets/header/robot.png" <img loading="lazy" alt="" src="@/assets/header/robot.png"
:style="{ filter: $route.path === '/home' || $route.path === '/role-config' || $route.path === '/device-management' ? 'brightness(0) invert(1)' : 'None' }" /> :style="{ filter: $route.path === '/home' || $route.path === '/role-config' || $route.path === '/device-management' ? 'brightness(0) invert(1)' : 'None' }" />
智能体管理 Agent Management
</div> </div>
<div v-if="isSuperAdmin" class="equipment-management" :class="{ 'active-tab': $route.path === '/model-config' }" <div v-if="isSuperAdmin" class="equipment-management" :class="{ 'active-tab': $route.path === '/model-config' }"
@click="goModelConfig"> @click="goModelConfig">
<img loading="lazy" alt="" src="@/assets/header/model_config.png" <img loading="lazy" alt="" src="@/assets/header/model_config.png"
:style="{ filter: $route.path === '/model-config' ? 'brightness(0) invert(1)' : 'None' }" /> :style="{ filter: $route.path === '/model-config' ? 'brightness(0) invert(1)' : 'None' }" />
模型配置 Model Configuration
</div> </div>
<div v-if="isSuperAdmin" class="equipment-management" <div v-if="isSuperAdmin" class="equipment-management"
:class="{ 'active-tab': $route.path === '/user-management' }" @click="goUserManagement"> :class="{ 'active-tab': $route.path === '/user-management' }" @click="goUserManagement">
<img loading="lazy" alt="" src="@/assets/header/user_management.png" <img loading="lazy" alt="" src="@/assets/header/user_management.png"
:style="{ filter: $route.path === '/user-management' ? 'brightness(0) invert(1)' : 'None' }" /> :style="{ filter: $route.path === '/user-management' ? 'brightness(0) invert(1)' : 'None' }" />
用户管理 User Management
</div> </div>
<div v-if="isSuperAdmin" class="equipment-management" <div v-if="isSuperAdmin" class="equipment-management"
:class="{ 'active-tab': $route.path === '/ota-management' }" @click="goOtaManagement"> :class="{ 'active-tab': $route.path === '/ota-management' }" @click="goOtaManagement">
<img loading="lazy" alt="" src="@/assets/header/firmware_update.png" <img loading="lazy" alt="" src="@/assets/header/firmware_update.png"
:style="{ filter: $route.path === '/ota-management' ? 'brightness(0) invert(1)' : 'None' }" /> :style="{ filter: $route.path === '/ota-management' ? 'brightness(0) invert(1)' : 'None' }" />
OTA管理 OTA Management
</div> </div>
<el-dropdown v-if="isSuperAdmin" trigger="click" class="equipment-management more-dropdown" <el-dropdown v-if="isSuperAdmin" trigger="click" class="equipment-management more-dropdown"
:class="{ 'active-tab': $route.path === '/dict-management' || $route.path === '/params-management' || $route.path === '/provider-management' || $route.path === '/server-side-management' }" :class="{ 'active-tab': $route.path === '/dict-management' || $route.path === '/params-management' || $route.path === '/provider-management' || $route.path === '/server-side-management' }"
@ -40,30 +40,30 @@
<span class="el-dropdown-link"> <span class="el-dropdown-link">
<img loading="lazy" alt="" src="@/assets/header/param_management.png" <img loading="lazy" alt="" src="@/assets/header/param_management.png"
:style="{ filter: $route.path === '/dict-management' || $route.path === '/params-management' || $route.path === '/provider-management' || $route.path === '/server-side-management' ? 'brightness(0) invert(1)' : 'None' }" /> :style="{ filter: $route.path === '/dict-management' || $route.path === '/params-management' || $route.path === '/provider-management' || $route.path === '/server-side-management' ? 'brightness(0) invert(1)' : 'None' }" />
参数字典 Parameters & Dictionary
<i class="el-icon-arrow-down el-icon--right" :class="{ 'rotate-down': paramDropdownVisible }"></i> <i class="el-icon-arrow-down el-icon--right" :class="{ 'rotate-down': paramDropdownVisible }"></i>
</span> </span>
<el-dropdown-menu slot="dropdown"> <el-dropdown-menu slot="dropdown">
<el-dropdown-item @click.native="goParamManagement"> <el-dropdown-item @click.native="goParamManagement">
参数管理 Parameter Management
</el-dropdown-item> </el-dropdown-item>
<el-dropdown-item @click.native="goDictManagement"> <el-dropdown-item @click.native="goDictManagement">
字典管理 Dictionary Management
</el-dropdown-item> </el-dropdown-item>
<el-dropdown-item @click.native="goProviderManagement"> <el-dropdown-item @click.native="goProviderManagement">
字段管理 Field Management
</el-dropdown-item> </el-dropdown-item>
<el-dropdown-item @click.native="goServerSideManagement"> <el-dropdown-item @click.native="goServerSideManagement">
服务端管理 Server Management
</el-dropdown-item> </el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</el-dropdown> </el-dropdown>
</div> </div>
<!-- 右侧元素 --> <!-- Right side elements -->
<div class="header-right"> <div class="header-right">
<div class="search-container" v-if="$route.path === '/home' && !(isSuperAdmin && isSmallScreen)"> <div class="search-container" v-if="$route.path === '/home' && !(isSuperAdmin && isSmallScreen)">
<el-input v-model="search" placeholder="输入名称搜索.." class="custom-search-input" <el-input v-model="search" placeholder="Search by name.." class="custom-search-input"
@keyup.enter.native="handleSearch"> @keyup.enter.native="handleSearch">
<i slot="suffix" class="el-icon-search search-icon" @click="handleSearch"></i> <i slot="suffix" class="el-icon-search search-icon" @click="handleSearch"></i>
</el-input> </el-input>
@ -71,18 +71,18 @@
<img loading="lazy" alt="" src="@/assets/home/avatar.png" class="avatar-img" /> <img loading="lazy" alt="" src="@/assets/home/avatar.png" class="avatar-img" />
<el-dropdown trigger="click" class="user-dropdown" @visible-change="handleUserDropdownVisibleChange"> <el-dropdown trigger="click" class="user-dropdown" @visible-change="handleUserDropdownVisibleChange">
<span class="el-dropdown-link"> <span class="el-dropdown-link">
{{ userInfo.username || '加载中...' }} {{ userInfo.username || 'Loading...' }}
<i class="el-icon-arrow-down el-icon--right" :class="{ 'rotate-down': userDropdownVisible }"></i> <i class="el-icon-arrow-down el-icon--right" :class="{ 'rotate-down': userDropdownVisible }"></i>
</span> </span>
<el-dropdown-menu slot="dropdown"> <el-dropdown-menu slot="dropdown">
<el-dropdown-item @click.native="showChangePasswordDialog">修改密码</el-dropdown-item> <el-dropdown-item @click.native="showChangePasswordDialog">Change Password</el-dropdown-item>
<el-dropdown-item @click.native="handleLogout">退出登录</el-dropdown-item> <el-dropdown-item @click.native="handleLogout">Logout</el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</el-dropdown> </el-dropdown>
</div> </div>
</div> </div>
<!-- 修改密码弹窗 --> <!-- Change Password Dialog -->
<ChangePasswordDialog v-model="isChangePasswordDialogVisible" /> <ChangePasswordDialog v-model="isChangePasswordDialogVisible" />
</el-header> </el-header>
</template> </template>
@ -90,14 +90,14 @@
<script> <script>
import userApi from '@/apis/module/user'; import userApi from '@/apis/module/user';
import { mapActions, mapGetters } from 'vuex'; import { mapActions, mapGetters } from 'vuex';
import ChangePasswordDialog from './ChangePasswordDialog.vue'; // 引入修改密码弹窗组件 import ChangePasswordDialog from './ChangePasswordDialog.vue'; // Import change password dialog component
export default { export default {
name: 'HeaderBar', name: 'HeaderBar',
components: { components: {
ChangePasswordDialog ChangePasswordDialog
}, },
props: ['devices'], // 接收父组件设备列表 props: ['devices'], // Receive device list from parent component
data() { data() {
return { return {
search: '', search: '',
@ -105,7 +105,7 @@ export default {
username: '', username: '',
mobile: '' mobile: ''
}, },
isChangePasswordDialogVisible: false, // 控制修改密码弹窗的显示 isChangePasswordDialogVisible: false, // Control the display of change password dialog
userDropdownVisible: false, userDropdownVisible: false,
paramDropdownVisible: false, paramDropdownVisible: false,
isSmallScreen: false isSmallScreen: false
@ -122,13 +122,13 @@ export default {
this.checkScreenSize(); this.checkScreenSize();
window.addEventListener('resize', this.checkScreenSize); window.addEventListener('resize', this.checkScreenSize);
}, },
//移除事件监听器 // Remove event listener
beforeDestroy() { beforeDestroy() {
window.removeEventListener('resize', this.checkScreenSize); window.removeEventListener('resize', this.checkScreenSize);
}, },
methods: { methods: {
goHome() { goHome() {
// 跳转到首页 // Navigate to home
this.$router.push('/home') this.$router.push('/home')
}, },
goUserManagement() { goUserManagement() {
@ -152,7 +152,7 @@ export default {
goServerSideManagement() { goServerSideManagement() {
this.$router.push('/server-side-management') this.$router.push('/server-side-management')
}, },
// 获取用户信息 // Get user information
fetchUserInfo() { fetchUserInfo() {
userApi.getUserInfo(({ data }) => { userApi.getUserInfo(({ data }) => {
this.userInfo = data.data this.userInfo = data.data
@ -164,46 +164,46 @@ export default {
checkScreenSize() { checkScreenSize() {
this.isSmallScreen = window.innerWidth <= 1386; this.isSmallScreen = window.innerWidth <= 1386;
}, },
// 处理搜索 // Handle search
handleSearch() { handleSearch() {
const searchValue = this.search.trim(); const searchValue = this.search.trim();
// 如果搜索内容为空,触发重置事件 // If search content is empty, trigger reset event
if (!searchValue) { if (!searchValue) {
this.$emit('search-reset'); this.$emit('search-reset');
return; return;
} }
try { try {
// 创建不区分大小写的正则表达式 // Create case-insensitive regular expression
const regex = new RegExp(searchValue, 'i'); const regex = new RegExp(searchValue, 'i');
// 触发搜索事件,将正则表达式传递给父组件 // Trigger search event, pass regex to parent component
this.$emit('search', regex); this.$emit('search', regex);
} catch (error) { } catch (error) {
console.error('正则表达式创建失败:', error); console.error('Failed to create regular expression:', error);
this.$message.error({ this.$message.error({
message: '搜索关键词格式不正确', message: 'Invalid search keyword format',
showClose: true showClose: true
}); });
} }
}, },
// 显示修改密码弹窗 // Show change password dialog
showChangePasswordDialog() { showChangePasswordDialog() {
this.isChangePasswordDialogVisible = true; this.isChangePasswordDialogVisible = true;
}, },
// 退出登录 // Logout
async handleLogout() { async handleLogout() {
try { try {
// 调用 Vuex 的 logout action // Call Vuex logout action
await this.logout(); await this.logout();
this.$message.success({ this.$message.success({
message: '退出登录成功', message: 'Logout successful',
showClose: true showClose: true
}); });
} catch (error) { } catch (error) {
console.error('退出登录失败:', error); console.error('Logout failed:', error);
this.$message.error({ this.$message.error({
message: '退出登录失败,请重试', message: 'Logout failed, please try again',
showClose: true showClose: true
}); });
} }
@ -211,12 +211,12 @@ export default {
handleUserDropdownVisibleChange(visible) { handleUserDropdownVisibleChange(visible) {
this.userDropdownVisible = visible; this.userDropdownVisible = visible;
}, },
// 监听第二个下拉菜单的可见状态变化 // Listen to the visibility change of the second dropdown menu
handleParamDropdownVisibleChange(visible) { handleParamDropdownVisibleChange(visible) {
this.paramDropdownVisible = visible; this.paramDropdownVisible = visible;
}, },
// 使用 mapActions 引入 Vuex 的 logout action // Use mapActions to import Vuex logout action
...mapActions(['logout']) ...mapActions(['logout'])
} }
} }
@ -228,7 +228,7 @@ export default {
border: 1px solid #fff; border: 1px solid #fff;
height: 63px !important; height: 63px !important;
min-width: 900px; min-width: 900px;
/* 设置最小宽度防止过度压缩 */ /* Set minimum width to prevent excessive compression */
overflow: hidden; overflow: hidden;
} }
@ -288,7 +288,7 @@ export default {
transition: all 0.3s ease; transition: all 0.3s ease;
cursor: pointer; cursor: pointer;
flex-shrink: 0; flex-shrink: 0;
/* 防止导航按钮被压缩 */ /* Prevent navigation buttons from being compressed */
padding: 0 15px; padding: 0 15px;
position: relative; position: relative;
} }
@ -364,7 +364,7 @@ export default {
transition: transform 0.3s ease; transition: transform 0.3s ease;
} }
/* 响应式调整 */ /* Responsive adjustments */
@media (max-width: 1200px) { @media (max-width: 1200px) {
.header-center { .header-center {
gap: 14px; gap: 14px;

View file

@ -1,9 +1,9 @@
<template> <template>
<el-dialog title="手动添加设备" :visible="visible" @close="handleClose" width="30%" center> <el-dialog title="Manual Add Device" :visible="visible" @close="handleClose" width="30%" center>
<div class="dialog-content"> <div class="dialog-content">
<el-form :model="deviceForm" :rules="rules" ref="deviceForm" label-width="100px"> <el-form :model="deviceForm" :rules="rules" ref="deviceForm" label-width="100px">
<el-form-item label="设备型号" prop="board"> <el-form-item label="Device Model" prop="board">
<el-select v-model="deviceForm.board" placeholder="请选择设备型号" style="width: 100%"> <el-select v-model="deviceForm.board" placeholder="Please select device model" style="width: 100%">
<el-option <el-option
v-for="item in firmwareTypes" v-for="item in firmwareTypes"
:key="item.key" :key="item.key"
@ -12,17 +12,17 @@
</el-option> </el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="固件版本" prop="appVersion"> <el-form-item label="Firmware Version" prop="appVersion">
<el-input v-model="deviceForm.appVersion" placeholder="请输入固件版本"></el-input> <el-input v-model="deviceForm.appVersion" placeholder="Please enter firmware version"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Mac地址" prop="macAddress"> <el-form-item label="MAC Address" prop="macAddress">
<el-input v-model="deviceForm.macAddress" placeholder="请输入Mac地址"></el-input> <el-input v-model="deviceForm.macAddress" placeholder="Please enter MAC address"></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
</div> </div>
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="submitForm">确定</div> <div class="dialog-btn" @click="submitForm">Confirm</div>
<div class="dialog-btn cancel-btn" @click="cancel">取消</div> <div class="dialog-btn cancel-btn" @click="cancel">Cancel</div>
</div> </div>
</el-dialog> </el-dialog>
</template> </template>
@ -37,13 +37,13 @@ export default {
agentId: { type: String, required: true } agentId: { type: String, required: true }
}, },
data() { data() {
// MAC地址验证规则 // MAC address validation rules
const validateMac = (rule, value, callback) => { const validateMac = (rule, value, callback) => {
const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/; const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
if (!value) { if (!value) {
callback(new Error('请输入Mac地址')); callback(new Error('Please enter MAC address'));
} else if (!macRegex.test(value)) { } else if (!macRegex.test(value)) {
callback(new Error('请输入正确的Mac地址格式,例如:00:1A:2B:3C:4D:5E')); callback(new Error('Please enter correct MAC address format, e.g.: 00:1A:2B:3C:4D:5E'));
} else { } else {
callback(); callback();
} }
@ -58,10 +58,10 @@ export default {
firmwareTypes: [], firmwareTypes: [],
rules: { rules: {
board: [ board: [
{ required: true, message: '请选择设备型号', trigger: 'change' } { required: true, message: 'Please select device model', trigger: 'change' }
], ],
appVersion: [ appVersion: [
{ required: true, message: '请输入固件版本', trigger: 'blur' } { required: true, message: 'Please enter firmware version', trigger: 'blur' }
], ],
macAddress: [ macAddress: [
{ required: true, validator: validateMac, trigger: 'blur' } { required: true, validator: validateMac, trigger: 'blur' }
@ -78,8 +78,8 @@ export default {
const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE'); const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE');
this.firmwareTypes = res.data; this.firmwareTypes = res.data;
} catch (error) { } catch (error) {
console.error('获取固件类型失败:', error); console.error('Failed to get firmware types:', error);
this.$message.error(error.message || '获取固件类型失败'); this.$message.error(error.message || 'Failed to get firmware types');
} }
}, },
submitForm() { submitForm() {
@ -97,11 +97,11 @@ export default {
Api.device.manualAddDevice(params, ({ data }) => { Api.device.manualAddDevice(params, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('设备添加成功'); this.$message.success('Device added successfully');
this.$emit('refresh'); this.$emit('refresh');
this.closeDialog(); this.closeDialog();
} else { } else {
this.$message.error(data.msg || '添加失败'); this.$message.error(data.msg || 'Failed to add');
} }
}); });
}, },

View file

@ -3,7 +3,7 @@
class="center-dialog" > class="center-dialog" >
<div style="margin: 0 18px; text-align: left; padding: 10px; border-radius: 10px;"> <div style="margin: 0 18px; text-align: left; padding: 10px; border-radius: 10px;">
<div style="font-size: 30px; color: #3d4566; margin-top: -10px; margin-bottom: 10px; text-align: center;"> <div style="font-size: 30px; color: #3d4566; margin-top: -10px; margin-bottom: 10px; text-align: center;">
修改模型 Edit Model
</div> </div>
<button class="custom-close-btn" @click="dialogVisible = false"> <button class="custom-close-btn" @click="dialogVisible = false">
@ -11,14 +11,14 @@
</button> </button>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div style="font-size: 20px; font-weight: bold; color: #3d4566;">模型信息</div> <div style="font-size: 20px; font-weight: bold; color: #3d4566;">Model Information</div>
<div style="display: flex; align-items: center; gap: 20px;"> <div style="display: flex; align-items: center; gap: 20px;">
<div style="display: flex; align-items: center;"> <div style="display: flex; align-items: center;">
<span style="margin-right: 8px;">是否启用</span> <span style="margin-right: 8px;">Enable</span>
<el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" class="custom-switch"></el-switch> <el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" class="custom-switch"></el-switch>
</div> </div>
<div style="display: none; align-items: center;"> <div style="display: none; align-items: center;">
<span style="margin-right: 8px;">设为默认</span> <span style="margin-right: 8px;">Set as Default</span>
<el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" class="custom-switch"></el-switch> <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" class="custom-switch"></el-switch>
</div> </div>
</div> </div>
@ -28,37 +28,37 @@
<el-form :model="form" ref="form" label-width="100px" label-position="left" class="custom-form"> <el-form :model="form" ref="form" label-width="100px" label-position="left" class="custom-form">
<div style="display: flex; gap: 20px; margin-bottom: 0;"> <div style="display: flex; gap: 20px; margin-bottom: 0;">
<el-form-item label="模型名称" prop="name" style="flex: 1;"> <el-form-item label="Model Name" prop="name" style="flex: 1;">
<el-input v-model="form.modelName" placeholder="请输入模型名称" class="custom-input-bg"></el-input> <el-input v-model="form.modelName" placeholder="Please enter model name" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="模型编码" prop="code" style="flex: 1;"> <el-form-item label="Model Code" prop="code" style="flex: 1;">
<el-input v-model="form.modelCode" placeholder="请输入模型编码" class="custom-input-bg"></el-input> <el-input v-model="form.modelCode" placeholder="Please enter model code" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
</div> </div>
<div style="display: flex; gap: 20px; margin-bottom: 0;"> <div style="display: flex; gap: 20px; margin-bottom: 0;">
<el-form-item label="供应器" prop="supplier" style="flex: 1;"> <el-form-item label="Provider" prop="supplier" style="flex: 1;">
<el-select v-model="form.configJson.type" placeholder="请选择" class="custom-select custom-input-bg" <el-select v-model="form.configJson.type" placeholder="Please select" class="custom-select custom-input-bg"
style="width: 100%;" @focus="loadProviders" filterable> style="width: 100%;" @focus="loadProviders" filterable>
<el-option v-for="item in providers" :key="item.value" :label="item.label" :value="item.value" /> <el-option v-for="item in providers" :key="item.value" :label="item.label" :value="item.value" />
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="排序号" prop="sort" style="flex: 1;"> <el-form-item label="Sort Order" prop="sort" style="flex: 1;">
<el-input v-model.number="form.sort" type="number" placeholder="请输入排序号" class="custom-input-bg"></el-input> <el-input v-model.number="form.sort" type="number" placeholder="Please enter sort order" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
</div> </div>
<el-form-item label="文档地址" prop="docUrl" style="margin-bottom: 27px;"> <el-form-item label="Document URL" prop="docUrl" style="margin-bottom: 27px;">
<el-input v-model="form.docLink" placeholder="请输入文档地址" class="custom-input-bg"></el-input> <el-input v-model="form.docLink" placeholder="Please enter document URL" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="备注" prop="remark" class="prop-remark"> <el-form-item label="Remarks" prop="remark" class="prop-remark">
<el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入模型备注" :autosize="{ minRows: 3, maxRows: 5 }" <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="Please enter model remarks" :autosize="{ minRows: 3, maxRows: 5 }"
class="custom-input-bg"></el-input> class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
<div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;">调用信息</div> <div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;">API Configuration</div>
<div style="height: 2px; background: #e9e9e9; margin-bottom: 22px;"></div> <div style="height: 2px; background: #e9e9e9; margin-bottom: 22px;"></div>
<el-form :model="form.configJson" ref="callInfoForm" label-width="auto" class="custom-form"> <el-form :model="form.configJson" ref="callInfoForm" label-width="auto" class="custom-form">
@ -67,7 +67,7 @@
<el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop" <el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop"
style="flex: 1;"> style="flex: 1;">
<template v-if="field.type === 'json-textarea'"> <template v-if="field.type === 'json-textarea'">
<el-input v-model="fieldJsonMap[field.prop]" type="textarea" :rows="3" placeholder="请输入JSON格式变量(示例:{'key':'value'})" <el-input v-model="fieldJsonMap[field.prop]" type="textarea" :rows="3" placeholder="Please enter JSON format variable (example: {'key':'value'})"
class="custom-input-bg" @change="(val) => handleJsonChange(field.prop, val)"></el-input> class="custom-input-bg" @change="(val) => handleJsonChange(field.prop, val)"></el-input>
</template> </template>
<el-input v-else v-model="form.configJson[field.prop]" :placeholder="field.placeholder" :type="field.type" <el-input v-else v-model="form.configJson[field.prop]" :placeholder="field.placeholder" :type="field.type"
@ -85,7 +85,7 @@
class="save-btn" class="save-btn"
:loading="saving" :loading="saving"
:disabled="saving"> :disabled="saving">
保存 Save
</el-button> </el-button>
</div> </div>
</el-dialog> </el-dialog>
@ -262,7 +262,7 @@ export default {
label: f.label, label: f.label,
prop: f.key, prop: f.key,
type: f.type === 'dict' ? 'json-textarea' : (f.type === 'password' ? 'password' : 'text'), type: f.type === 'dict' ? 'json-textarea' : (f.type === 'password' ? 'password' : 'text'),
placeholder: `请输入${f.label}` placeholder: `Please enter ${f.label}`
})); }));
if (this.pendingModelData && this.pendingProviderType === providerCode) { if (this.pendingModelData && this.pendingProviderType === providerCode) {
@ -312,13 +312,13 @@ export default {
return parsed; return parsed;
} }
this.$message.error({ this.$message.error({
message: '必须输入字典格式(如 {"key":"value"}),保存则使用原数据', message: 'Must enter dictionary format (e.g. {"key":"value"}), save will use original data',
showClose: true showClose: true
}); });
return null; return null;
} catch (e) { } catch (e) {
this.$message.error({ this.$message.error({
message: 'JSON格式错误(如 {"key":"value"}),保存则使用原数据', message: 'JSON format error (e.g. {"key":"value"}), save will use original data',
showClose: true showClose: true
}); });
return null; return null;

View file

@ -20,22 +20,22 @@
</div> </div>
<el-form :model="form" :rules="rules" ref="form" label-width="110px" label-position="left" class="param-form"> <el-form :model="form" :rules="rules" ref="form" label-width="110px" label-position="left" class="param-form">
<el-form-item label="参数编码" prop="paramCode" class="form-item"> <el-form-item label="Parameter Code" prop="paramCode" class="form-item">
<el-input v-model="form.paramCode" placeholder="请输入参数编码" class="custom-input"></el-input> <el-input v-model="form.paramCode" placeholder="Please enter parameter code" class="custom-input"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="参数值" prop="paramValue" class="form-item"> <el-form-item label="Parameter Value" prop="paramValue" class="form-item">
<el-input v-model="form.paramValue" placeholder="请输入参数值" class="custom-input"></el-input> <el-input v-model="form.paramValue" placeholder="Please enter parameter value" class="custom-input"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="值类型" prop="valueType" class="form-item"> <el-form-item label="Value Type" prop="valueType" class="form-item">
<el-select v-model="form.valueType" placeholder="请选择值类型" class="custom-select"> <el-select v-model="form.valueType" placeholder="Please select value type" class="custom-select">
<el-option v-for="item in valueTypeOptions" :key="item.value" :label="item.label" :value="item.value"/> <el-option v-for="item in valueTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="备注" prop="remark" class="form-item remark-item"> <el-form-item label="Remarks" prop="remark" class="form-item remark-item">
<el-input type="textarea" v-model="form.remark" placeholder="请输入备注" :rows="3" class="custom-textarea"></el-input> <el-input type="textarea" v-model="form.remark" placeholder="Please enter remarks" :rows="3" class="custom-textarea"></el-input>
</el-form-item> </el-form-item>
</el-form> </el-form>
@ -46,10 +46,10 @@
class="save-btn" class="save-btn"
:loading="saving" :loading="saving"
:disabled="saving"> :disabled="saving">
保存 Save
</el-button> </el-button>
<el-button @click="cancel" class="cancel-btn"> <el-button @click="cancel" class="cancel-btn">
取消 Cancel
</el-button> </el-button>
</div> </div>
</div> </div>
@ -61,7 +61,7 @@ export default {
props: { props: {
title: { title: {
type: String, type: String,
default: '新增参数' default: 'Add Parameter'
}, },
visible: { visible: {
type: Boolean, type: Boolean,
@ -83,21 +83,21 @@ export default {
dialogKey: Date.now(), dialogKey: Date.now(),
saving: false, saving: false,
valueTypeOptions: [ valueTypeOptions: [
{ value: 'string', label: '字符串(string)' }, { value: 'string', label: 'String (string)' },
{ value: 'number', label: '数字(number)' }, { value: 'number', label: 'Number (number)' },
{ value: 'boolean', label: '布尔值(boolean)' }, { value: 'boolean', label: 'Boolean (boolean)' },
{ value: 'array', label: '数组(array)' }, { value: 'array', label: 'Array (array)' },
{ value: 'json', label: 'JSON对象(json)' } { value: 'json', label: 'JSON Object (json)' }
], ],
rules: { rules: {
paramCode: [ paramCode: [
{ required: true, message: "请输入参数编码", trigger: "blur" } { required: true, message: "Please enter parameter code", trigger: "blur" }
], ],
paramValue: [ paramValue: [
{ required: true, message: "请输入参数值", trigger: "blur" } { required: true, message: "Please enter parameter value", trigger: "blur" }
], ],
valueType: [ valueType: [
{ required: true, message: "请选择值类型", trigger: "change" } { required: true, message: "Please select value type", trigger: "change" }
] ]
} }
}; };

View file

@ -11,42 +11,42 @@
<el-form :model="form" label-width="100px" :rules="rules" ref="form" class="custom-form"> <el-form :model="form" label-width="100px" :rules="rules" ref="form" class="custom-form">
<div style="display: flex; gap: 20px; margin-bottom: 20px;"> <div style="display: flex; gap: 20px; margin-bottom: 20px;">
<el-form-item label="类别" prop="modelType" style="flex: 1;"> <el-form-item label="Category" prop="modelType" style="flex: 1;">
<el-select v-model="form.modelType" placeholder="请选择类别" class="custom-input-bg" style="width: 100%;"> <el-select v-model="form.modelType" placeholder="Please select category" class="custom-input-bg" style="width: 100%;">
<el-option v-for="item in modelTypes" :key="item.value" :label="item.label" :value="item.value"> <el-option v-for="item in modelTypes" :key="item.value" :label="item.label" :value="item.value">
</el-option> </el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="编码" prop="providerCode" style="flex: 1;"> <el-form-item label="Code" prop="providerCode" style="flex: 1;">
<el-input v-model="form.providerCode" placeholder="请输入供应器编码" class="custom-input-bg"></el-input> <el-input v-model="form.providerCode" placeholder="Please enter provider code" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
</div> </div>
<div style="display: flex; gap: 20px; margin-bottom: 20px;"> <div style="display: flex; gap: 20px; margin-bottom: 20px;">
<el-form-item label="名称" prop="name" style="flex: 1;"> <el-form-item label="Name" prop="name" style="flex: 1;">
<el-input v-model="form.name" placeholder="请输入供应器名称" class="custom-input-bg"></el-input> <el-input v-model="form.name" placeholder="Please enter provider name" class="custom-input-bg"></el-input>
</el-form-item> </el-form-item>
<el-form-item label="排序" prop="sort" style="flex: 1;"> <el-form-item label="Sort" prop="sort" style="flex: 1;">
<el-input-number v-model="form.sort" :min="0" controls-position="right" class="custom-input-bg" <el-input-number v-model="form.sort" :min="0" controls-position="right" class="custom-input-bg"
style="width: 100%;"></el-input-number> style="width: 100%;"></el-input-number>
</el-form-item> </el-form-item>
</div> </div>
<div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;"> <div style="font-size: 20px; font-weight: bold; color: #3d4566; margin-bottom: 15px;">
字段配置 Field Configuration
<div style="display: inline-block; float: right;"> <div style="display: inline-block; float: right;">
<el-button type="primary" @click="addField" size="small" style="background: #5bc98c; border: none;" <el-button type="primary" @click="addField" size="small" style="background: #5bc98c; border: none;"
:disabled="hasIncompleteFields"> :disabled="hasIncompleteFields">
添加 Add
</el-button> </el-button>
<el-button type="primary" @click="toggleSelectAllFields" size="small" <el-button type="primary" @click="toggleSelectAllFields" size="small"
style="background: #5f70f3; border: none; margin-left: 10px;"> style="background: #5f70f3; border: none; margin-left: 10px;">
{{ isAllFieldsSelected ? '取消全选' : '全选' }} {{ isAllFieldsSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button type="danger" @click="batchRemoveFields" size="small" <el-button type="danger" @click="batchRemoveFields" size="small"
style="background: red; border: none; margin-left: 10px;"> style="background: red; border: none; margin-left: 10px;">
批量删除 Batch Delete
</el-button> </el-button>
</div> </div>
</div> </div>
@ -54,40 +54,40 @@
<div class="fields-container"> <div class="fields-container">
<el-table :data="form.fields" style="width: 100%;" border size="medium" :key="tableKey"> <el-table :data="form.fields" style="width: 100%;" border size="medium" :key="tableKey">
<el-table-column label="选择" align="center" width="50"> <el-table-column label="Select" align="center" width="50">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected" @change="handleFieldSelectChange"></el-checkbox> <el-checkbox v-model="scope.row.selected" @change="handleFieldSelectChange"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="字段key"> <el-table-column label="Field Key">
<template slot-scope="scope"> <template slot-scope="scope">
<template v-if="scope.row.editing"> <template v-if="scope.row.editing">
<el-input v-model="scope.row.key" placeholder="字段key"></el-input> <el-input v-model="scope.row.key" placeholder="Field key"></el-input>
</template> </template>
<template v-else> <template v-else>
{{ scope.row.key }} {{ scope.row.key }}
</template> </template>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="字段标签"> <el-table-column label="Field Label">
<template slot-scope="scope"> <template slot-scope="scope">
<template v-if="scope.row.editing"> <template v-if="scope.row.editing">
<el-input v-model="scope.row.label" placeholder="字段标签"></el-input> <el-input v-model="scope.row.label" placeholder="Field label"></el-input>
</template> </template>
<template v-else> <template v-else>
{{ scope.row.label }} {{ scope.row.label }}
</template> </template>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="字段类型"> <el-table-column label="Field Type">
<template slot-scope="scope"> <template slot-scope="scope">
<template v-if="scope.row.editing"> <template v-if="scope.row.editing">
<el-select v-model="scope.row.type" placeholder="类型"> <el-select v-model="scope.row.type" placeholder="Type">
<el-option label="字符串" value="string"></el-option> <el-option label="String" value="string"></el-option>
<el-option label="数字" value="number"></el-option> <el-option label="Number" value="number"></el-option>
<el-option label="布尔值" value="boolean"></el-option> <el-option label="Boolean" value="boolean"></el-option>
<el-option label="字典" value="dict"></el-option> <el-option label="Dictionary" value="dict"></el-option>
<el-option label="分号分割的列表" value="array"></el-option> <el-option label="Semicolon-separated List" value="array"></el-option>
</el-select> </el-select>
</template> </template>
<template v-else> <template v-else>
@ -95,26 +95,26 @@
</template> </template>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="默认值"> <el-table-column label="Default Value">
<template slot-scope="scope"> <template slot-scope="scope">
<template v-if="scope.row.editing"> <template v-if="scope.row.editing">
<el-input v-model="scope.row.default" placeholder="请输入默认值"></el-input> <el-input v-model="scope.row.default" placeholder="Please enter default value"></el-input>
</template> </template>
<template v-else> <template v-else>
{{ scope.row.default }} {{ scope.row.default }}
</template> </template>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" width="150" align="center"> <el-table-column label="Actions" width="150" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button v-if="!scope.row.editing" type="primary" size="mini" @click="startEditing(scope.row)"> <el-button v-if="!scope.row.editing" type="primary" size="mini" @click="startEditing(scope.row)">
编辑 Edit
</el-button> </el-button>
<el-button v-else type="success" size="mini" @click="stopEditing(scope.row)"> <el-button v-else type="success" size="mini" @click="stopEditing(scope.row)">
完成 Done
</el-button> </el-button>
<el-button type="danger" size="mini" @click="removeField(scope.$index)"> <el-button type="danger" size="mini" @click="removeField(scope.$index)">
删除 Delete
</el-button> </el-button>
</template> </template>
</el-table-column> </el-table-column>
@ -124,7 +124,7 @@
</div> </div>
<div style="display: flex; justify-content: center;"> <div style="display: flex; justify-content: center;">
<el-button type="primary" @click="submit" class="save-btn" :loading="saving">保存</el-button> <el-button type="primary" @click="submit" class="save-btn" :loading="saving">Save</el-button>
</div> </div>
</el-dialog> </el-dialog>
</template> </template>
@ -141,12 +141,12 @@ export default {
return { return {
saving: false, saving: false,
rules: { rules: {
modelType: [{ required: true, message: '请选择类别', trigger: 'change' }], modelType: [{ required: true, message: 'Please select category', trigger: 'change' }],
providerCode: [{ required: true, message: '请输入供应器编码', trigger: 'blur' }], providerCode: [{ required: true, message: 'Please enter provider code', trigger: 'blur' }],
name: [{ required: true, message: '请输入供应器名称', trigger: 'blur' }] name: [{ required: true, message: 'Please enter provider name', trigger: 'blur' }]
}, },
isAllFieldsSelected: false, isAllFieldsSelected: false,
tableKey: 0 // 用于强制表格重新渲染 tableKey: 0 // Used to force table re-render
}; };
}, },
computed: { computed: {
@ -159,11 +159,11 @@ export default {
methods: { methods: {
getTypeLabel(type) { getTypeLabel(type) {
const typeMap = { const typeMap = {
'string': '字符串', 'string': 'String',
'number': '数字', 'number': 'Number',
'boolean': '布尔值', 'boolean': 'Boolean',
'dict': '字典', 'dict': 'Dictionary',
'array': '分号分割的列表' 'array': 'Semicolon-separated List'
}; };
return typeMap[type]; return typeMap[type];
}, },
@ -212,7 +212,7 @@ export default {
addField() { addField() {
if (this.hasIncompleteFields) { if (this.hasIncompleteFields) {
this.$message.warning({ this.$message.warning({
message: '请先完成当前字段的编辑', message: 'Please complete editing the current field first',
showClose: true showClose: true
}); });
return; return;
@ -230,21 +230,21 @@ export default {
}, },
removeField(index) { removeField(index) {
this.$confirm('确定要删除该字段吗?', '提示', { this.$confirm('Are you sure you want to delete this field?', 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
this.form.fields = this.form.fields.filter((_, i) => i !== index); this.form.fields = this.form.fields.filter((_, i) => i !== index);
this.updateSelectAllStatus(); this.updateSelectAllStatus();
this.forceTableRerender(); this.forceTableRerender();
this.$message.success({ this.$message.success({
message: '删除成功', message: 'Deleted successfully',
showClose: true showClose: true
}); });
}).catch(() => { }).catch(() => {
this.$message.info({ this.$message.info({
message: '已取消删除', message: 'Delete operation cancelled',
showClose: true showClose: true
}); });
}); });
@ -254,26 +254,26 @@ export default {
const selectedFields = this.form.fields.filter(field => field.selected); const selectedFields = this.form.fields.filter(field => field.selected);
if (selectedFields.length === 0) { if (selectedFields.length === 0) {
this.$message.warning({ this.$message.warning({
message: '请先选择要删除的字段', message: 'Please select fields to delete first',
showClose: true showClose: true
}); });
return; return;
} }
this.$confirm(`确定要删除选中的 ${selectedFields.length} 个字段吗?`, '提示', { this.$confirm(`Are you sure you want to delete ${selectedFields.length} selected fields?`, 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
this.form.fields = this.form.fields.filter(field => !field.selected); this.form.fields = this.form.fields.filter(field => !field.selected);
this.isAllFieldsSelected = false; this.isAllFieldsSelected = false;
this.forceTableRerender(); this.forceTableRerender();
this.$message.success({ this.$message.success({
message: `成功删除 ${selectedFields.length} 个字段`, message: `Successfully deleted ${selectedFields.length} fields`,
showClose: true showClose: true
}); });
}).catch(() => { }).catch(() => {
this.$message.info({ this.$message.info({
message: '已取消删除', message: 'Delete operation cancelled',
showClose: true showClose: true
}); });
}); });
@ -285,7 +285,7 @@ export default {
}, },
forceTableRerender() { forceTableRerender() {
this.tableKey += 1; // 改变key值强制表格重新渲染 this.tableKey += 1; // Change key value to force table re-render
}, },
submit() { submit() {
@ -294,7 +294,7 @@ export default {
const editingField = this.form.fields.find(field => field.editing); const editingField = this.form.fields.find(field => field.editing);
if (editingField) { if (editingField) {
this.$message.warning({ this.$message.warning({
message: '请先完成当前字段的编辑', message: 'Please complete editing the current field first',
showClose: true showClose: true
}); });
return; return;

View file

@ -9,30 +9,30 @@
<el-table v-loading="loading" :data="filteredTtsModels" style="width: 100%;" class="data-table" <el-table v-loading="loading" :data="filteredTtsModels" style="width: 100%;" class="data-table"
header-row-class-name="table-header" :fit="true" element-loading-text="拼命加载中" header-row-class-name="table-header" :fit="true" element-loading-text="拼命加载中"
element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"> element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
<el-table-column label="选择" width="50" align="center"> <el-table-column label="Select" width="50" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="音色编码" align="center"> <el-table-column label="Voice Code" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-input v-if="scope.row.editing" v-model="scope.row.voiceCode"></el-input> <el-input v-if="scope.row.editing" v-model="scope.row.voiceCode"></el-input>
<span v-else>{{ scope.row.voiceCode }}</span> <span v-else>{{ scope.row.voiceCode }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="音色名称" align="center"> <el-table-column label="Voice Name" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-input v-if="scope.row.editing" v-model="scope.row.voiceName"></el-input> <el-input v-if="scope.row.editing" v-model="scope.row.voiceName"></el-input>
<span v-else>{{ scope.row.voiceName }}</span> <span v-else>{{ scope.row.voiceName }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="语言类型" align="center"> <el-table-column label="Language Type" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-input v-if="scope.row.editing" v-model="scope.row.languageType"></el-input> <el-input v-if="scope.row.editing" v-model="scope.row.languageType"></el-input>
<span v-else>{{ scope.row.languageType }}</span> <span v-else>{{ scope.row.languageType }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column v-if="!showReferenceColumns" label="试听" align="center" class-name="audio-column"> <el-table-column v-if="!showReferenceColumns" label="Preview" align="center" class-name="audio-column">
<template slot-scope="scope"> <template slot-scope="scope">
<div class="custom-audio-container"> <div class="custom-audio-container">
<el-input v-if="scope.row.editing" v-model="scope.row.voiceDemo" placeholder="请输入MP3地址" <el-input v-if="scope.row.editing" v-model="scope.row.voiceDemo" placeholder="请输入MP3地址"
@ -42,33 +42,33 @@
</div> </div>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column v-if="!showReferenceColumns" label="备注" align="center"> <el-table-column v-if="!showReferenceColumns" label="Remarks" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-input v-if="scope.row.editing" type="textarea" :rows="1" autosize v-model="scope.row.remark" <el-input v-if="scope.row.editing" type="textarea" :rows="1" autosize v-model="scope.row.remark"
placeholder="这里是备注" class="remark-input"></el-input> placeholder="这里是备注" class="remark-input"></el-input>
<span v-else>{{ scope.row.remark }}</span> <span v-else>{{ scope.row.remark }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column v-if="showReferenceColumns" label="克隆音频路径" align="center"> <el-table-column v-if="showReferenceColumns" label="Clone Audio Path" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-input v-if="scope.row.editing" v-model="scope.row.referenceAudio" placeholder="这里是克隆音频路径"></el-input> <el-input v-if="scope.row.editing" v-model="scope.row.referenceAudio" placeholder="这里是克隆音频路径"></el-input>
<span v-else>{{ scope.row.referenceAudio }}</span> <span v-else>{{ scope.row.referenceAudio }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column v-if="showReferenceColumns" label="克隆音频文本" align="center"> <el-table-column v-if="showReferenceColumns" label="Clone Audio Text" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-input v-if="scope.row.editing" v-model="scope.row.referenceText" placeholder="这里是克隆音频对应文本"></el-input> <el-input v-if="scope.row.editing" v-model="scope.row.referenceText" placeholder="这里是克隆音频对应文本"></el-input>
<span v-else>{{ scope.row.referenceText }}</span> <span v-else>{{ scope.row.referenceText }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" align="center" width="150"> <el-table-column label="Actions" align="center" width="150">
<template slot-scope="scope"> <template slot-scope="scope">
<template v-if="!scope.row.editing"> <template v-if="!scope.row.editing">
<el-button type="text" size="mini" @click="startEdit(scope.row)" class="edit-btn"> <el-button type="text" size="mini" @click="startEdit(scope.row)" class="edit-btn">
编辑 Edit
</el-button> </el-button>
<el-button type="text" size="mini" @click="deleteRow(scope.row)" class="delete-btn"> <el-button type="text" size="mini" @click="deleteRow(scope.row)" class="delete-btn">
删除 Delete
</el-button> </el-button>
</template> </template>
<el-button v-else type="success" size="mini" @click="saveEdit(scope.row)" class="save-Tts">保存 <el-button v-else type="success" size="mini" @click="saveEdit(scope.row)" class="save-Tts">保存
@ -87,10 +87,10 @@
</div> </div>
<div class="action-buttons"> <div class="action-buttons">
<el-button type="primary" size="mini" @click="toggleSelectAll" style="background: #606ff3;border: None"> <el-button type="primary" size="mini" @click="toggleSelectAll" style="background: #606ff3;border: None">
{{ selectAll ? '取消全选' : '全选' }} {{ selectAll ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button type="primary" size="mini" @click="addNew" style="background: #5bc98c;border: None;"> <el-button type="primary" size="mini" @click="addNew" style="background: #5bc98c;border: None;">
新增 Add
</el-button> </el-button>
<el-button type="primary" size="mini" @click="deleteRow(filteredTtsModels.filter(row => row.selected))" <el-button type="primary" size="mini" @click="deleteRow(filteredTtsModels.filter(row => row.selected))"
style="background: red;border:None">删除 style="background: red;border:None">删除

View file

@ -8,7 +8,7 @@
rel="noopener" class="beian-link"> rel="noopener" class="beian-link">
<img <img
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAMAAABhEH5lAAACXlBMVEUAAADax4rGxqP556zmsVD/6KXu5JvwvFPglEFnY3nnpEjosU1+XFTmuVfu13Hrv1jpsFa1k3mne2HlvnPdqmPqz3fu3YrJoWv04J/mz5z246aSi3i2p2/0zGj82WDrtFjar1O7klO4dkfimUJcWnbho0rgr1vntFfmvFflvGOZdFKXZkOUemnmv2XkuWWVe2ziqlXnt1Tr0HDpwl6ObmCkbEKqhVyOc2jdoVHmuljfrmDq0nPapWDUnErqy3XjtWXesXLrzHjz34rqzYfmw3fy4YrqyYDevW/dzoTIhkndsXLRsIneuHjlyIzQroTjuXjlyYfktWvw2prhvoHTmGfx45j3773TuYT/25LdijyKf321oXU+Nm3cumXfuWLtwlzpwVz40FvpvlvqvFfouFXjrlHipEjcmEfknEXPbzfbZyzZQR/YMBrWKBrhJhLdHxDTGg5HV4xBT4YYKYaWk4SDgYIWIYBybH0qLn1KS3tlZHpNS3WGfHIcHXEwLHAnF28rKW07NGuzn2pNQ2ruzWnDrGnuy2jryGjAnGgoH2j1x2RCNGPcrmIsEGGQdl/pu17YtV7FoV3muVxoRVzWqFvSmVp2SVbyw1XbkVTuvFPfo1PgmVPpt1LcnFLWkVLlp1F7W1HpsU92QE5oMUtFAUrpqUjnjUFOAEHUgz+DUj14FzvbczieMTdhATfodjXWcDXcbjXVcTS/Xi/hay7WXS3cWS3vYyvaVSrUVymnJSjXSyeKDSbNSiWfHCPMTyLFQiHkSR/lPxvVLRrPLBnUJRfUHhbaJxXVGxTZJxPNFhBdOhm/AAAAWXRSTlMABQIU/hIJ/v79/Pj29PPx4cC6s7CNfmxZWRv+/v7+/v7+/v78/Pr6+fPz8vHq6ujl5eTj4ODe2NTQzMW6ubKsnJeQkJCJiIOBgX9ubGpoW1lMREM0JR8dDgvYx1gAAAE7SURBVBjTYgADJmZJQUFJZiYGOGD2EzLV1jIT8paCibCJ86zctGPD1D4ecUaICKuPyYLMYznZOfNqzP0jwEJBOt1KB4/mHjqZ3dGsHwxW5M4Zk5l/PPdIQcGMShUPVqBlgQLlMSvyDq+P3HVidjWnkQQTA5MXV1SFYtb+jZGrl02si2J3Y2JgFMmILl68efueLVvXLSqLXirCCBgDow1HT+GS/AP7srblLS+K5bIHCjmodpXUr929d+eaVb3SsuouQCHhufPjShsbJk/rrK2KW8hiBxRyVkvnkI9tnaDQJDNFOU1DDOjRMEfe9Mjpiewz5RIzZmmKMoPcKqGbkJqSkBSfnDqpXS+ACeRpJ76W/uSUpDlpLPFtfK5soLAKFbU05Odm4eblN7YWk4KEGWOIp62FgYCVsG84SAAAL7BaooX965sAAAAASUVORK5CYII=" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAMAAABhEH5lAAACXlBMVEUAAADax4rGxqP556zmsVD/6KXu5JvwvFPglEFnY3nnpEjosU1+XFTmuVfu13Hrv1jpsFa1k3mne2HlvnPdqmPqz3fu3YrJoWv04J/mz5z246aSi3i2p2/0zGj82WDrtFjar1O7klO4dkfimUJcWnbho0rgr1vntFfmvFflvGOZdFKXZkOUemnmv2XkuWWVe2ziqlXnt1Tr0HDpwl6ObmCkbEKqhVyOc2jdoVHmuljfrmDq0nPapWDUnErqy3XjtWXesXLrzHjz34rqzYfmw3fy4YrqyYDevW/dzoTIhkndsXLRsIneuHjlyIzQroTjuXjlyYfktWvw2prhvoHTmGfx45j3773TuYT/25LdijyKf321oXU+Nm3cumXfuWLtwlzpwVz40FvpvlvqvFfouFXjrlHipEjcmEfknEXPbzfbZyzZQR/YMBrWKBrhJhLdHxDTGg5HV4xBT4YYKYaWk4SDgYIWIYBybH0qLn1KS3tlZHpNS3WGfHIcHXEwLHAnF28rKW07NGuzn2pNQ2ruzWnDrGnuy2jryGjAnGgoH2j1x2RCNGPcrmIsEGGQdl/pu17YtV7FoV3muVxoRVzWqFvSmVp2SVbyw1XbkVTuvFPfo1PgmVPpt1LcnFLWkVLlp1F7W1HpsU92QE5oMUtFAUrpqUjnjUFOAEHUgz+DUj14FzvbczieMTdhATfodjXWcDXcbjXVcTS/Xi/hay7WXS3cWS3vYyvaVSrUVymnJSjXSyeKDSbNSiWfHCPMTyLFQiHkSR/lPxvVLRrPLBnUJRfUHhbaJxXVGxTZJxPNFhBdOhm/AAAAWXRSTlMABQIU/hIJ/v79/Pj29PPx4cC6s7CNfmxZWRv+/v7+/v7+/v78/Pr6+fPz8vHq6ujl5eTj4ODe2NTQzMW6ubKsnJeQkJCJiIOBgX9ubGpoW1lMREM0JR8dDgvYx1gAAAE7SURBVBjTYgADJmZJQUFJZiYGOGD2EzLV1jIT8paCibCJ86zctGPD1D4ecUaICKuPyYLMYznZOfNqzP0jwEJBOt1KB4/mHjqZ3dGsHwxW5M4Zk5l/PPdIQcGMShUPVqBlgQLlMSvyDq+P3HVidjWnkQQTA5MXV1SFYtb+jZGrl02si2J3Y2JgFMmILl68efueLVvXLSqLXirCCBgDow1HT+GS/AP7srblLS+K5bIHCjmodpXUr929d+eaVb3SsuouQCHhufPjShsbJk/rrK2KW8hiBxRyVkvnkI9tnaDQJDNFOU1DDOjRMEfe9Mjpiewz5RIzZmmKMoPcKqGbkJqSkBSfnDqpXS+ACeRpJ76W/uSUpDlpLPFtfK5soLAKFbU05Odm4eblN7YWk4KEGWOIp62FgYCVsG84SAAAL7BaooX965sAAAAASUVORK5CYII="
class="beian-icon" alt="备案图标"> class="beian-icon" alt="Filing Icon">
<span class="beian-text">{{ beianGaNum }}</span> <span class="beian-text">{{ beianGaNum }}</span>
</a> </a>
</template> </template>

View file

@ -7,13 +7,13 @@
<img src="@/assets/login/shield.png" alt="" <img src="@/assets/login/shield.png" alt=""
style="width: 19px;height: 23px; filter: brightness(0) invert(1);" /> style="width: 19px;height: 23px; filter: brightness(0) invert(1);" />
</div> </div>
用户新密码 User New Password
</div> </div>
<div style="height: 1px;background: #e8f0ff;" /> <div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;"> <div style="margin: 22px 15px;">
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> <div style="color: red;display: inline-block;">*</div>
用户新密码: User New Password:
</div> </div>
<div class="input-46" style="margin-top: 12px;"> <div class="input-46" style="margin-top: 12px;">
<el-input v-model="password" type="text" :readonly="true" style="font-weight: bold; color: #333;" /> <el-input v-model="password" type="text" :readonly="true" style="font-weight: bold; color: #333;" />
@ -22,10 +22,10 @@
<div style="display: flex;margin: 15px 15px;gap: 7px;"> <div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" <div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;"
@click="closeDialog"> @click="closeDialog">
关闭 Close
</div> </div>
<div class="dialog-btn" style="background: #5778ff;color: white;" @click="copyPassword"> <div class="dialog-btn" style="background: #5778ff;color: white;" @click="copyPassword">
复制密码 Copy Password
</div> </div>
</div> </div>
</el-dialog> </el-dialog>
@ -45,7 +45,7 @@ export default {
copyPassword() { copyPassword() {
navigator.clipboard.writeText(this.password) navigator.clipboard.writeText(this.password)
this.$message.success({ this.$message.success({
message: '密码已复制', message: 'Password copied',
showClose: true showClose: true
}) })
} }

View file

@ -46,7 +46,7 @@ const routes = [
return import('../views/retrievePassword.vue') return import('../views/retrievePassword.vue')
} }
}, },
// 设备管理页面路由 // Device management page route
{ {
path: '/device-management', path: '/device-management',
name: 'DeviceManagement', name: 'DeviceManagement',
@ -54,7 +54,7 @@ const routes = [
return import('../views/DeviceManagement.vue') return import('../views/DeviceManagement.vue')
} }
}, },
// 添加用户管理路由 // Add user management route
{ {
path: '/user-management', path: '/user-management',
name: 'UserManagement', name: 'UserManagement',
@ -77,7 +77,7 @@ const routes = [
}, },
meta: { meta: {
requiresAuth: true, requiresAuth: true,
title: '参数管理' title: 'Parameter Management'
} }
}, },
@ -89,7 +89,7 @@ const routes = [
}, },
meta: { meta: {
requiresAuth: true, requiresAuth: true,
title: '服务端管理' title: 'Server Management'
} }
}, },
{ {
@ -100,7 +100,7 @@ const routes = [
}, },
meta: { meta: {
requiresAuth: true, requiresAuth: true,
title: 'OTA管理' title: 'OTA Management'
} }
}, },
{ {
@ -123,31 +123,31 @@ const router = new VueRouter({
routes routes
}) })
// 全局处理重复导航,改为刷新页面 // Global handling of duplicate navigation, changed to refresh page
const originalPush = VueRouter.prototype.push const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) { VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => { return originalPush.call(this, location).catch(err => {
if (err.name === 'NavigationDuplicated') { if (err.name === 'NavigationDuplicated') {
// 如果是重复导航,刷新页面 // If it's duplicate navigation, refresh page
window.location.reload() window.location.reload()
} else { } else {
// 其他错误正常抛出 // Throw other errors normally
throw err throw err
} }
}) })
} }
// 需要登录才能访问的路由 // Routes that require login to access
const protectedRoutes = ['home', 'RoleConfig', 'DeviceManagement', 'UserManagement', 'ModelConfig'] const protectedRoutes = ['home', 'RoleConfig', 'DeviceManagement', 'UserManagement', 'ModelConfig']
// 路由守卫 // Route guard
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
// 检查是否是需要保护的路由 // Check if it's a protected route
if (protectedRoutes.includes(to.name)) { if (protectedRoutes.includes(to.name)) {
// 从localStorage获取token // Get token from localStorage
const token = localStorage.getItem('token') const token = localStorage.getItem('token')
if (!token) { if (!token) {
// 未登录,跳转到登录页 // Not logged in, redirect to login page
next({ name: 'login', query: { redirect: to.fullPath } }) next({ name: 'login', query: { redirect: to.fullPath } })
return return
} }

View file

@ -1,10 +1,10 @@
/** /**
* 缓存查看工具 - 用于检查CDN资源是否已被Service Worker缓存 * Cache viewing tool - used to check if CDN resources have been cached by Service Worker
*/ */
/** /**
* 获取所有Service Worker缓存的名称 * Get all Service Worker cache names
* @returns {Promise<string[]>} 缓存名称列表 * @returns {Promise<string[]>} Cache name list
*/ */
export const getCacheNames = async () => { export const getCacheNames = async () => {
if (!('caches' in window)) { if (!('caches' in window)) {
@ -14,15 +14,15 @@ export const getCacheNames = async () => {
try { try {
return await caches.keys(); return await caches.keys();
} catch (error) { } catch (error) {
console.error('获取缓存名称失败:', error); console.error('Get cache names failed:', error);
return []; return [];
} }
}; };
/** /**
* 获取指定缓存中的所有URL * Get all URLs in specified cache
* @param {string} cacheName 缓存名称 * @param {string} cacheName Cache name
* @returns {Promise<string[]>} 缓存的URL列表 * @returns {Promise<string[]>} Cached URL list
*/ */
export const getCacheUrls = async (cacheName) => { export const getCacheUrls = async (cacheName) => {
if (!('caches' in window)) { if (!('caches' in window)) {
@ -34,15 +34,15 @@ export const getCacheUrls = async (cacheName) => {
const requests = await cache.keys(); const requests = await cache.keys();
return requests.map(request => request.url); return requests.map(request => request.url);
} catch (error) { } catch (error) {
console.error(`获取缓存 ${cacheName} 的URL失败:`, error); console.error(`Get cache ${cacheName} URLs failed:`, error);
return []; return [];
} }
}; };
/** /**
* 检查特定URL是否已被缓存 * Check if specific URL has been cached
* @param {string} url 要检查的URL * @param {string} url URL to check
* @returns {Promise<boolean>} 是否已缓存 * @returns {Promise<boolean>} Whether cached
*/ */
export const isUrlCached = async (url) => { export const isUrlCached = async (url) => {
if (!('caches' in window)) { if (!('caches' in window)) {
@ -60,17 +60,17 @@ export const isUrlCached = async (url) => {
} }
return false; return false;
} catch (error) { } catch (error) {
console.error(`检查URL ${url} 是否缓存失败:`, error); console.error(`Check URL ${url} cache status failed:`, error);
return false; return false;
} }
}; };
/** /**
* 获取当前页面所有CDN资源的缓存状态 * Get cache status of all CDN resources on current page
* @returns {Promise<Object>} 缓存状态对象 * @returns {Promise<Object>} Cache status object
*/ */
export const checkCdnCacheStatus = async () => { export const checkCdnCacheStatus = async () => {
// 从CDN缓存中查找资源 // Find resources from CDN cache
const cdnCaches = ['cdn-stylesheets', 'cdn-scripts']; const cdnCaches = ['cdn-stylesheets', 'cdn-scripts'];
const results = { const results = {
css: [], css: [],
@ -83,7 +83,7 @@ export const checkCdnCacheStatus = async () => {
try { try {
const urls = await getCacheUrls(cacheName); const urls = await getCacheUrls(cacheName);
// 区分CSS和JS资源 // Distinguish CSS and JS resources
for (const url of urls) { for (const url of urls) {
if (url.endsWith('.css')) { if (url.endsWith('.css')) {
results.css.push({ url, cached: true }); results.css.push({ url, cached: true });
@ -93,7 +93,7 @@ export const checkCdnCacheStatus = async () => {
results.totalCached++; results.totalCached++;
} }
} catch (error) { } catch (error) {
console.error(`获取 ${cacheName} 缓存信息失败:`, error); console.error(`Get ${cacheName} cache information failed:`, error);
} }
} }
@ -101,8 +101,8 @@ export const checkCdnCacheStatus = async () => {
}; };
/** /**
* 清除所有Service Worker缓存 * Clear all Service Worker caches
* @returns {Promise<boolean>} 是否成功清除 * @returns {Promise<boolean>} Whether successfully cleared
*/ */
export const clearAllCaches = async () => { export const clearAllCaches = async () => {
if (!('caches' in window)) { if (!('caches' in window)) {
@ -116,23 +116,23 @@ export const clearAllCaches = async () => {
} }
return true; return true;
} catch (error) { } catch (error) {
console.error('清除所有缓存失败:', error); console.error('Clear all caches failed:', error);
return false; return false;
} }
}; };
/** /**
* 将缓存状态输出到控制台 * Output cache status to console
*/ */
export const logCacheStatus = async () => { export const logCacheStatus = async () => {
console.group('Service Worker 缓存状态'); console.group('Service Worker cache status');
const cacheNames = await getCacheNames(); const cacheNames = await getCacheNames();
console.log('已发现的缓存:', cacheNames); console.log('Discovered caches:', cacheNames);
for (const cacheName of cacheNames) { for (const cacheName of cacheNames) {
const urls = await getCacheUrls(cacheName); const urls = await getCacheUrls(cacheName);
console.group(`缓存: ${cacheName} (${urls.length} 项)`); console.group(`Cache: ${cacheName} (${urls.length} items)`);
urls.forEach(url => console.log(url)); urls.forEach(url => console.log(url));
console.groupEnd(); console.groupEnd();
} }

6
main/manager-web/src/utils/constant.js Executable file → Normal file
View file

@ -1,6 +1,6 @@
const HAVE_NO_RESULT = '暂无' const HAVE_NO_RESULT = 'No data'
export default { export default {
HAVE_NO_RESULT, // 项目的配置信息 HAVE_NO_RESULT, // Project configuration information
PAGE: { PAGE: {
LOGIN: '/login', LOGIN: '/login',
}, },
@ -15,7 +15,7 @@ export default {
FONT_SIZE: { FONT_SIZE: {
'big': 'big', 'big': 'big',
'normal': 'normal', 'normal': 'normal',
}, // 获取map中的某key }, // Get certain key from map
get(map, key) { get(map, key) {
return map[key] || HAVE_NO_RESULT return map[key] || HAVE_NO_RESULT
} }

0
main/manager-web/src/utils/date.js Executable file → Normal file
View file

0
main/manager-web/src/utils/index.js Executable file → Normal file
View file

View file

@ -3,11 +3,11 @@
<HeaderBar/> <HeaderBar/>
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">设备管理</h2> <h2 class="page-title">Device Management</h2>
<div class="right-operations"> <div class="right-operations">
<el-input placeholder="请输入设备型号或Mac地址查询" v-model="searchKeyword" class="search-input" <el-input placeholder="Enter device model or MAC address to search" v-model="searchKeyword" class="search-input"
@keyup.enter.native="handleSearch" clearable/> @keyup.enter.native="handleSearch" clearable/>
<el-button class="btn-search" @click="handleSearch">搜索</el-button> <el-button class="btn-search" @click="handleSearch">Search</el-button>
</div> </div>
</div> </div>
@ -17,23 +17,23 @@
<el-card class="device-card" shadow="never"> <el-card class="device-card" shadow="never">
<el-table ref="deviceTable" :data="paginatedDeviceList" class="transparent-table" <el-table ref="deviceTable" :data="paginatedDeviceList" class="transparent-table"
:header-cell-class-name="headerCellClassName" v-loading="loading" :header-cell-class-name="headerCellClassName" v-loading="loading"
element-loading-text="拼命加载中" element-loading-text="Loading..."
element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)"> element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="Select" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="设备型号" prop="model" align="center"> <el-table-column label="Device Model" prop="model" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ getFirmwareTypeName(scope.row.model) }} {{ getFirmwareTypeName(scope.row.model) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="固件版本" prop="firmwareVersion" align="center"></el-table-column> <el-table-column label="Firmware Version" prop="firmwareVersion" align="center"></el-table-column>
<el-table-column label="Mac地址" prop="macAddress" align="center"></el-table-column> <el-table-column label="MAC Address" prop="macAddress" align="center"></el-table-column>
<el-table-column label="绑定时间" prop="bindTime" align="center"></el-table-column> <el-table-column label="Bind Time" prop="bindTime" align="center"></el-table-column>
<el-table-column label="最近对话" prop="lastConversation" align="center"></el-table-column> <el-table-column label="Last Conversation" prop="lastConversation" align="center"></el-table-column>
<el-table-column label="备注" align="center"> <el-table-column label="Remark" align="center">
<template #default="{ row }"> <template #default="{ row }">
<el-input <el-input
v-show="row.isEdit" v-show="row.isEdit"
@ -56,16 +56,16 @@
</span> </span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="OTA升级" align="center"> <el-table-column label="OTA Upgrade" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-switch v-model="scope.row.otaSwitch" size="mini" active-color="#13ce66" inactive-color="#ff4949" <el-switch v-model="scope.row.otaSwitch" size="mini" active-color="#13ce66" inactive-color="#ff4949"
@change="handleOtaSwitchChange(scope.row)"></el-switch> @change="handleOtaSwitchChange(scope.row)"></el-switch>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" align="center"> <el-table-column label="Actions" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="mini" type="text" @click="handleUnbind(scope.row.device_id)"> <el-button size="mini" type="text" @click="handleUnbind(scope.row.device_id)">
解绑 Unbind
</el-button> </el-button>
</template> </template>
</el-table-column> </el-table-column>
@ -74,29 +74,29 @@
<div class="table_bottom"> <div class="table_bottom">
<div class="ctrl_btn"> <div class="ctrl_btn">
<el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll"> <el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll">
{{ isAllSelected ? '取消全选' : '全选' }} {{ isAllSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button type="success" size="mini" class="add-device-btn" @click="handleAddDevice"> <el-button type="success" size="mini" class="add-device-btn" @click="handleAddDevice">
验证码绑定 Bind with Code
</el-button> </el-button>
<el-button type="success" size="mini" class="add-device-btn" @click="handleManualAddDevice"> <el-button type="success" size="mini" class="add-device-btn" @click="handleManualAddDevice">
手动添加 Manual Add
</el-button> </el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSelected">解绑</el-button> <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSelected">Unbind</el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <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 v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`" :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">首页</button> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">First</button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">上一页</button> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">Previous</button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> </button>
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">下一页</button> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">Next</button>
<span class="total-text">共{{ deviceList.length }}条记录</span> <span class="total-text">Total {{ deviceList.length }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -191,8 +191,8 @@ export default {
const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE') const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE')
this.firmwareTypes = res.data this.firmwareTypes = res.data
} catch (error) { } catch (error) {
console.error('获取固件类型失败:', error) console.error('Failed to get firmware types:', error)
this.$message.error(error.message || '获取固件类型失败') this.$message.error(error.message || 'Failed to get firmware types')
} }
}, },
handlePageSizeChange(val) { handlePageSizeChange(val) {
@ -216,15 +216,15 @@ export default {
this.selectedDevices = this.paginatedDeviceList.filter(device => device.selected); this.selectedDevices = this.paginatedDeviceList.filter(device => device.selected);
if (this.selectedDevices.length === 0) { if (this.selectedDevices.length === 0) {
this.$message.warning({ this.$message.warning({
message: '请至少选择一条记录', message: 'Please select at least one record',
showClose: true showClose: true
}); });
return; return;
} }
this.$confirm(`确认要解绑选中的 ${this.selectedDevices.length} 台设备吗?`, '警告', { this.$confirm(`Are you sure you want to unbind ${this.selectedDevices.length} selected devices?`, 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
const deviceIds = this.selectedDevices.map(device => device.device_id); const deviceIds = this.selectedDevices.map(device => device.device_id);
@ -238,7 +238,7 @@ export default {
if (data.code === 0) { if (data.code === 0) {
resolve(); resolve();
} else { } else {
reject(data.msg || '解绑失败'); reject(data.msg || 'Failed to unbind');
} }
}); });
}); });
@ -246,7 +246,7 @@ export default {
Promise.all(promises) Promise.all(promises)
.then(() => { .then(() => {
this.$message.success({ this.$message.success({
message: `成功解绑 ${deviceIds.length} 台设备`, message: `Successfully unbound ${deviceIds.length} devices`,
showClose: true showClose: true
}); });
this.fetchBindDevices(this.currentAgentId); this.fetchBindDevices(this.currentAgentId);
@ -255,7 +255,7 @@ export default {
}) })
.catch(error => { .catch(error => {
this.$message.error({ this.$message.error({
message: error || '批量解绑过程中出现错误', message: error || 'Error occurred during batch unbinding',
showClose: true showClose: true
}); });
}); });
@ -271,7 +271,7 @@ export default {
const text = (row.remark || '').trim(); const text = (row.remark || '').trim();
if (text.length > 64) { if (text.length > 64) {
this.$message.warning('备注不能超过 64 字符'); this.$message.warning('Remark cannot exceed 64 characters');
return; return;
} }
if (text === row._originalRemark) { if (text === row._originalRemark) {
@ -282,42 +282,42 @@ export default {
this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => { this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => {
if (ok) { if (ok) {
row._originalRemark = text; row._originalRemark = text;
this.$message.success('备注已保存'); this.$message.success('Remark saved successfully');
} else { } else {
row.remark = row._originalRemark; row.remark = row._originalRemark;
this.$message.error(resp.msg || '备注保存失败'); this.$message.error(resp.msg || 'Failed to save remark');
} }
row._submitting = false; row._submitting = false;
}); });
}, },
// 备注输入框:失焦时提交 // Remark input: submit on blur
onRemarkBlur(row) { onRemarkBlur(row) {
row.isEdit = false; row.isEdit = false;
setTimeout(() => { setTimeout(() => {
this.submitRemark(row); this.submitRemark(row);
}, 100); // 延迟 100ms,避开 enter+blur 同时触发的窗口 }, 100); // Delay 100ms to avoid simultaneous enter+blur trigger
}, },
// 备注输入框:按回车时提交 // Remark input: submit on Enter key
onRemarkEnter(row) { onRemarkEnter(row) {
row.isEdit = false; row.isEdit = false;
this.submitRemark(row); this.submitRemark(row);
}, },
handleUnbind(device_id) { handleUnbind(device_id) {
this.$confirm('确认要解绑该设备吗?', '警告', { this.$confirm('Are you sure you want to unbind this device?', 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
Api.device.unbindDevice(device_id, ({data}) => { Api.device.unbindDevice(device_id, ({data}) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: '设备解绑成功', message: 'Device unbound successfully',
showClose: true showClose: true
}); });
this.fetchBindDevices(this.$route.query.agentId); this.fetchBindDevices(this.$route.query.agentId);
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '设备解绑失败', message: data.msg || 'Failed to unbind device',
showClose: true showClose: true
}); });
} }
@ -362,7 +362,7 @@ export default {
this.activeSearchKeyword = ""; this.activeSearchKeyword = "";
this.searchKeyword = ""; this.searchKeyword = "";
} else { } else {
this.$message.error(data.msg || '获取设备列表失败'); this.$message.error(data.msg || 'Failed to get device list');
} }
}); });
}, },
@ -384,11 +384,11 @@ export default {
handleOtaSwitchChange(row) { handleOtaSwitchChange(row) {
this.updateDeviceInfo(row.device_id, {autoUpdate: row.otaSwitch ? 1 : 0}, (result, {msg}) => { this.updateDeviceInfo(row.device_id, {autoUpdate: row.otaSwitch ? 1 : 0}, (result, {msg}) => {
if (result) { if (result) {
this.$message.success(row.otaSwitch ? '已设置成自动升级' : '已关闭自动升级'); this.$message.success(row.otaSwitch ? 'Auto-upgrade enabled' : 'Auto-upgrade disabled');
return; return;
} }
row.otaSwitch = !row.otaSwitch row.otaSwitch = !row.otaSwitch
this.$message.error(msg || '操作失败') this.$message.error(msg || 'Operation failed')
}) })
}, },
} }

View file

@ -3,70 +3,70 @@
<HeaderBar /> <HeaderBar />
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">字典管理</h2> <h2 class="page-title">Dictionary Management</h2>
<div class="action-group"> <div class="action-group">
<div class="search-group"> <div class="search-group">
<el-input placeholder="请输入字典值标签查询" v-model="search" class="search-input" clearable <el-input placeholder="Enter dictionary label to search" v-model="search" class="search-input" clearable
@keyup.enter.native="handleSearch" style="width: 240px" /> @keyup.enter.native="handleSearch" style="width: 240px" />
<el-button class="btn-search" @click="handleSearch"> <el-button class="btn-search" @click="handleSearch">
搜索 Search
</el-button> </el-button>
</div> </div>
</div> </div>
</div> </div>
<!-- 主体内容 --> <!-- Main content -->
<div class="main-wrapper"> <div class="main-wrapper">
<div class="content-panel"> <div class="content-panel">
<!-- 左侧字典类型列表 --> <!-- Left side dictionary type list -->
<div class="dict-type-panel"> <div class="dict-type-panel">
<div class="dict-type-header"> <div class="dict-type-header">
<el-button type="success" size="mini" @click="showAddDictTypeDialog">新增字典类型</el-button> <el-button type="success" size="mini" @click="showAddDictTypeDialog">Add Dictionary Type</el-button>
<el-button type="danger" size="mini" @click="batchDeleteDictType" <el-button type="danger" size="mini" @click="batchDeleteDictType"
:disabled="selectedDictTypes.length === 0"> :disabled="selectedDictTypes.length === 0">
批量删除字典类型 Batch Delete Types
</el-button> </el-button>
</div> </div>
<el-table ref="dictTypeTable" :data="dictTypeList" style="width: 100%" v-loading="dictTypeLoading" <el-table ref="dictTypeTable" :data="dictTypeList" style="width: 100%" v-loading="dictTypeLoading"
element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)" @row-click="handleDictTypeRowClick" element-loading-background="rgba(255, 255, 255, 0.7)" @row-click="handleDictTypeRowClick"
@selection-change="handleDictTypeSelectionChange" :row-class-name="tableRowClassName" @selection-change="handleDictTypeSelectionChange" :row-class-name="tableRowClassName"
class="dict-type-table"> class="dict-type-table">
<el-table-column type="selection" width="55" align="center"></el-table-column> <el-table-column type="selection" width="55" align="center"></el-table-column>
<el-table-column label="字典类型名称" prop="dictName" align="center"></el-table-column> <el-table-column label="Dictionary Type Name" prop="dictName" align="center"></el-table-column>
<el-table-column label="操作" width="100" align="center"> <el-table-column label="Actions" width="100" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button type="text" size="mini" @click.stop="editDictType(scope.row)">编辑</el-button> <el-button type="text" size="mini" @click.stop="editDictType(scope.row)">Edit</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
</div> </div>
<!-- 右侧字典数据列表 --> <!-- Right side dictionary data list -->
<div class="content-area"> <div class="content-area">
<el-card class="dict-data-card" shadow="never"> <el-card class="dict-data-card" shadow="never">
<el-table ref="dictDataTable" :data="dictDataList" style="width: 100%" <el-table ref="dictDataTable" :data="dictDataList" style="width: 100%"
v-loading="dictDataLoading" element-loading-text="拼命加载中" v-loading="dictDataLoading" element-loading-text="Loading..."
element-loading-spinner="el-icon-loading" element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)" class="data-table" element-loading-background="rgba(255, 255, 255, 0.7)" class="data-table"
header-row-class-name="table-header"> header-row-class-name="table-header">
<el-table-column label="选择" align="center" width="55"> <el-table-column label="Select" align="center" width="55">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="字典标签" prop="dictLabel" align="center"></el-table-column> <el-table-column label="Dictionary Label" prop="dictLabel" align="center"></el-table-column>
<el-table-column label="字典值" prop="dictValue" align="center"></el-table-column> <el-table-column label="Dictionary Value" prop="dictValue" align="center"></el-table-column>
<el-table-column label="排序" prop="sort" align="center"></el-table-column> <el-table-column label="Sort Order" prop="sort" align="center"></el-table-column>
<el-table-column label="操作" align="center" width="180px"> <el-table-column label="Actions" align="center" width="180px">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button type="text" size="mini" @click="editDictData(scope.row)" <el-button type="text" size="mini" @click="editDictData(scope.row)"
class="edit-btn"> class="edit-btn">
修改 Edit
</el-button> </el-button>
<el-button type="text" size="mini" @click="deleteDictData(scope.row)" <el-button type="text" size="mini" @click="deleteDictData(scope.row)"
class="delete-btn"> class="delete-btn">
删除 Delete
</el-button> </el-button>
</template> </template>
</el-table-column> </el-table-column>
@ -74,36 +74,36 @@
<div class="table-footer"> <div class="table-footer">
<div class="batch-actions"> <div class="batch-actions">
<el-button size="mini" type="primary" @click="selectAllDictData"> <el-button size="mini" type="primary" @click="selectAllDictData">
{{ isAllDictDataSelected ? '取消全选' : '全选' }} {{ isAllDictDataSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button type="success" size="mini" @click="showAddDictDataDialog" class="add-btn"> <el-button type="success" size="mini" @click="showAddDictDataDialog" class="add-btn">
新增字典数据 Add Dictionary Data
</el-button> </el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" @click="batchDeleteDictData"> <el-button size="mini" type="danger" icon="el-icon-delete" @click="batchDeleteDictData">
批量删除字典数据 Batch Delete Data
</el-button> </el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select">
<el-option v-for="item in pageSizeOptions" :key="item" :label="`${item}条/页`" <el-option v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`"
:value="item"> :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">
首页 First
</button> </button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">
上一页 Previous
</button> </button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> </button>
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext"> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">
下一页 Next
</button> </button>
<span class="total-text">共{{ total }}条记录</span> <span class="total-text">Total {{ total }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -111,11 +111,11 @@
</div> </div>
</div> </div>
<!-- 使用字典类型编辑弹框组件 --> <!-- Dictionary type edit dialog component -->
<DictTypeDialog :visible.sync="dictTypeDialogVisible" :title="dictTypeDialogTitle" :dictTypeData="dictTypeForm" <DictTypeDialog :visible.sync="dictTypeDialogVisible" :title="dictTypeDialogTitle" :dictTypeData="dictTypeForm"
@save="saveDictType" /> @save="saveDictType" />
<!-- 使用字典数据编辑弹框组件 --> <!-- Dictionary data edit dialog component -->
<DictDataDialog :visible.sync="dictDataDialogVisible" :title="dictDataDialogTitle" :dictData="dictDataForm" <DictDataDialog :visible.sync="dictDataDialogVisible" :title="dictDataDialogTitle" :dictData="dictDataForm"
:dictTypeId="selectedDictType?.id" @save="saveDictData" /> :dictTypeId="selectedDictType?.id" @save="saveDictData" />
<el-footer style="flex-shrink:unset;"> <el-footer style="flex-shrink:unset;">
@ -140,25 +140,25 @@ export default {
}, },
data() { data() {
return { return {
// 字典类型相关 // Dictionary type related
dictTypeList: [], dictTypeList: [],
dictTypeLoading: false, dictTypeLoading: false,
selectedDictType: null, selectedDictType: null,
selectedDictTypes: [], // 恢复多选数组 selectedDictTypes: [], // 恢复多选数组
dictTypeDialogVisible: false, dictTypeDialogVisible: false,
dictTypeDialogTitle: '新增字典类型', dictTypeDialogTitle: 'Add Dictionary Type',
dictTypeForm: { dictTypeForm: {
id: null, id: null,
dictName: '', dictName: '',
dictType: '' dictType: ''
}, },
// 字典数据相关 // Dictionary data related
dictDataList: [], dictDataList: [],
dictDataLoading: false, dictDataLoading: false,
isAllDictDataSelected: false, isAllDictDataSelected: false,
dictDataDialogVisible: false, dictDataDialogVisible: false,
dictDataDialogTitle: '新增字典数据', dictDataDialogTitle: 'Add Dictionary Data',
dictDataForm: { dictDataForm: {
id: null, id: null,
dictTypeId: null, dictTypeId: null,
@ -178,7 +178,7 @@ export default {
this.loadDictTypeList() this.loadDictTypeList()
}, },
methods: { methods: {
// 字典类型相关方法 // Dictionary type related methods
loadDictTypeList() { loadDictTypeList() {
this.dictTypeLoading = true this.dictTypeLoading = true
dictApi.getDictTypeList({ dictApi.getDictTypeList({
@ -211,7 +211,7 @@ export default {
return row === this.selectedDictType ? 'current-row' : '' return row === this.selectedDictType ? 'current-row' : ''
}, },
showAddDictTypeDialog() { showAddDictTypeDialog() {
this.dictTypeDialogTitle = '新增字典类型' this.dictTypeDialogTitle = 'Add Dictionary Type'
this.dictTypeForm = { this.dictTypeForm = {
id: null, id: null,
dictName: '', dictName: '',
@ -220,7 +220,7 @@ export default {
this.dictTypeDialogVisible = true this.dictTypeDialogVisible = true
}, },
editDictType(row) { editDictType(row) {
this.dictTypeDialogTitle = '编辑字典类型' this.dictTypeDialogTitle = 'Edit Dictionary Type'
this.dictTypeForm = { ...row } this.dictTypeForm = { ...row }
this.dictTypeDialogVisible = true this.dictTypeDialogVisible = true
}, },
@ -228,7 +228,7 @@ export default {
const api = formData.id ? dictApi.updateDictType : dictApi.addDictType const api = formData.id ? dictApi.updateDictType : dictApi.addDictType
api(formData, ({ data }) => { api(formData, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('保存成功') this.$message.success('Saved successfully')
this.dictTypeDialogVisible = false this.dictTypeDialogVisible = false
this.loadDictTypeList() this.loadDictTypeList()
} }
@ -236,26 +236,26 @@ export default {
}, },
batchDeleteDictType() { batchDeleteDictType() {
if (this.selectedDictTypes.length === 0) { if (this.selectedDictTypes.length === 0) {
this.$message.warning('请选择要删除的字典类型') this.$message.warning('Please select dictionary types to delete')
return return
} }
this.$confirm('确定要删除选中的字典类型吗?', '提示', { this.$confirm('Are you sure you want to delete the selected dictionary types?', 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
const ids = this.selectedDictTypes.map(item => item.id) const ids = this.selectedDictTypes.map(item => item.id)
dictApi.deleteDictType(ids, ({ data }) => { dictApi.deleteDictType(ids, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('删除成功') this.$message.success('Deleted successfully')
this.loadDictTypeList() this.loadDictTypeList()
} }
}) })
}) })
}, },
// 字典数据相关方法 // Dictionary data related methods
loadDictDataList(dictTypeId) { loadDictDataList(dictTypeId) {
if (!dictTypeId) return if (!dictTypeId) return
this.dictDataLoading = true this.dictDataLoading = true
@ -273,7 +273,7 @@ export default {
})) }))
this.total = data.data.total this.total = data.data.total
} else { } else {
this.$message.error(data.msg || '获取字典数据失败') this.$message.error(data.msg || 'Failed to get dictionary data')
} }
this.dictDataLoading = false this.dictDataLoading = false
}) })
@ -286,10 +286,10 @@ export default {
}, },
showAddDictDataDialog() { showAddDictDataDialog() {
if (!this.selectedDictType) { if (!this.selectedDictType) {
this.$message.warning('请先选择字典类型') this.$message.warning('Please select a dictionary type first')
return return
} }
this.dictDataDialogTitle = '新增字典数据' this.dictDataDialogTitle = 'Add Dictionary Data'
this.dictDataForm = { this.dictDataForm = {
id: null, id: null,
dictTypeId: this.selectedDictType.id, dictTypeId: this.selectedDictType.id,
@ -300,7 +300,7 @@ export default {
this.dictDataDialogVisible = true this.dictDataDialogVisible = true
}, },
editDictData(row) { editDictData(row) {
this.dictDataDialogTitle = '编辑字典数据' this.dictDataDialogTitle = 'Edit Dictionary Data'
this.dictDataForm = { ...row } this.dictDataForm = { ...row }
this.dictDataDialogVisible = true this.dictDataDialogVisible = true
}, },
@ -308,21 +308,21 @@ export default {
const api = formData.id ? dictApi.updateDictData : dictApi.addDictData const api = formData.id ? dictApi.updateDictData : dictApi.addDictData
api(formData, ({ data }) => { api(formData, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('保存成功') this.$message.success('Saved successfully')
this.dictDataDialogVisible = false this.dictDataDialogVisible = false
this.loadDictDataList(formData.dictTypeId) this.loadDictDataList(formData.dictTypeId)
} }
}) })
}, },
deleteDictData(row) { deleteDictData(row) {
this.$confirm('确定要删除该字典数据吗?', '提示', { this.$confirm('Are you sure you want to delete this dictionary data?', 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
dictApi.deleteDictData([row.id], ({ data }) => { dictApi.deleteDictData([row.id], ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('删除成功') this.$message.success('Deleted successfully')
this.loadDictDataList(row.dictTypeId) this.loadDictDataList(row.dictTypeId)
} }
}) })
@ -331,19 +331,19 @@ export default {
batchDeleteDictData() { batchDeleteDictData() {
const selectedRows = this.dictDataList.filter(row => row.selected) const selectedRows = this.dictDataList.filter(row => row.selected)
if (selectedRows.length === 0) { if (selectedRows.length === 0) {
this.$message.warning('请选择要删除的字典数据') this.$message.warning('Please select dictionary data to delete')
return return
} }
this.$confirm(`确定要删除选中的${selectedRows.length}个字典数据吗?`, '提示', { this.$confirm(`Are you sure you want to delete ${selectedRows.length} selected dictionary data items?`, 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
const ids = selectedRows.map(item => item.id) const ids = selectedRows.map(item => item.id)
dictApi.deleteDictData(ids, ({ data }) => { dictApi.deleteDictData(ids, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('删除成功') this.$message.success('Deleted successfully')
this.loadDictDataList(this.selectedDictType.id) this.loadDictDataList(this.selectedDictType.id)
} }
}) })
@ -351,13 +351,13 @@ export default {
}, },
handleSearch() { handleSearch() {
if (!this.selectedDictType) { if (!this.selectedDictType) {
this.$message.warning('请先选择字典类型') this.$message.warning('Please select a dictionary type first')
return return
} }
this.currentPage = 1 this.currentPage = 1
this.loadDictDataList(this.selectedDictType.id) this.loadDictDataList(this.selectedDictType.id)
}, },
// 添加分页相关方法 // Add pagination related methods
handlePageSizeChange(val) { handlePageSizeChange(val) {
this.pageSize = val; this.pageSize = val;
this.currentPage = 1; this.currentPage = 1;

View file

@ -6,86 +6,86 @@
<h2 class="page-title">{{ modelTypeText }}</h2> <h2 class="page-title">{{ modelTypeText }}</h2>
<div class="action-group"> <div class="action-group">
<div class="search-group"> <div class="search-group">
<el-input placeholder="请输入模型名称查询" v-model="search" class="search-input" clearable <el-input placeholder="Enter model name to search" v-model="search" class="search-input" clearable
@keyup.enter.native="handleSearch" style="width: 240px" /> @keyup.enter.native="handleSearch" style="width: 240px" />
<el-button class="btn-search" @click="handleSearch"> <el-button class="btn-search" @click="handleSearch">
搜索 Search
</el-button> </el-button>
</div> </div>
</div> </div>
</div> </div>
<!-- 主体内容 --> <!-- Main content -->
<div class="main-wrapper"> <div class="main-wrapper">
<div class="content-panel"> <div class="content-panel">
<!-- 左侧导航 --> <!-- Left navigation -->
<el-menu :default-active="activeTab" class="nav-panel" @select="handleMenuSelect" <el-menu :default-active="activeTab" class="nav-panel" @select="handleMenuSelect"
style="background-size: cover; background-position: center;"> style="background-size: cover; background-position: center;">
<el-menu-item index="vad"> <el-menu-item index="vad">
<span class="menu-text">语言活动检测</span> <span class="menu-text">Voice Activity Detection</span>
</el-menu-item> </el-menu-item>
<el-menu-item index="asr"> <el-menu-item index="asr">
<span class="menu-text">语音识别</span> <span class="menu-text">Speech Recognition</span>
</el-menu-item> </el-menu-item>
<el-menu-item index="llm"> <el-menu-item index="llm">
<span class="menu-text">大语言模型</span> <span class="menu-text">Large Language Model</span>
</el-menu-item> </el-menu-item>
<el-menu-item index="vllm"> <el-menu-item index="vllm">
<span class="menu-text">视觉大模型</span> <span class="menu-text">Vision Language Model</span>
</el-menu-item> </el-menu-item>
<el-menu-item index="intent"> <el-menu-item index="intent">
<span class="menu-text">意图识别</span> <span class="menu-text">Intent Recognition</span>
</el-menu-item> </el-menu-item>
<el-menu-item index="tts"> <el-menu-item index="tts">
<span class="menu-text">语音合成</span> <span class="menu-text">Text-to-Speech</span>
</el-menu-item> </el-menu-item>
<el-menu-item index="memory"> <el-menu-item index="memory">
<span class="menu-text">记忆</span> <span class="menu-text">Memory</span>
</el-menu-item> </el-menu-item>
</el-menu> </el-menu>
<!-- 右侧内容 --> <!-- Right content -->
<div class="content-area"> <div class="content-area">
<el-card class="model-card" shadow="never"> <el-card class="model-card" shadow="never">
<el-table ref="modelTable" style="width: 100%" v-loading="loading" element-loading-text="拼命加载中" <el-table ref="modelTable" style="width: 100%" v-loading="loading" element-loading-text="Loading..."
element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)"
:header-cell-style="{ background: 'transparent' }" :data="modelList" class="data-table" :header-cell-style="{ background: 'transparent' }" :data="modelList" class="data-table"
header-row-class-name="table-header" :header-cell-class-name="headerCellClassName" header-row-class-name="table-header" :header-cell-class-name="headerCellClassName"
@selection-change="handleSelectionChange"> @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center"></el-table-column> <el-table-column type="selection" width="55" align="center"></el-table-column>
<el-table-column label="模型ID" prop="id" align="center"></el-table-column> <el-table-column label="Model ID" prop="id" align="center"></el-table-column>
<el-table-column label="模型名称" prop="modelName" align="center"></el-table-column> <el-table-column label="Model Name" prop="modelName" align="center"></el-table-column>
<el-table-column label="提供商" align="center"> <el-table-column label="Provider" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ scope.row.configJson.type || '未知' }} {{ scope.row.configJson.type || 'Unknown' }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="是否启用" align="center"> <el-table-column label="Enabled" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-switch v-model="scope.row.isEnabled" class="custom-switch" :active-value="1" :inactive-value="0" <el-switch v-model="scope.row.isEnabled" class="custom-switch" :active-value="1" :inactive-value="0"
@change="handleStatusChange(scope.row)" /> @change="handleStatusChange(scope.row)" />
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="是否默认" align="center"> <el-table-column label="Default" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-switch v-model="scope.row.isDefault" class="custom-switch" :active-value="1" :inactive-value="0" <el-switch v-model="scope.row.isDefault" class="custom-switch" :active-value="1" :inactive-value="0"
@change="handleDefaultChange(scope.row)" /> @change="handleDefaultChange(scope.row)" />
</template> </template>
</el-table-column> </el-table-column>
<el-table-column v-if="activeTab === 'tts'" label="音色管理" align="center"> <el-table-column v-if="activeTab === 'tts'" label="Voice Management" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button type="text" size="mini" @click="openTtsDialog(scope.row)" class="voice-management-btn"> <el-button type="text" size="mini" @click="openTtsDialog(scope.row)" class="voice-management-btn">
音色管理 Voice Management
</el-button> </el-button>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" align="center" width="150px"> <el-table-column label="Actions" align="center" width="150px">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button type="text" size="mini" @click="editModel(scope.row)" class="edit-btn"> <el-button type="text" size="mini" @click="editModel(scope.row)" class="edit-btn">
修改 Edit
</el-button> </el-button>
<el-button type="text" size="mini" @click="deleteModel(scope.row)" class="delete-btn"> <el-button type="text" size="mini" @click="deleteModel(scope.row)" class="delete-btn">
删除 Delete
</el-button> </el-button>
</template> </template>
</el-table-column> </el-table-column>
@ -94,32 +94,32 @@
<div class="batch-actions"> <div class="batch-actions">
<el-button size="mini" type="primary" @click="selectAll"> <el-button size="mini" type="primary" @click="selectAll">
{{ isAllSelected ? {{ isAllSelected ?
'取消全选' : '全选' }} 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button type="success" size="mini" @click="addModel" class="add-btn"> <el-button type="success" size="mini" @click="addModel" class="add-btn">
新增 Add
</el-button> </el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" @click="batchDelete"> <el-button size="mini" type="danger" icon="el-icon-delete" @click="batchDelete">
删除 Delete
</el-button> </el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <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 v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`" :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">首页</button> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">First</button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">上一页</button> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">Previous</button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> </button>
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">下一页</button> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">Next</button>
<span class="total-text">共{{ total }}条记录</span> <span class="total-text">Total {{ total }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -174,15 +174,15 @@ export default {
computed: { computed: {
modelTypeText() { modelTypeText() {
const map = { const map = {
vad: '语言活动检测模型(VAD)', vad: 'Voice Activity Detection Model (VAD)',
asr: '语音识别模型(ASR)', asr: 'Speech Recognition Model (ASR)',
llm: '大语言模型(LLM)', llm: 'Large Language Model (LLM)',
vllm: '视觉大模型(VLLM)', vllm: 'Vision Language Model (VLLM)',
intent: '意图识别模型(Intent)', intent: 'Intent Recognition Model (Intent)',
tts: '语音合成模型(TTS)', tts: 'Text-to-Speech Model (TTS)',
memory: '记忆模型(Memory)' memory: 'Memory Model (Memory)'
} }
return map[this.activeTab] || '模型配置' return map[this.activeTab] || 'Model Configuration'
}, },
pageCount() { pageCount() {
return Math.ceil(this.total / this.pageSize); return Math.ceil(this.total / this.pageSize);
@ -223,24 +223,24 @@ export default {
}, },
handleMenuSelect(index) { handleMenuSelect(index) {
this.activeTab = index; this.activeTab = index;
this.currentPage = 1; // 重置到第一页 this.currentPage = 1; // Reset to first page
this.pageSize = 10; // 可选:重置每页条数 this.pageSize = 10; // Optional: reset items per page
this.loadData(); this.loadData();
}, },
handleSearch() { handleSearch() {
this.currentPage = 1; this.currentPage = 1;
this.loadData(); this.loadData();
}, },
// 批量删除 // Batch delete
batchDelete() { batchDelete() {
if (this.selectedModels.length === 0) { if (this.selectedModels.length === 0) {
this.$message.warning('请先选择要删除的模型') this.$message.warning('Please select models to delete first')
return return
} }
this.$confirm('确定要删除选中的模型吗?', '提示', { this.$confirm('Are you sure you want to delete the selected models?', 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
const deletePromises = this.selectedModels.map(model => const deletePromises = this.selectedModels.map(model =>
@ -255,19 +255,19 @@ export default {
Promise.all(deletePromises).then(results => { Promise.all(deletePromises).then(results => {
if (results.every(Boolean)) { if (results.every(Boolean)) {
this.$message.success({ this.$message.success({
message: '批量删除成功', message: 'Batch deletion successful',
showClose: true showClose: true
}) })
this.loadData() this.loadData()
} else { } else {
this.$message.error({ this.$message.error({
message: '部分删除失败', message: 'Some deletions failed',
showClose: true showClose: true
}) })
} }
}) })
}).catch(() => { }).catch(() => {
this.$message.info('已取消删除') this.$message.info('Deletion cancelled')
}) })
}, },
addModel() { addModel() {
@ -277,11 +277,11 @@ export default {
this.editModelData = JSON.parse(JSON.stringify(model)); this.editModelData = JSON.parse(JSON.stringify(model));
this.editDialogVisible = true; this.editDialogVisible = true;
}, },
// 删除单个模型 // Delete single model
deleteModel(model) { deleteModel(model) {
this.$confirm('确定要删除该模型吗?', '提示', { this.$confirm('Are you sure you want to delete this model?', 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
Api.model.deleteModel( Api.model.deleteModel(
@ -289,20 +289,20 @@ export default {
({ data }) => { ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: '删除成功', message: 'Deleted successfully',
showClose: true showClose: true
}) })
this.loadData() this.loadData()
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '删除失败', message: data.msg || 'Failed to delete',
showClose: true showClose: true
}) })
} }
} }
) )
}).catch(() => { }).catch(() => {
this.$message.info('已取消删除') this.$message.info('Deletion cancelled')
}) })
}, },
handleCurrentChange(page) { handleCurrentChange(page) {
@ -317,13 +317,13 @@ export default {
{ modelType, provideCode, id, formData }, { modelType, provideCode, id, formData },
({ data }) => { ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('保存成功'); this.$message.success('Saved successfully');
this.loadData(); this.loadData();
this.editDialogVisible = false; this.editDialogVisible = false;
} else { } else {
this.$message.error(data.msg || '保存失败'); this.$message.error(data.msg || 'Failed to save');
} }
done && done(); // 调用done回调关闭加载状态 done && done(); // Call done callback to close loading state
} }
); );
}, },
@ -342,7 +342,7 @@ export default {
} }
}, },
// 新增模型配置 // Add new model configuration
handleAddConfirm(newModel) { handleAddConfirm(newModel) {
const params = { const params = {
modelType: this.activeTab, modelType: this.activeTab,
@ -358,20 +358,20 @@ export default {
Api.model.addModel(params, ({ data }) => { Api.model.addModel(params, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: '新增成功', message: 'Added successfully',
showClose: true showClose: true
}); });
this.loadData(); this.loadData();
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '新增失败', message: data.msg || 'Failed to add',
showClose: true showClose: true
}); });
} }
}); });
}, },
// 分页器 // Pagination
goFirst() { goFirst() {
this.currentPage = 1; this.currentPage = 1;
this.loadData(); this.loadData();
@ -393,9 +393,9 @@ export default {
this.loadData(); this.loadData();
}, },
// 获取模型配置列表 // Get model configuration list
loadData() { loadData() {
this.loading = true; // 开始加载 this.loading = true; // Start loading
const params = { const params = {
modelType: this.activeTab, modelType: this.activeTab,
modelName: this.search, modelName: this.search,
@ -404,16 +404,16 @@ export default {
}; };
Api.model.getModelList(params, ({ data }) => { Api.model.getModelList(params, ({ data }) => {
this.loading = false; // 结束加载 this.loading = false; // End loading
if (data.code === 0) { if (data.code === 0) {
this.modelList = data.data.list; this.modelList = data.data.list;
this.total = data.data.total; this.total = data.data.total;
} else { } else {
this.$message.error(data.msg || '获取模型列表失败'); this.$message.error(data.msg || 'Failed to get model list');
} }
}); });
}, },
// 处理启用/禁用状态变更 // Handle enable/disable status change
handleStatusChange(model) { handleStatusChange(model) {
const newStatus = model.isEnabled ? 1 : 0 const newStatus = model.isEnabled ? 1 : 0
const originalStatus = model.isEnabled const originalStatus = model.isEnabled
@ -425,13 +425,13 @@ export default {
newStatus, newStatus,
({ data }) => { ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success(newStatus === 1 ? '启用成功' : '禁用成功') this.$message.success(newStatus === 1 ? 'Enabled successfully' : 'Disabled successfully')
// 保持新状态 // Keep new status
model.isEnabled = newStatus model.isEnabled = newStatus
} else { } else {
// 操作失败时恢复原状态 // Restore original status on failure
model.isEnabled = originalStatus model.isEnabled = originalStatus
this.$message.error(data.msg || '操作失败') this.$message.error(data.msg || 'Operation failed')
} }
} }
) )
@ -439,7 +439,7 @@ export default {
handleDefaultChange(model) { handleDefaultChange(model) {
Api.model.setDefaultModel(model.id, ({ data }) => { Api.model.setDefaultModel(model.id, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success('设置默认模型成功') this.$message.success('Default model set successfully')
this.loadData() this.loadData()
} }
}) })
@ -741,7 +741,7 @@ export default {
} }
::v-deep .el-table .custom-selection-header .cell::before { ::v-deep .el-table .custom-selection-header .cell::before {
content: '选择'; content: 'Select';
display: block; display: block;
text-align: center; text-align: center;
line-height: 0; line-height: 0;
@ -808,7 +808,7 @@ export default {
.voice-management-btn:hover { .voice-management-btn:hover {
background: #8aa2e0; background: #8aa2e0;
/* 悬停时颜色加深 */ /* Darker color on hover */
transform: scale(1.05); transform: scale(1.05);
} }
@ -831,13 +831,13 @@ export default {
padding-right: 10px; padding-right: 10px;
} }
/* 分页器 */ /* Pagination */
.custom-pagination { .custom-pagination {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
/* 导航按钮样式 (首页、上一页、下一页) */ /* Navigation button styles (First, Previous, Next) */
.pagination-btn:first-child, .pagination-btn:first-child,
.pagination-btn:nth-child(2), .pagination-btn:nth-child(2),
.pagination-btn:nth-child(3), .pagination-btn:nth-child(3),
@ -863,7 +863,7 @@ export default {
} }
} }
/* 数字按钮样式 */ /* Number button styles */
.pagination-btn:not(:first-child):not(:nth-child(2)):not(:nth-child(3)):not(:nth-last-child(2)) { .pagination-btn:not(:first-child):not(:nth-child(2)):not(:nth-child(3)):not(:nth-last-child(2)) {
min-width: 28px; min-width: 28px;
height: 32px; height: 32px;

View file

@ -3,11 +3,11 @@
<HeaderBar /> <HeaderBar />
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">固件管理</h2> <h2 class="page-title">Firmware Management</h2>
<div class="right-operations"> <div class="right-operations">
<el-input placeholder="请输入固件名称查询" v-model="searchName" class="search-input" <el-input placeholder="Enter firmware name to search" v-model="searchName" class="search-input"
@keyup.enter.native="handleSearch" clearable /> @keyup.enter.native="handleSearch" clearable />
<el-button class="btn-search" @click="handleSearch">搜索</el-button> <el-button class="btn-search" @click="handleSearch">Search</el-button>
</div> </div>
</div> </div>
@ -16,44 +16,44 @@
<div class="content-area"> <div class="content-area">
<el-card class="params-card" shadow="never"> <el-card class="params-card" shadow="never">
<el-table ref="paramsTable" :data="paramsList" class="transparent-table" v-loading="loading" <el-table ref="paramsTable" :data="paramsList" class="transparent-table" v-loading="loading"
element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)" element-loading-background="rgba(255, 255, 255, 0.7)"
:header-cell-class-name="headerCellClassName"> :header-cell-class-name="headerCellClassName">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="Select" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="固件名称" prop="firmwareName" align="center"></el-table-column> <el-table-column label="Firmware Name" prop="firmwareName" align="center"></el-table-column>
<el-table-column label="固件类型" prop="type" align="center"> <el-table-column label="Firmware Type" prop="type" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ getFirmwareTypeName(scope.row.type) }} {{ getFirmwareTypeName(scope.row.type) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="版本号" prop="version" align="center"></el-table-column> <el-table-column label="Version" prop="version" align="center"></el-table-column>
<el-table-column label="文件大小" prop="size" align="center"> <el-table-column label="File Size" prop="size" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ formatFileSize(scope.row.size) }} {{ formatFileSize(scope.row.size) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="备注" prop="remark" align="center" <el-table-column label="Remark" prop="remark" align="center"
show-overflow-tooltip></el-table-column> show-overflow-tooltip></el-table-column>
<el-table-column label="创建时间" prop="createDate" align="center"> <el-table-column label="Create Time" prop="createDate" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ formatDate(scope.row.createDate) }} {{ formatDate(scope.row.createDate) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="更新时间" prop="updateDate" align="center"> <el-table-column label="Update Time" prop="updateDate" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
{{ formatDate(scope.row.updateDate) }} {{ formatDate(scope.row.updateDate) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" align="center"> <el-table-column label="Actions" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="mini" type="text" <el-button size="mini" type="text"
@click="downloadFirmware(scope.row)">下载</el-button> @click="downloadFirmware(scope.row)">Download</el-button>
<el-button size="mini" type="text" @click="editParam(scope.row)">编辑</el-button> <el-button size="mini" type="text" @click="editParam(scope.row)">Edit</el-button>
<el-button size="mini" type="text" @click="deleteParam(scope.row)">删除</el-button> <el-button size="mini" type="text" @click="deleteParam(scope.row)">Delete</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -61,33 +61,33 @@
<div class="table_bottom"> <div class="table_bottom">
<div class="ctrl_btn"> <div class="ctrl_btn">
<el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll"> <el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll">
{{ isAllSelected ? '取消全选' : '全选' }} {{ isAllSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button size="mini" type="success" @click="showAddDialog" <el-button size="mini" type="success" @click="showAddDialog"
style="background: #5bc98c;border: None;">新增</el-button> style="background: #5bc98c;border: None;">Add</el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" <el-button size="mini" type="danger" icon="el-icon-delete"
@click="deleteSelectedParams">删除</el-button> @click="deleteSelectedParams">Delete</el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select">
<el-option v-for="item in pageSizeOptions" :key="item" :label="`${item}条/页`" <el-option v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`"
:value="item"> :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">
首页 First
</button> </button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">
上一页 Previous
</button> </button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> </button>
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext"> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">
下一页 Next
</button> </button>
<span class="total-text">共{{ total }}条记录</span> <span class="total-text">Total {{ total }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -95,7 +95,7 @@
</div> </div>
</div> </div>
<!-- 新增/编辑固件对话框 --> <!-- Add/Edit firmware dialog -->
<firmware-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="firmwareForm" <firmware-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="firmwareForm"
:firmware-types="firmwareTypes" @submit="handleSubmit" @cancel="dialogVisible = false" /> :firmware-types="firmwareTypes" @submit="handleSubmit" @cancel="dialogVisible = false" />
<el-footer> <el-footer>
@ -124,7 +124,7 @@ export default {
pageSizeOptions: [10, 20, 50, 100], pageSizeOptions: [10, 20, 50, 100],
total: 0, total: 0,
dialogVisible: false, dialogVisible: false,
dialogTitle: "新增固件", dialogTitle: "Add Firmware",
isAllSelected: false, isAllSelected: false,
firmwareForm: { firmwareForm: {
id: null, id: null,
@ -193,7 +193,7 @@ export default {
this.paramsList = []; this.paramsList = [];
this.total = 0; this.total = 0;
this.$message.error({ this.$message.error({
message: res?.data?.msg || '获取固件列表失败', message: res?.data?.msg || 'Failed to get firmware list',
showClose: true showClose: true
}); });
} }
@ -210,8 +210,8 @@ export default {
}); });
}, },
showAddDialog() { showAddDialog() {
this.dialogTitle = "新增固件"; this.dialogTitle = "Add Firmware";
// 完全重置表单数据 // Completely reset form data
this.firmwareForm = { this.firmwareForm = {
id: null, id: null,
firmwareName: "", firmwareName: "",
@ -222,7 +222,7 @@ export default {
firmwarePath: "" firmwarePath: ""
}; };
this.$nextTick(() => { this.$nextTick(() => {
// 重置表单的校验状态 // Reset form validation state
if (this.$refs.firmwareDialog && this.$refs.firmwareDialog.$refs.form) { if (this.$refs.firmwareDialog && this.$refs.firmwareDialog.$refs.form) {
this.$refs.firmwareDialog.$refs.form.clearValidate(); this.$refs.firmwareDialog.$refs.form.clearValidate();
} }
@ -230,43 +230,43 @@ export default {
this.dialogVisible = true; this.dialogVisible = true;
}, },
editParam(row) { editParam(row) {
this.dialogTitle = "编辑固件"; this.dialogTitle = "Edit Firmware";
this.firmwareForm = { ...row }; this.firmwareForm = { ...row };
this.dialogVisible = true; this.dialogVisible = true;
}, },
handleSubmit(form) { handleSubmit(form) {
if (form.id) { if (form.id) {
// 编辑 // Edit
Api.ota.updateOta(form.id, form, (res) => { Api.ota.updateOta(form.id, form, (res) => {
res = res.data; res = res.data;
if (res.code === 0) { if (res.code === 0) {
this.$message.success({ this.$message.success({
message: "修改成功", message: "Modified successfully",
showClose: true showClose: true
}); });
this.dialogVisible = false; this.dialogVisible = false;
this.fetchFirmwareList(); this.fetchFirmwareList();
} else { } else {
this.$message.error({ this.$message.error({
message: res.msg || "修改失败", message: res.msg || "Failed to modify",
showClose: true showClose: true
}); });
} }
}); });
} else { } else {
// 新增 // Add
Api.ota.saveOta(form, (res) => { Api.ota.saveOta(form, (res) => {
res = res.data; res = res.data;
if (res.code === 0) { if (res.code === 0) {
this.$message.success({ this.$message.success({
message: "新增成功", message: "Added successfully",
showClose: true showClose: true
}); });
this.dialogVisible = false; this.dialogVisible = false;
this.fetchFirmwareList(); this.fetchFirmwareList();
} else { } else {
this.$message.error({ this.$message.error({
message: res.msg || "新增失败", message: res.msg || "Failed to add",
showClose: true showClose: true
}); });
} }
@ -278,7 +278,7 @@ export default {
const selectedRows = this.firmwareList.filter(row => row.selected); const selectedRows = this.firmwareList.filter(row => row.selected);
if (selectedRows.length === 0) { if (selectedRows.length === 0) {
this.$message.warning({ this.$message.warning({
message: "请先选择需要删除的固件", message: "Please select firmware to delete first",
showClose: true showClose: true
}); });
return; return;
@ -286,28 +286,28 @@ export default {
this.deleteParam(selectedRows); this.deleteParam(selectedRows);
}, },
deleteParam(row) { deleteParam(row) {
// 处理单个参数或参数数组 // Handle single parameter or parameter array
const params = Array.isArray(row) ? row : [row]; const params = Array.isArray(row) ? row : [row];
if (Array.isArray(row) && row.length === 0) { if (Array.isArray(row) && row.length === 0) {
this.$message.warning({ this.$message.warning({
message: "请先选择需要删除的参数", message: "Please select parameters to delete first",
showClose: true showClose: true
}); });
return; return;
} }
const paramCount = params.length; const paramCount = params.length;
this.$confirm(`确定要删除选中的${paramCount}个固件吗?`, '警告', { this.$confirm(`Are you sure you want to delete ${paramCount} selected firmware?`, 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning', type: 'warning',
distinguishCancelAndClose: true distinguishCancelAndClose: true
}).then(() => { }).then(() => {
const ids = params.map(param => param.id); const ids = params.map(param => param.id);
if (ids.some(id => !id)) { if (ids.some(id => !id)) {
this.$message.error({ this.$message.error({
message: '存在无效的参数ID', message: 'Invalid parameter IDs found',
showClose: true showClose: true
}); });
return; return;
@ -317,13 +317,13 @@ export default {
res = res.data; res = res.data;
if (res.code === 0) { if (res.code === 0) {
this.$message.success({ this.$message.success({
message: `成功删除${paramCount}个固件`, message: `Successfully deleted ${paramCount} firmware`,
showClose: true showClose: true
}); });
this.fetchFirmwareList(); this.fetchFirmwareList();
} else { } else {
this.$message.error({ this.$message.error({
message: res.msg || '删除失败,请重试', message: res.msg || 'Failed to delete, please try again',
showClose: true showClose: true
}); });
} }
@ -332,13 +332,13 @@ export default {
if (action === 'cancel') { if (action === 'cancel') {
this.$message({ this.$message({
type: 'info', type: 'info',
message: '已取消删除操作', message: 'Delete operation cancelled',
duration: 1000 duration: 1000
}); });
} else { } else {
this.$message({ this.$message({
type: 'info', type: 'info',
message: '操作已关闭', message: 'Operation closed',
duration: 1000 duration: 1000
}); });
} }
@ -372,17 +372,17 @@ export default {
}, },
downloadFirmware(firmware) { downloadFirmware(firmware) {
if (!firmware || !firmware.id) { if (!firmware || !firmware.id) {
this.$message.error('固件信息不完整'); this.$message.error('Incomplete firmware information');
return; return;
} }
// 先获取下载链接 // First get download link
Api.ota.getDownloadUrl(firmware.id, (res) => { Api.ota.getDownloadUrl(firmware.id, (res) => {
if (res.data.code === 0) { if (res.data.code === 0) {
const uuid = res.data.data; const uuid = res.data.data;
const baseUrl = process.env.VUE_APP_API_BASE_URL || ''; const baseUrl = process.env.VUE_APP_API_BASE_URL || '';
window.open(`${window.location.origin}${baseUrl}/otaMag/download/${uuid}`); window.open(`${window.location.origin}${baseUrl}/otaMag/download/${uuid}`);
} else { } else {
this.$message.error('获取下载链接失败'); this.$message.error('Failed to get download link');
} }
}); });
}, },
@ -393,8 +393,8 @@ export default {
const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE') const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE')
this.firmwareTypes = res.data this.firmwareTypes = res.data
} catch (error) { } catch (error) {
console.error('获取固件类型失败:', error) console.error('Failed to get firmware types:', error)
this.$message.error(error.message || '获取固件类型失败') this.$message.error(error.message || 'Failed to get firmware types')
} }
}, },
getFirmwareTypeName(type) { getFirmwareTypeName(type) {

View file

@ -3,11 +3,11 @@
<HeaderBar /> <HeaderBar />
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">参数管理</h2> <h2 class="page-title">Parameter Management</h2>
<div class="right-operations"> <div class="right-operations">
<el-input placeholder="请输入参数编码或备注查询" v-model="searchCode" class="search-input" <el-input placeholder="Enter parameter code or remark to search" v-model="searchCode" class="search-input"
@keyup.enter.native="handleSearch" clearable /> @keyup.enter.native="handleSearch" clearable />
<el-button class="btn-search" @click="handleSearch">搜索</el-button> <el-button class="btn-search" @click="handleSearch">Search</el-button>
</div> </div>
</div> </div>
@ -16,33 +16,33 @@
<div class="content-area"> <div class="content-area">
<el-card class="params-card" shadow="never"> <el-card class="params-card" shadow="never">
<el-table ref="paramsTable" :data="paramsList" class="transparent-table" v-loading="loading" <el-table ref="paramsTable" :data="paramsList" class="transparent-table" v-loading="loading"
element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)" element-loading-background="rgba(255, 255, 255, 0.7)"
:header-cell-class-name="headerCellClassName"> :header-cell-class-name="headerCellClassName">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="Select" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="参数编码" prop="paramCode" align="center"></el-table-column> <el-table-column label="Parameter Code" prop="paramCode" align="center"></el-table-column>
<el-table-column label="参数值" prop="paramValue" align="center" show-overflow-tooltip> <el-table-column label="Parameter Value" prop="paramValue" align="center" show-overflow-tooltip>
<template slot-scope="scope"> <template slot-scope="scope">
<div v-if="isSensitiveParam(scope.row.paramCode)"> <div v-if="isSensitiveParam(scope.row.paramCode)">
<span v-if="!scope.row.showValue">{{ maskSensitiveValue(scope.row.paramValue) <span v-if="!scope.row.showValue">{{ maskSensitiveValue(scope.row.paramValue)
}}</span> }}</span>
<span v-else>{{ scope.row.paramValue }}</span> <span v-else>{{ scope.row.paramValue }}</span>
<el-button size="mini" type="text" @click="toggleSensitiveValue(scope.row)"> <el-button size="mini" type="text" @click="toggleSensitiveValue(scope.row)">
{{ scope.row.showValue ? '隐藏' : '查看' }} {{ scope.row.showValue ? 'Hide' : 'View' }}
</el-button> </el-button>
</div> </div>
<span v-else>{{ scope.row.paramValue }}</span> <span v-else>{{ scope.row.paramValue }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="备注" prop="remark" align="center"></el-table-column> <el-table-column label="Remark" prop="remark" align="center"></el-table-column>
<el-table-column label="操作" align="center"> <el-table-column label="Actions" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="mini" type="text" @click="editParam(scope.row)">编辑</el-button> <el-button size="mini" type="text" @click="editParam(scope.row)">Edit</el-button>
<el-button size="mini" type="text" @click="deleteParam(scope.row)">删除</el-button> <el-button size="mini" type="text" @click="deleteParam(scope.row)">Delete</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -50,32 +50,32 @@
<div class="table_bottom"> <div class="table_bottom">
<div class="ctrl_btn"> <div class="ctrl_btn">
<el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll"> <el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll">
{{ isAllSelected ? '取消全选' : '全选' }} {{ isAllSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button size="mini" type="success" @click="showAddDialog">新增</el-button> <el-button size="mini" type="success" @click="showAddDialog">Add</el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" <el-button size="mini" type="danger" icon="el-icon-delete"
@click="deleteSelectedParams">删除</el-button> @click="deleteSelectedParams">Delete</el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select">
<el-option v-for="item in pageSizeOptions" :key="item" :label="`${item}条/页`" <el-option v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`"
:value="item"> :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">
首页 First
</button> </button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">
上一页 Previous
</button> </button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> </button>
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext"> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">
下一页 Next
</button> </button>
<span class="total-text">共{{ total }}条记录</span> <span class="total-text">Total {{ total }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -83,7 +83,7 @@
</div> </div>
</div> </div>
<!-- 新增/编辑参数对话框 --> <!-- Add/Edit parameter dialog -->
<param-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="paramForm" @submit="handleSubmit" <param-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="paramForm" @submit="handleSubmit"
@cancel="dialogVisible = false" /> @cancel="dialogVisible = false" />
<el-footer> <el-footer>
@ -109,7 +109,7 @@ export default {
pageSizeOptions: [10, 20, 50, 100], pageSizeOptions: [10, 20, 50, 100],
total: 0, total: 0,
dialogVisible: false, dialogVisible: false,
dialogTitle: "新增参数", dialogTitle: "Add Parameter",
isAllSelected: false, isAllSelected: false,
sensitive_keys: ["api_key", "personal_access_token", "access_token", "token", "secret", "access_key_secret", "secret_key"], sensitive_keys: ["api_key", "personal_access_token", "access_token", "token", "secret", "access_key_secret", "secret_key"],
paramForm: { paramForm: {
@ -170,7 +170,7 @@ export default {
this.total = data.data.total; this.total = data.data.total;
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '获取参数列表失败', message: data.msg || 'Failed to get parameter list',
showClose: true showClose: true
}); });
} }
@ -188,7 +188,7 @@ export default {
}); });
}, },
showAddDialog() { showAddDialog() {
this.dialogTitle = "新增参数"; this.dialogTitle = "Add Parameter";
this.paramForm = { this.paramForm = {
id: null, id: null,
paramCode: "", paramCode: "",
@ -198,18 +198,18 @@ export default {
this.dialogVisible = true; this.dialogVisible = true;
}, },
editParam(row) { editParam(row) {
this.dialogTitle = "编辑参数"; this.dialogTitle = "Edit Parameter";
this.paramForm = { ...row }; this.paramForm = { ...row };
this.dialogVisible = true; this.dialogVisible = true;
}, },
handleSubmit({ form, done }) { handleSubmit({ form, done }) {
if (form.id) { if (form.id) {
// 编辑 // Edit
Api.admin.updateParam(form, ({ data }) => { Api.admin.updateParam(form, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: "修改成功", message: "Modified successfully",
showClose: true showClose: true
}); });
this.dialogVisible = false; this.dialogVisible = false;
@ -218,11 +218,11 @@ export default {
done && done(); done && done();
}); });
} else { } else {
// 新增 // Add
Api.admin.addParam(form, ({ data }) => { Api.admin.addParam(form, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: "新增成功", message: "Added successfully",
showClose: true showClose: true
}); });
this.dialogVisible = false; this.dialogVisible = false;
@ -237,7 +237,7 @@ export default {
const selectedRows = this.paramsList.filter(row => row.selected); const selectedRows = this.paramsList.filter(row => row.selected);
if (selectedRows.length === 0) { if (selectedRows.length === 0) {
this.$message.warning({ this.$message.warning({
message: "请先选择需要删除的参数", message: "Please select parameters to delete first",
showClose: true showClose: true
}); });
return; return;
@ -245,28 +245,28 @@ export default {
this.deleteParam(selectedRows); this.deleteParam(selectedRows);
}, },
deleteParam(row) { deleteParam(row) {
// 处理单个参数或参数数组 // Handle single parameter or parameter array
const params = Array.isArray(row) ? row : [row]; const params = Array.isArray(row) ? row : [row];
if (Array.isArray(row) && row.length === 0) { if (Array.isArray(row) && row.length === 0) {
this.$message.warning({ this.$message.warning({
message: "请先选择需要删除的参数", message: "Please select parameters to delete first",
showClose: true showClose: true
}); });
return; return;
} }
const paramCount = params.length; const paramCount = params.length;
this.$confirm(`确定要删除选中的${paramCount}个参数吗?`, '警告', { this.$confirm(`Are you sure you want to delete ${paramCount} selected parameters?`, 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning', type: 'warning',
distinguishCancelAndClose: true distinguishCancelAndClose: true
}).then(() => { }).then(() => {
const ids = params.map(param => param.id); const ids = params.map(param => param.id);
if (ids.some(id => isNaN(id))) { if (ids.some(id => isNaN(id))) {
this.$message.error({ this.$message.error({
message: '存在无效的参数ID', message: 'Invalid parameter IDs found',
showClose: true showClose: true
}); });
return; return;
@ -275,13 +275,13 @@ export default {
Api.admin.deleteParam(ids, ({ data }) => { Api.admin.deleteParam(ids, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: `成功删除${paramCount}个参数`, message: `Successfully deleted ${paramCount} parameters`,
showClose: true showClose: true
}); });
this.fetchParams(); this.fetchParams();
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '删除失败,请重试', message: data.msg || 'Failed to delete, please try again',
showClose: true showClose: true
}); });
} }
@ -290,13 +290,13 @@ export default {
if (action === 'cancel') { if (action === 'cancel') {
this.$message({ this.$message({
type: 'info', type: 'info',
message: '已取消删除操作', message: 'Delete operation cancelled',
duration: 1000 duration: 1000
}); });
} else { } else {
this.$message({ this.$message({
type: 'info', type: 'info',
message: '操作已关闭', message: 'Operation closed',
duration: 1000 duration: 1000
}); });
} }

View file

@ -3,23 +3,23 @@
<HeaderBar /> <HeaderBar />
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">字段管理</h2> <h2 class="page-title">Provider Management</h2>
<div class="right-operations"> <div class="right-operations">
<el-dropdown trigger="click" @command="handleSelectModelType" @visible-change="handleDropdownVisibleChange"> <el-dropdown trigger="click" @command="handleSelectModelType" @visible-change="handleDropdownVisibleChange">
<el-button class="category-btn"> <el-button class="category-btn">
类别筛选 {{ selectedModelTypeLabel }}<i class="el-icon-arrow-down el-icon--right" Category Filter {{ selectedModelTypeLabel }}<i class="el-icon-arrow-down el-icon--right"
:class="{ 'rotate-down': DropdownVisible }"></i> :class="{ 'rotate-down': DropdownVisible }"></i>
</el-button> </el-button>
<el-dropdown-menu slot="dropdown"> <el-dropdown-menu slot="dropdown">
<el-dropdown-item command="">全部</el-dropdown-item> <el-dropdown-item command="">All</el-dropdown-item>
<el-dropdown-item v-for="item in modelTypes" :key="item.value" :command="item.value"> <el-dropdown-item v-for="item in modelTypes" :key="item.value" :command="item.value">
{{ item.label }} {{ item.label }}
</el-dropdown-item> </el-dropdown-item>
</el-dropdown-menu> </el-dropdown-menu>
</el-dropdown> </el-dropdown>
<el-input placeholder="请输入供应器名称查询" v-model="searchName" class="search-input" @keyup.enter.native="handleSearch" <el-input placeholder="Enter provider name to search" v-model="searchName" class="search-input" @keyup.enter.native="handleSearch"
clearable /> clearable />
<el-button class="btn-search" @click="handleSearch">搜索</el-button> <el-button class="btn-search" @click="handleSearch">Search</el-button>
</div> </div>
</div> </div>
@ -28,24 +28,24 @@
<div class="content-area"> <div class="content-area">
<el-card class="provider-card" shadow="never"> <el-card class="provider-card" shadow="never">
<el-table ref="providersTable" :data="filteredProvidersList" class="transparent-table" v-loading="loading" <el-table ref="providersTable" :data="filteredProvidersList" class="transparent-table" v-loading="loading"
element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)" :header-cell-class-name="headerCellClassName"> element-loading-background="rgba(255, 255, 255, 0.7)" :header-cell-class-name="headerCellClassName">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="Select" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="类别" prop="modelType" align="center" width="200"> <el-table-column label="Category" prop="modelType" align="center" width="200">
<template slot="header" slot-scope="scope"> <template slot="header" slot-scope="scope">
<el-dropdown trigger="click" @command="handleSelectModelType" <el-dropdown trigger="click" @command="handleSelectModelType"
@visible-change="isDropdownOpen = $event"> @visible-change="isDropdownOpen = $event">
<span class="dropdown-trigger" :class="{ 'active': isDropdownOpen }"> <span class="dropdown-trigger" :class="{ 'active': isDropdownOpen }">
类别{{ selectedModelTypeLabel }} <i class="dropdown-arrow" Category{{ selectedModelTypeLabel }} <i class="dropdown-arrow"
:class="{ 'is-active': isDropdownOpen }"></i> :class="{ 'is-active': isDropdownOpen }"></i>
</span> </span>
<el-dropdown-menu slot="dropdown"> <el-dropdown-menu slot="dropdown">
<el-dropdown-item command="">全部</el-dropdown-item> <el-dropdown-item command="">All</el-dropdown-item>
<el-dropdown-item v-for="item in modelTypes" :key="item.value" :command="item.value"> <el-dropdown-item v-for="item in modelTypes" :key="item.value" :command="item.value">
{{ item.label }} {{ item.label }}
</el-dropdown-item> </el-dropdown-item>
@ -58,25 +58,25 @@
</el-tag> </el-tag>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="供应器编码" prop="providerCode" align="center" width="150"></el-table-column> <el-table-column label="Provider Code" prop="providerCode" align="center" width="150"></el-table-column>
<el-table-column label="名称" prop="name" align="center"></el-table-column> <el-table-column label="Name" prop="name" align="center"></el-table-column>
<el-table-column label="字段配置" align="center"> <el-table-column label="Field Configuration" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-popover placement="top-start" width="400" trigger="hover"> <el-popover placement="top-start" width="400" trigger="hover">
<div v-for="field in scope.row.fields" :key="field.key" class="field-item"> <div v-for="field in scope.row.fields" :key="field.key" class="field-item">
<span class="field-label">{{ field.label }}:</span> <span class="field-label">{{ field.label }}:</span>
<span class="field-type">{{ field.type }}</span> <span class="field-type">{{ field.type }}</span>
<span v-if="isSensitiveField(field.key)" class="sensitive-tag">敏感</span> <span v-if="isSensitiveField(field.key)" class="sensitive-tag">Sensitive</span>
</div> </div>
<el-button slot="reference" size="mini" type="text">查看字段</el-button> <el-button slot="reference" size="mini" type="text">View Fields</el-button>
</el-popover> </el-popover>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="排序" prop="sort" align="center" width="80"></el-table-column> <el-table-column label="Sort Order" prop="sort" align="center" width="80"></el-table-column>
<el-table-column label="操作" align="center" width="180"> <el-table-column label="Actions" align="center" width="180">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="mini" type="text" @click="editProvider(scope.row)">编辑</el-button> <el-button size="mini" type="text" @click="editProvider(scope.row)">Edit</el-button>
<el-button size="mini" type="text" @click="deleteProvider(scope.row)">删除</el-button> <el-button size="mini" type="text" @click="deleteProvider(scope.row)">Delete</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -84,31 +84,31 @@
<div class="table_bottom"> <div class="table_bottom">
<div class="ctrl_btn"> <div class="ctrl_btn">
<el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll"> <el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll">
{{ isAllSelected ? '取消全选' : '全选' }} {{ isAllSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button size="mini" type="success" @click="showAddDialog">新增</el-button> <el-button size="mini" type="success" @click="showAddDialog">Add</el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSelectedProviders">删除 <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSelectedProviders">Delete
</el-button> </el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <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 v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`" :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">
首页 First
</button> </button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">
上一页 Previous
</button> </button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> </button>
<button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext"> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">
下一页 Next
</button> </button>
<span class="total-text">共{{ total }}条记录</span> <span class="total-text">Total {{ total }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -116,7 +116,7 @@
</div> </div>
</div> </div>
<!-- 新增/编辑供应器对话框 --> <!-- Add/Edit provider dialog -->
<provider-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="providerForm" :model-types="modelTypes" <provider-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="providerForm" :model-types="modelTypes"
@submit="handleSubmit" @cancel="dialogVisible = false" /> @submit="handleSubmit" @cancel="dialogVisible = false" />
@ -140,14 +140,14 @@ export default {
searchModelType: "", searchModelType: "",
providersList: [], providersList: [],
modelTypes: [ modelTypes: [
{ value: "ASR", label: "语音识别" }, { value: "ASR", label: "Speech Recognition" },
{ value: "TTS", label: "语音合成" }, { value: "TTS", label: "Text-to-Speech" },
{ value: "LLM", label: "大语言模型" }, { value: "LLM", label: "Large Language Model" },
{ value: "VLLM", label: "视觉大语言模型" }, { value: "VLLM", label: "Vision Language Model" },
{ value: "Intent", label: "意图识别" }, { value: "Intent", label: "Intent Recognition" },
{ value: "Memory", label: "记忆模块" }, { value: "Memory", label: "Memory Module" },
{ value: "VAD", label: "语音活动检测" }, { value: "VAD", label: "Voice Activity Detection" },
{ value: "Plugin", label: "插件工具" } { value: "Plugin", label: "Plugin Tools" }
], ],
currentPage: 1, currentPage: 1,
loading: false, loading: false,
@ -155,7 +155,7 @@ export default {
pageSizeOptions: [10, 20, 50, 100], pageSizeOptions: [10, 20, 50, 100],
total: 0, total: 0,
dialogVisible: false, dialogVisible: false,
dialogTitle: "新增供应器", dialogTitle: "Add Provider",
isAllSelected: false, isAllSelected: false,
isDropdownOpen: false, isDropdownOpen: false,
sensitive_keys: ["api_key", "personal_access_token", "access_token", "token", "secret", "access_key_secret", "secret_key"], sensitive_keys: ["api_key", "personal_access_token", "access_token", "token", "secret", "access_key_secret", "secret_key"],
@ -175,7 +175,7 @@ export default {
}, },
computed: { computed: {
selectedModelTypeLabel() { selectedModelTypeLabel() {
if (!this.searchModelType) return "(全部)"; if (!this.searchModelType) return "(All)";
const selectedType = this.modelTypes.find(item => item.value === this.searchModelType); const selectedType = this.modelTypes.find(item => item.value === this.searchModelType);
return selectedType ? `(${selectedType.label})` : ""; return selectedType ? `(${selectedType.label})` : "";
}, },
@ -237,7 +237,7 @@ export default {
this.total = data.data.total; this.total = data.data.total;
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '获取参数列表失败' message: data.msg || 'Failed to get provider list'
}); });
} }
} }
@ -259,7 +259,7 @@ export default {
}); });
}, },
showAddDialog() { showAddDialog() {
this.dialogTitle = "新增供应器"; this.dialogTitle = "Add Provider";
this.providerForm = { this.providerForm = {
id: null, id: null,
modelType: "", modelType: "",
@ -271,7 +271,7 @@ export default {
this.dialogVisible = true; this.dialogVisible = true;
}, },
editProvider(row) { editProvider(row) {
this.dialogTitle = "编辑供应器"; this.dialogTitle = "Edit Provider";
this.providerForm = { this.providerForm = {
...row, ...row,
fields: JSON.parse(JSON.stringify(row.fields)) fields: JSON.parse(JSON.stringify(row.fields))
@ -281,24 +281,24 @@ export default {
handleSubmit({ form, done }) { handleSubmit({ form, done }) {
this.loading = true; this.loading = true;
if (form.id) { if (form.id) {
// 编辑 // Edit
Api.model.updateModelProvider(form, ({ data }) => { Api.model.updateModelProvider(form, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.fetchProviders(); // 刷新表格 this.fetchProviders(); // Refresh table
this.$message.success({ this.$message.success({
message: "修改成功", message: "Modified successfully",
showClose: true showClose: true
}); });
} }
}); });
} else { } else {
// 新增 // Add
Api.model.addModelProvider(form, ({ data }) => { Api.model.addModelProvider(form, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.fetchProviders(); // 刷新表格 this.fetchProviders(); // Refresh table
this.$message.success({ this.$message.success({
message: "新增成功", message: "Added successfully",
showClose: true showClose: true
}); });
this.total += 1; this.total += 1;
@ -313,7 +313,7 @@ export default {
const selectedRows = this.providersList.filter(row => row.selected); const selectedRows = this.providersList.filter(row => row.selected);
if (selectedRows.length === 0) { if (selectedRows.length === 0) {
this.$message.warning({ this.$message.warning({
message: "请先选择需要删除的供应器", message: "Please select providers to delete first",
showClose: true showClose: true
}); });
return; return;
@ -324,9 +324,9 @@ export default {
const providers = Array.isArray(row) ? row : [row]; const providers = Array.isArray(row) ? row : [row];
const providerCount = providers.length; const providerCount = providers.length;
this.$confirm(`确定要删除选中的${providerCount}个供应器吗?`, '警告', { this.$confirm(`Are you sure you want to delete ${providerCount} selected providers?`, 'Warning', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning', type: 'warning',
}).then(() => { }).then(() => {
const ids = providers.map(provider => provider.id); const ids = providers.map(provider => provider.id);
@ -334,15 +334,15 @@ export default {
if (data.code === 0) { if (data.code === 0) {
this.isAllSelected = false; this.isAllSelected = false;
this.fetchProviders(); // 刷新表格 this.fetchProviders(); // Refresh table
this.$message.success({ this.$message.success({
message: `成功删除${providerCount}个参数`, message: `Successfully deleted ${providerCount} providers`,
showClose: true showClose: true
}); });
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '删除失败,请重试', message: data.msg || 'Failed to delete, please try again',
showClose: true showClose: true
}); });
} }
@ -350,7 +350,7 @@ export default {
}).catch(() => { }).catch(() => {
this.$message({ this.$message({
type: 'info', type: 'info',
message: '已取消删除', message: 'Delete operation cancelled',
showClose: true, showClose: true,
duration: 1000 duration: 1000
}); });

View file

@ -3,7 +3,7 @@
<HeaderBar /> <HeaderBar />
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">服务端管理</h2> <h2 class="page-title">Server Management</h2>
</div> </div>
<div class="main-wrapper"> <div class="main-wrapper">
@ -11,19 +11,19 @@
<div class="content-area"> <div class="content-area">
<el-card class="params-card" shadow="never"> <el-card class="params-card" shadow="never">
<el-table ref="paramsTable" :data="paramsList" class="transparent-table" v-loading="loading" <el-table ref="paramsTable" :data="paramsList" class="transparent-table" v-loading="loading"
element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)" :header-cell-class-name="headerCellClassName"> element-loading-background="rgba(255, 255, 255, 0.7)" :header-cell-class-name="headerCellClassName">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="Select" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="ws地址" prop="address" align="center"></el-table-column> <el-table-column label="WebSocket Address" prop="address" align="center"></el-table-column>
<el-table-column label="操作" prop="operator" align="center" show-overflow-tooltip> <el-table-column label="Actions" prop="operator" align="center" show-overflow-tooltip>
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="medium" type="text" @click="emitAction(scope.row, actionMap.restart)">重启</el-button> <el-button size="medium" type="text" @click="emitAction(scope.row, actionMap.restart)">Restart</el-button>
<el-button size="medium" type="text" <el-button size="medium" type="text"
@click="emitAction(scope.row, actionMap.update_config)">更新配置</el-button> @click="emitAction(scope.row, actionMap.update_config)">Update Config</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -53,15 +53,15 @@ export default {
actionMap: { actionMap: {
restart: { restart: {
value: 'restart', value: 'restart',
title: "重启服务端", title: "Restart Server",
message: "确定要重启服务端吗?", message: "Are you sure you want to restart the server?",
confirmText: "重启", confirmText: "Restart",
}, },
update_config: { update_config: {
value: 'update_config', value: 'update_config',
title: "更新配置", title: "Update Configuration",
message: "确定要更新配置吗?", message: "Are you sure you want to update the configuration?",
confirmText: "更新", confirmText: "Update",
} }
}, },
currentPage: 1, currentPage: 1,
@ -70,7 +70,7 @@ export default {
pageSizeOptions: [10, 20, 50, 100], pageSizeOptions: [10, 20, 50, 100],
total: 0, total: 0,
dialogVisible: false, dialogVisible: false,
dialogTitle: "新增参数", dialogTitle: "Add Parameter",
isAllSelected: false, isAllSelected: false,
sensitive_keys: ["api_key", "personal_access_token", "access_token", "token", "secret", "access_key_secret", "secret_key"], sensitive_keys: ["api_key", "personal_access_token", "access_token", "token", "secret", "access_key_secret", "secret_key"],
paramForm: { paramForm: {
@ -122,7 +122,7 @@ export default {
this.total = data.data.length; this.total = data.data.length;
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '获取参数列表失败', message: data.msg || 'Failed to get parameter list',
showClose: true showClose: true
}); });
} }
@ -133,24 +133,24 @@ export default {
if (actionItem === undefined || rowItem.address === undefined) { if (actionItem === undefined || rowItem.address === undefined) {
return; return;
} }
// 弹开询问框 // Show confirmation dialog
this.$confirm(actionItem.message, actionItem.title, { this.$confirm(actionItem.message, actionItem.title, {
confirmButtonText: actionItem.confirmText, // 确认按钮文本 confirmButtonText: actionItem.confirmText, // Confirm button text
}).then(() => { }).then(() => {
// 用户点击了确认按钮 // User clicked confirm button
Api.admin.sendWsServerAction({ Api.admin.sendWsServerAction({
targetWs: rowItem.address, targetWs: rowItem.address,
action: actionItem.value action: actionItem.value
}, ({ data }) => { }, ({ data }) => {
if (data.code !== 0) { if (data.code !== 0) {
this.$message.error({ this.$message.error({
message: data.msg || '操作失败', message: data.msg || 'Operation failed',
showClose: true showClose: true
}); });
return; return;
} }
this.$message.success({ this.$message.success({
message: `${actionItem.title}成功`, message: `${actionItem.title} successful`,
showClose: true showClose: true
}) })
}) })

View file

@ -3,11 +3,11 @@
<HeaderBar /> <HeaderBar />
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">用户管理</h2> <h2 class="page-title">User Management</h2>
<div class="right-operations"> <div class="right-operations">
<el-input placeholder="请输入手机号码查询" v-model="searchPhone" class="search-input" clearable <el-input placeholder="Enter phone number to search" v-model="searchPhone" class="search-input" clearable
@keyup.enter.native="handleSearch" /> @keyup.enter.native="handleSearch" />
<el-button class="btn-search" @click="handleSearch">搜索</el-button> <el-button class="btn-search" @click="handleSearch">Search</el-button>
</div> </div>
</div> </div>
@ -16,31 +16,31 @@
<div class="content-area"> <div class="content-area">
<el-card class="user-card" shadow="never"> <el-card class="user-card" shadow="never">
<el-table ref="userTable" :data="userList" class="transparent-table" v-loading="loading" <el-table ref="userTable" :data="userList" class="transparent-table" v-loading="loading"
element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0.7)"> element-loading-background="rgba(255, 255, 255, 0.7)">
<el-table-column label="选择" align="center" width="120"> <el-table-column label="Select" align="center" width="120">
<template slot-scope="scope"> <template slot-scope="scope">
<el-checkbox v-model="scope.row.selected"></el-checkbox> <el-checkbox v-model="scope.row.selected"></el-checkbox>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="用户Id" prop="userid" align="center"></el-table-column> <el-table-column label="User ID" prop="userid" align="center"></el-table-column>
<el-table-column label="手机号码" prop="mobile" align="center"></el-table-column> <el-table-column label="Phone Number" prop="mobile" align="center"></el-table-column>
<el-table-column label="设备数量" prop="deviceCount" align="center"></el-table-column> <el-table-column label="Device Count" prop="deviceCount" align="center"></el-table-column>
<el-table-column label="注册时间" prop="createDate" align="center"></el-table-column> <el-table-column label="Registration Time" prop="createDate" align="center"></el-table-column>
<el-table-column label="状态" prop="status" align="center"> <el-table-column label="Status" prop="status" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-tag v-if="scope.row.status === 1" type="success">正常</el-tag> <el-tag v-if="scope.row.status === 1" type="success">Active</el-tag>
<el-tag v-else type="danger">禁用</el-tag> <el-tag v-else type="danger">Disabled</el-tag>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" align="center"> <el-table-column label="Actions" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button size="mini" type="text" @click="resetPassword(scope.row)">重置密码</el-button> <el-button size="mini" type="text" @click="resetPassword(scope.row)">Reset Password</el-button>
<el-button size="mini" type="text" v-if="scope.row.status === 1" <el-button size="mini" type="text" v-if="scope.row.status === 1"
@click="handleChangeStatus(scope.row, 0)">禁用账户</el-button> @click="handleChangeStatus(scope.row, 0)">Disable Account</el-button>
<el-button size="mini" type="text" v-if="scope.row.status === 0" <el-button size="mini" type="text" v-if="scope.row.status === 0"
@click="handleChangeStatus(scope.row, 1)">恢复账号</el-button> @click="handleChangeStatus(scope.row, 1)">Enable Account</el-button>
<el-button size="mini" type="text" @click="deleteUser(scope.row)">删除用户</el-button> <el-button size="mini" type="text" @click="deleteUser(scope.row)">Delete User</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@ -48,32 +48,32 @@
<div class="table_bottom"> <div class="table_bottom">
<div class="ctrl_btn"> <div class="ctrl_btn">
<el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll"> <el-button size="mini" type="primary" class="select-all-btn" @click="handleSelectAll">
{{ isAllSelected ? '取消全选' : '全选' }} {{ isAllSelected ? 'Deselect All' : 'Select All' }}
</el-button> </el-button>
<el-button size="mini" type="success" icon="el-icon-circle-check" @click="batchEnable">启用</el-button> <el-button size="mini" type="success" icon="el-icon-circle-check" @click="batchEnable">Enable</el-button>
<el-button size="mini" type="warning" @click="batchDisable"><i <el-button size="mini" type="warning" @click="batchDisable"><i
class="el-icon-remove-outline rotated-icon"></i>禁用</el-button> class="el-icon-remove-outline rotated-icon"></i>Disable</el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" @click="batchDelete">删除</el-button> <el-button size="mini" type="danger" icon="el-icon-delete" @click="batchDelete">Delete</el-button>
</div> </div>
<div class="custom-pagination"> <div class="custom-pagination">
<el-select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select"> <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 v-for="item in pageSizeOptions" :key="item" :label="`${item} items/page`" :value="item">
</el-option> </el-option>
</el-select> </el-select>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goFirst">
首页 First
</button> </button>
<button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev"> <button class="pagination-btn" :disabled="currentPage === 1" @click="goPrev">
上一页 Previous
</button> </button>
<button v-for="page in visiblePages" :key="page" class="pagination-btn" <button v-for="page in visiblePages" :key="page" class="pagination-btn"
:class="{ active: page === currentPage }" @click="goToPage(page)"> :class="{ active: page === currentPage }" @click="goToPage(page)">
{{ page }} {{ page }}
</button> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext"> </button> <button class="pagination-btn" :disabled="currentPage === pageCount" @click="goNext">
下一页 Next
</button> </button>
<span class="total-text">共{{ total }}条记录</span> <span class="total-text">Total {{ total }} records</span>
</div> </div>
</div> </div>
</el-card> </el-card>
@ -148,7 +148,7 @@ export default {
mobile: this.searchPhone, mobile: this.searchPhone,
}, },
({ data }) => { ({ data }) => {
this.loading = false; // 结束加载 this.loading = false; // End loading
if (data.code === 0) { if (data.code === 0) {
this.userList = data.data.list.map(item => ({ this.userList = data.data.list.map(item => ({
...item, ...item,
@ -172,19 +172,19 @@ export default {
batchDelete() { batchDelete() {
const selectedUsers = this.userList.filter(user => user.selected); const selectedUsers = this.userList.filter(user => user.selected);
if (selectedUsers.length === 0) { if (selectedUsers.length === 0) {
this.$message.warning("请先选择需要删除的用户"); this.$message.warning("Please select users to delete first");
return; return;
} }
this.$confirm(`确定要删除选中的${selectedUsers.length}个用户吗?`, "警告", { this.$confirm(`Are you sure you want to delete ${selectedUsers.length} selected users?`, "Warning", {
confirmButtonText: "确定", confirmButtonText: "Confirm",
cancelButtonText: "取消", cancelButtonText: "Cancel",
type: "warning", type: "warning",
}) })
.then(async () => { .then(async () => {
const loading = this.$loading({ const loading = this.$loading({
lock: true, lock: true,
text: "正在删除中...", text: "Deleting...",
spinner: "el-icon-loading", spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)", background: "rgba(0, 0, 0, 0.7)",
}); });
@ -209,29 +209,29 @@ export default {
if (failCount === 0) { if (failCount === 0) {
this.$message.success({ this.$message.success({
message: `成功删除${successCount}个用户`, message: `Successfully deleted ${successCount} users`,
showClose: true showClose: true
}); });
} else if (successCount === 0) { } else if (successCount === 0) {
this.$message.error({ this.$message.error({
message: '删除失败,请重试', message: 'Deletion failed, please try again',
showClose: true showClose: true
}); });
} else { } else {
this.$message.warning( this.$message.warning(
`成功删除${successCount}个用户,${failCount}个删除失败` `Successfully deleted ${successCount} users, ${failCount} failed`
); );
} }
this.fetchUsers(); this.fetchUsers();
} catch (error) { } catch (error) {
this.$message.error("删除过程中发生错误"); this.$message.error("An error occurred during deletion");
} finally { } finally {
loading.close(); loading.close();
} }
}) })
.catch(() => { .catch(() => {
this.$message.info("已取消删除"); this.$message.info("Deletion cancelled");
}); });
}, },
batchEnable() { batchEnable() {
@ -243,16 +243,16 @@ export default {
this.handleChangeStatus(selectedUsers, 0); this.handleChangeStatus(selectedUsers, 0);
}, },
resetPassword(row) { resetPassword(row) {
this.$confirm("重置后将会生成新密码,是否继续?", "提示", { this.$confirm("A new password will be generated after reset. Continue?", "Confirm", {
confirmButtonText: "确定", confirmButtonText: "Confirm",
cancelButtonText: "取消", cancelButtonText: "Cancel",
}).then(() => { }).then(() => {
Api.admin.resetUserPassword(row.userid, ({ data }) => { Api.admin.resetUserPassword(row.userid, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.currentPassword = data.data; this.currentPassword = data.data;
this.showViewPassword = true; this.showViewPassword = true;
this.$message.success({ this.$message.success({
message: "密码已重置,请通知用户使用新密码登录", message: "Password has been reset. Please notify the user to login with the new password",
showClose: true showClose: true
}); });
} }
@ -260,22 +260,22 @@ export default {
}); });
}, },
deleteUser(row) { deleteUser(row) {
this.$confirm("确定要删除该用户吗?", "警告", { this.$confirm("Are you sure you want to delete this user?", "Warning", {
confirmButtonText: "确定", confirmButtonText: "Confirm",
cancelButtonText: "取消", cancelButtonText: "Cancel",
type: "warning", type: "warning",
}) })
.then(() => { .then(() => {
Api.admin.deleteUser(row.userid, ({ data }) => { Api.admin.deleteUser(row.userid, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: "删除成功", message: "Deleted successfully",
showClose: true showClose: true
}); });
this.fetchUsers(); this.fetchUsers();
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || "删除失败", message: data.msg || "Failed to delete",
showClose: true showClose: true
}); });
} }
@ -304,38 +304,38 @@ export default {
this.fetchUsers(); this.fetchUsers();
}, },
handleChangeStatus(row, status) { handleChangeStatus(row, status) {
// 处理单个用户或用户数组 // Handle single user or user array
const users = Array.isArray(row) ? row : [row]; const users = Array.isArray(row) ? row : [row];
const confirmText = status === 0 ? '禁用' : '启用'; const confirmText = status === 0 ? 'disable' : 'enable';
const userCount = users.length; const userCount = users.length;
this.$confirm(`确定要${confirmText}选中的${userCount}个用户吗?`, '提示', { this.$confirm(`Are you sure you want to ${confirmText} ${userCount} selected users?`, 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
const userIds = users.map(user => user.userid); const userIds = users.map(user => user.userid);
if (userIds.some(id => isNaN(id))) { if (userIds.some(id => isNaN(id))) {
this.$message.error('存在无效的用户ID'); this.$message.error('Invalid user IDs found');
return; return;
} }
Api.user.changeUserStatus(status, userIds, ({ data }) => { Api.user.changeUserStatus(status, userIds, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: `成功${confirmText}${userCount}个用户`, message: `Successfully ${confirmText}d ${userCount} users`,
showClose: true showClose: true
}); });
this.fetchUsers(); // 刷新用户列表 this.fetchUsers(); // Refresh user list
} else { } else {
this.$message.error({ this.$message.error({
message: '操作失败,请重试', message: 'Operation failed, please try again',
showClose: true showClose: true
}); });
} }
}); });
}).catch(() => { }).catch(() => {
// 用户取消操作 // User cancelled operation
}); });
}, },
}, },

View file

@ -1,19 +1,19 @@
<template> <template>
<div class="welcome"> <div class="welcome">
<!-- 公共头部 --> <!-- Common header -->
<HeaderBar :devices="devices" @search="handleSearch" @search-reset="handleSearchReset" /> <HeaderBar :devices="devices" @search="handleSearch" @search-reset="handleSearchReset" />
<el-main style="padding: 20px;display: flex;flex-direction: column;"> <el-main style="padding: 20px;display: flex;flex-direction: column;">
<div> <div>
<!-- 首页内容 --> <!-- Home page content -->
<div class="add-device"> <div class="add-device">
<div class="add-device-bg"> <div class="add-device-bg">
<div class="hellow-text" style="margin-top: 30px;"> <div class="hellow-text" style="margin-top: 30px;">
你好,小智 Hello, Xiaozhi
</div> </div>
<div class="hellow-text"> <div class="hellow-text">
让我们度过 Let's have
<div style="display: inline-block;color: #5778FF;"> <div style="display: inline-block;color: #5778FF;">
美好的一天! a wonderful day!
</div> </div>
</div> </div>
<div class="hi-hint"> <div class="hi-hint">
@ -21,7 +21,7 @@
</div> </div>
<div class="add-device-btn"> <div class="add-device-btn">
<div class="left-add" @click="showAddDialog"> <div class="left-add" @click="showAddDialog">
添加智能体 Add Agent
</div> </div>
<div style="width: 23px;height: 13px;background: #5778ff;margin-left: -10px;" /> <div style="width: 23px;height: 13px;background: #5778ff;margin-left: -10px;" />
<div class="right-add"> <div class="right-add">
@ -92,7 +92,7 @@ export default {
this.addDeviceDialogVisible = true this.addDeviceDialogVisible = true
}, },
goToRoleConfig() { goToRoleConfig() {
// 点击配置角色后跳转到角色配置页 // Navigate to role configuration page after clicking configure role
this.$router.push('/role-config') this.$router.push('/role-config')
}, },
handleWisdomBodyAdded(res) { handleWisdomBodyAdded(res) {
@ -122,11 +122,11 @@ export default {
return this.searchRegex.test(device.agentName); return this.searchRegex.test(device.agentName);
}); });
}, },
// 搜索更新智能体列表 // Search and update agent list
handleSearchResult(filteredList) { handleSearchResult(filteredList) {
this.devices = filteredList; // 更新设备列表 this.devices = filteredList; // Update device list
}, },
// 获取智能体列表 // Get agent list
fetchAgentList() { fetchAgentList() {
this.isLoading = true; this.isLoading = true;
Api.agent.getAgentList(({ data }) => { Api.agent.getAgentList(({ data }) => {
@ -136,10 +136,10 @@ export default {
agentId: item.id agentId: item.id
})); }));
// 动态设置骨架屏数量(可选) // Dynamically set skeleton screen count (optional)
this.skeletonCount = Math.min( this.skeletonCount = Math.min(
Math.max(this.originalDevices.length, 3), // 最少3个 Math.max(this.originalDevices.length, 3), // At least 3
10 // 最多10个 10 // At most 10
); );
this.handleSearchReset(); this.handleSearchReset();
@ -150,23 +150,23 @@ export default {
this.isLoading = false; this.isLoading = false;
}); });
}, },
// 删除智能体 // Delete agent
handleDeleteAgent(agentId) { handleDeleteAgent(agentId) {
this.$confirm('确定要删除该智能体吗?', '提示', { this.$confirm('Are you sure you want to delete this agent?', 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
Api.agent.deleteAgent(agentId, (res) => { Api.agent.deleteAgent(agentId, (res) => {
if (res.data.code === 0) { if (res.data.code === 0) {
this.$message.success({ this.$message.success({
message: '删除成功', message: 'Deletion successful',
showClose: true showClose: true
}); });
this.fetchAgentList(); // 刷新列表 this.fetchAgentList(); // Refresh list
} else { } else {
this.$message.error({ this.$message.error({
message: res.data.msg || '删除失败', message: res.data.msg || 'Deletion failed',
showClose: true showClose: true
}); });
} }
@ -191,13 +191,13 @@ export default {
flex-direction: column; flex-direction: column;
background: linear-gradient(145deg, #e6eeff, #eff0ff); background: linear-gradient(145deg, #e6eeff, #eff0ff);
background-size: cover; background-size: cover;
/* 确保背景图像覆盖整个元素 */ /* Ensure the background image covers the entire element */
background-position: center; background-position: center;
/* 从顶部中心对齐 */ /* Align from top center */
-webkit-background-size: cover; -webkit-background-size: cover;
/* 兼容老版本WebKit浏览器 */ /* Compatible with older WebKit browsers */
-o-background-size: cover; -o-background-size: cover;
/* 兼容老版本Opera浏览器 */ /* Compatible with older Opera browsers */
} }
.add-device { .add-device {
@ -218,15 +218,15 @@ export default {
background-image: url("@/assets/home/main-top-bg.png"); background-image: url("@/assets/home/main-top-bg.png");
overflow: hidden; overflow: hidden;
background-size: cover; background-size: cover;
/* 确保背景图像覆盖整个元素 */ /* Ensure the background image covers the entire element */
background-position: center; background-position: center;
/* 从顶部中心对齐 */ /* Align from top center */
-webkit-background-size: cover; -webkit-background-size: cover;
/* 兼容老版本WebKit浏览器 */ /* Compatible with older WebKit browsers */
-o-background-size: cover; -o-background-size: cover;
box-sizing: border-box; box-sizing: border-box;
/* 兼容老版本Opera浏览器 */ /* Compatible with older Opera browsers */
.hellow-text { .hellow-text {
margin-left: 75px; margin-left: 75px;
color: #3d4566; color: #3d4566;
@ -283,10 +283,10 @@ export default {
padding: 30px 0; padding: 30px 0;
} }
/* 在 DeviceItem.vue 的样式中 */ /* In DeviceItem.vue styles */
.device-item { .device-item {
margin: 0 !important; margin: 0 !important;
/* 避免冲突 */ /* Avoid conflicts */
width: auto !important; width: auto !important;
} }
@ -297,10 +297,10 @@ export default {
padding-top: 30px; padding-top: 30px;
color: #979db1; color: #979db1;
text-align: center; text-align: center;
/* 居中显示 */ /* Center display */
} }
/* 骨架屏动画 */ /* Skeleton screen animation */
@keyframes shimmer { @keyframes shimmer {
100% { 100% {
transform: translateX(100%); transform: translateX(100%);

View file

@ -14,7 +14,7 @@
<div class="login-box" @keyup.enter="login"> <div class="login-box" @keyup.enter="login">
<div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;"> <div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;">
<img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" /> <img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" />
<div class="login-text">登录</div> <div class="login-text">Login</div>
<div class="login-welcome"> <div class="login-welcome">
WELCOME TO LOGIN WELCOME TO LOGIN
</div> </div>
@ -24,7 +24,7 @@
<template v-if="!isMobileLogin"> <template v-if="!isMobileLogin">
<div class="input-box"> <div class="input-box">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/username.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/username.png" />
<el-input v-model="form.username" placeholder="请输入用户名" /> <el-input v-model="form.username" placeholder="Please enter username" />
</div> </div>
</template> </template>
@ -36,48 +36,48 @@
<el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`" <el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`"
:value="item.key" /> :value="item.key" />
</el-select> </el-select>
<el-input v-model="form.mobile" placeholder="请输入手机号码" /> <el-input v-model="form.mobile" placeholder="Please enter phone number" />
</div> </div>
</div> </div>
</template> </template>
<div class="input-box"> <div class="input-box">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
<el-input v-model="form.password" placeholder="请输入密码" type="password" /> <el-input v-model="form.password" placeholder="Please enter password" type="password" />
</div> </div>
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;"> <div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;"> <div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" />
<el-input v-model="form.captcha" placeholder="请输入验证码" style="flex: 1;" /> <el-input v-model="form.captcha" placeholder="Please enter verification code" style="flex: 1;" />
</div> </div>
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="验证码" <img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="Verification Code"
style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" /> style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" />
</div> </div>
<div <div
style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;display: flex;justify-content: space-between;margin-top: 20px;"> style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;display: flex;justify-content: space-between;margin-top: 20px;">
<div v-if="allowUserRegister" style="cursor: pointer;" @click="goToRegister">新用户注册</div> <div v-if="allowUserRegister" style="cursor: pointer;" @click="goToRegister">New User Registration</div>
<div style="cursor: pointer;" @click="goToForgetPassword" v-if="enableMobileRegister">忘记密码?</div> <div style="cursor: pointer;" @click="goToForgetPassword" v-if="enableMobileRegister">Forgot Password?</div>
</div> </div>
</div> </div>
<div class="login-btn" @click="login">登录</div> <div class="login-btn" @click="login">Login</div>
<!-- 登录方式切换按钮 --> <!-- 登录方式切换按钮 -->
<div class="login-type-container" v-if="enableMobileRegister"> <div class="login-type-container" v-if="enableMobileRegister">
<el-tooltip content="手机号码登录" placement="bottom"> <el-tooltip content="Login with Phone Number" placement="bottom">
<el-button :type="isMobileLogin ? 'primary' : 'default'" icon="el-icon-mobile" circle <el-button :type="isMobileLogin ? 'primary' : 'default'" icon="el-icon-mobile" circle
@click="switchLoginType('mobile')"></el-button> @click="switchLoginType('mobile')"></el-button>
</el-tooltip> </el-tooltip>
<el-tooltip content="用户名登录" placement="bottom"> <el-tooltip content="Login with Username" placement="bottom">
<el-button :type="!isMobileLogin ? 'primary' : 'default'" icon="el-icon-user" circle <el-button :type="!isMobileLogin ? 'primary' : 'default'" icon="el-icon-user" circle
@click="switchLoginType('username')"></el-button> @click="switchLoginType('username')"></el-button>
</el-tooltip> </el-tooltip>
</div> </div>
<div style="font-size: 14px;color: #979db1;"> <div style="font-size: 14px;color: #979db1;">
登录即同意 By logging in, you agree to
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《用户协议》</div> <div style="display: inline-block;color: #5778FF;cursor: pointer;">"User Agreement"</div>
和 and
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《隐私政策》</div> <div style="display: inline-block;color: #5778FF;cursor: pointer;">"Privacy Policy"</div>
</div> </div>
</div> </div>
</el-main> </el-main>
@ -143,7 +143,7 @@ export default {
const blob = new Blob([res.data], { type: res.data.type }); const blob = new Blob([res.data], { type: res.data.type });
this.captchaUrl = URL.createObjectURL(blob); this.captchaUrl = URL.createObjectURL(blob);
} else { } else {
showDanger('验证码加载失败,点击刷新'); showDanger('Failed to load verification code, click to refresh');
} }
}); });
} }
@ -173,35 +173,35 @@ export default {
if (this.isMobileLogin) { if (this.isMobileLogin) {
// 手机号登录验证 // 手机号登录验证
if (!validateMobile(this.form.mobile, this.form.areaCode)) { if (!validateMobile(this.form.mobile, this.form.areaCode)) {
showDanger('请输入正确的手机号码'); showDanger('Please enter a valid phone number');
return; return;
} }
// 拼接手机号作为用户名 // 拼接手机号作为用户名
this.form.username = this.form.areaCode + this.form.mobile; this.form.username = this.form.areaCode + this.form.mobile;
} else { } else {
// 用户名登录验证 // 用户名登录验证
if (!this.validateInput(this.form.username, '用户名不能为空')) { if (!this.validateInput(this.form.username, 'Username cannot be empty')) {
return; return;
} }
} }
// 验证密码 // 验证密码
if (!this.validateInput(this.form.password, '密码不能为空')) { if (!this.validateInput(this.form.password, 'Password cannot be empty')) {
return; return;
} }
// 验证验证码 // 验证验证码
if (!this.validateInput(this.form.captcha, '验证码不能为空')) { if (!this.validateInput(this.form.captcha, 'Verification code cannot be empty')) {
return; return;
} }
this.form.captchaId = this.captchaUuid this.form.captchaId = this.captchaUuid
Api.user.login(this.form, ({ data }) => { Api.user.login(this.form, ({ data }) => {
showSuccess('登录成功!'); showSuccess('Login successful!');
this.$store.commit('setToken', JSON.stringify(data.data)); this.$store.commit('setToken', JSON.stringify(data.data));
goToPage('/home'); goToPage('/home');
}, (err) => { }, (err) => {
showDanger(err.data.msg || '登录失败') showDanger(err.data.msg || 'Login failed')
if (err.data != null && err.data.msg != null && err.data.msg.indexOf('图形验证码') > -1) { if (err.data != null && err.data.msg != null && err.data.msg.indexOf('verification code') > -1) {
this.fetchCaptcha() this.fetchCaptcha()
} }
}) })

View file

@ -16,7 +16,7 @@
<!-- 修改标题部分 --> <!-- 修改标题部分 -->
<div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;"> <div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;">
<img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" /> <img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" />
<div class="login-text">注册</div> <div class="login-text">Register</div>
<div class="login-welcome"> <div class="login-welcome">
WELCOME TO REGISTER WELCOME TO REGISTER
</div> </div>
@ -27,7 +27,7 @@
<!-- 用户名/手机号输入框 --> <!-- 用户名/手机号输入框 -->
<div class="input-box" v-if="!enableMobileRegister"> <div class="input-box" v-if="!enableMobileRegister">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/username.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/username.png" />
<el-input v-model="form.username" placeholder="请输入用户名" /> <el-input v-model="form.username" placeholder="Please enter username" />
</div> </div>
<!-- 手机号注册部分 --> <!-- 手机号注册部分 -->
@ -38,16 +38,16 @@
<el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`" <el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`"
:value="item.key" /> :value="item.key" />
</el-select> </el-select>
<el-input v-model="form.mobile" placeholder="请输入手机号码" /> <el-input v-model="form.mobile" placeholder="Please enter mobile number" />
</div> </div>
</div> </div>
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;"> <div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;"> <div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" />
<el-input v-model="form.captcha" placeholder="请输入验证码" style="flex: 1;" /> <el-input v-model="form.captcha" placeholder="Please enter verification code" style="flex: 1;" />
</div> </div>
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="验证码" <img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="Verification Code"
style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" /> style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" />
</div> </div>
@ -56,12 +56,12 @@
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;"> <div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;"> <div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/phone.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/phone.png" />
<el-input v-model="form.mobileCaptcha" placeholder="请输入手机验证码" style="flex: 1;" maxlength="6" /> <el-input v-model="form.mobileCaptcha" placeholder="Please enter mobile verification code" style="flex: 1;" maxlength="6" />
</div> </div>
<el-button type="primary" class="send-captcha-btn" :disabled="!canSendMobileCaptcha" <el-button type="primary" class="send-captcha-btn" :disabled="!canSendMobileCaptcha"
@click="sendMobileCaptcha"> @click="sendMobileCaptcha">
<span> <span>
{{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }} {{ countdown > 0 ? `Retry in ${countdown}s` : 'Send Code' }}
</span> </span>
</el-button> </el-button>
</div> </div>
@ -70,13 +70,13 @@
<!-- 密码输入框 --> <!-- 密码输入框 -->
<div class="input-box"> <div class="input-box">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
<el-input v-model="form.password" placeholder="请输入密码" type="password" /> <el-input v-model="form.password" placeholder="Please enter password" type="password" />
</div> </div>
<!-- 新增确认密码 --> <!-- 新增确认密码 -->
<div class="input-box"> <div class="input-box">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
<el-input v-model="form.confirmPassword" placeholder="请确认密码" type="password" /> <el-input v-model="form.confirmPassword" placeholder="Please confirm password" type="password" />
</div> </div>
<!-- 验证码部分保持相同 --> <!-- 验证码部分保持相同 -->
@ -92,20 +92,20 @@
<!-- 修改底部链接 --> <!-- 修改底部链接 -->
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;margin-top: 20px;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;margin-top: 20px;">
<div style="cursor: pointer;" @click="goToLogin">已有账号?立即登录</div> <div style="cursor: pointer;" @click="goToLogin">Already have an account? Sign in now</div>
</div> </div>
</form> </form>
</div> </div>
<!-- 修改按钮文本 --> <!-- 修改按钮文本 -->
<div class="login-btn" @click="register">立即注册</div> <div class="login-btn" @click="register">Register Now</div>
<!-- 保持相同的协议声明 --> <!-- 保持相同的协议声明 -->
<div style="font-size: 14px;color: #979db1;"> <div style="font-size: 14px;color: #979db1;">
注册即同意 Registration implies agreement to
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《用户协议》</div> <div style="display: inline-block;color: #5778FF;cursor: pointer;">User Agreement</div>
和 and
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《隐私政策》</div> <div style="display: inline-block;color: #5778FF;cursor: pointer;">Privacy Policy</div>
</div> </div>
</div> </div>
</el-main> </el-main>
@ -159,7 +159,7 @@ export default {
mounted() { mounted() {
this.$store.dispatch('fetchPubConfig').then(() => { this.$store.dispatch('fetchPubConfig').then(() => {
if (!this.allowUserRegister) { if (!this.allowUserRegister) {
showDanger('当前不允许普通用户注册'); showDanger('User registration is currently not allowed');
setTimeout(() => { setTimeout(() => {
goToPage('/login'); goToPage('/login');
}, 1500); }, 1500);
@ -177,13 +177,13 @@ export default {
this.captchaUrl = URL.createObjectURL(blob); this.captchaUrl = URL.createObjectURL(blob);
} else { } else {
console.error('验证码加载异常:', error); console.error('Verification code loading error:', error);
showDanger('验证码加载失败,点击刷新'); showDanger('Failed to load verification code, click to refresh');
} }
}); });
}, },
// 封装输入验证逻辑 // Encapsulated input validation logic
validateInput(input, message) { validateInput(input, message) {
if (!input.trim()) { if (!input.trim()) {
showDanger(message); showDanger(message);
@ -195,23 +195,23 @@ export default {
// 发送手机验证码 // 发送手机验证码
sendMobileCaptcha() { sendMobileCaptcha() {
if (!validateMobile(this.form.mobile, this.form.areaCode)) { if (!validateMobile(this.form.mobile, this.form.areaCode)) {
showDanger('请输入正确的手机号码'); showDanger('Please enter a valid mobile number');
return; return;
} }
// 验证图形验证码 // Validate image verification code
if (!this.validateInput(this.form.captcha, '请输入图形验证码')) { if (!this.validateInput(this.form.captcha, 'Please enter image verification code')) {
this.fetchCaptcha(); this.fetchCaptcha();
return; return;
} }
// 清除可能存在的旧定时器 // Clear any existing old timer
if (this.timer) { if (this.timer) {
clearInterval(this.timer); clearInterval(this.timer);
this.timer = null; this.timer = null;
} }
// 开始倒计时 // Start countdown
this.countdown = 60; this.countdown = 60;
this.timer = setInterval(() => { this.timer = setInterval(() => {
if (this.countdown > 0) { if (this.countdown > 0) {
@ -222,49 +222,49 @@ export default {
} }
}, 1000); }, 1000);
// 调用发送验证码接口 // Call send verification code API
Api.user.sendSmsVerification({ Api.user.sendSmsVerification({
phone: this.form.areaCode + this.form.mobile, phone: this.form.areaCode + this.form.mobile,
captcha: this.form.captcha, captcha: this.form.captcha,
captchaId: this.form.captchaId captchaId: this.form.captchaId
}, (res) => { }, (res) => {
showSuccess('验证码发送成功'); showSuccess('Verification code sent successfully');
}, (err) => { }, (err) => {
showDanger(err.data.msg || '验证码发送失败'); showDanger(err.data.msg || 'Failed to send verification code');
this.countdown = 0; this.countdown = 0;
this.fetchCaptcha(); this.fetchCaptcha();
}); });
}, },
// 注册逻辑 // Registration logic
register() { register() {
if (this.enableMobileRegister) { if (this.enableMobileRegister) {
// 手机号注册验证 // Mobile registration validation
if (!validateMobile(this.form.mobile, this.form.areaCode)) { if (!validateMobile(this.form.mobile, this.form.areaCode)) {
showDanger('请输入正确的手机号码'); showDanger('Please enter a valid mobile number');
return; return;
} }
if (!this.form.mobileCaptcha) { if (!this.form.mobileCaptcha) {
showDanger('请输入手机验证码'); showDanger('Please enter mobile verification code');
return; return;
} }
} else { } else {
// 用户名注册验证 // Username registration validation
if (!this.validateInput(this.form.username, '用户名不能为空')) { if (!this.validateInput(this.form.username, 'Username cannot be empty')) {
return; return;
} }
} }
// 验证密码 // Validate password
if (!this.validateInput(this.form.password, '密码不能为空')) { if (!this.validateInput(this.form.password, 'Password cannot be empty')) {
return; return;
} }
if (this.form.password !== this.form.confirmPassword) { if (this.form.password !== this.form.confirmPassword) {
showDanger('两次输入的密码不一致') showDanger('The two passwords entered do not match')
return return
} }
// 验证验证码 // Validate verification code
if (!this.validateInput(this.form.captcha, '验证码不能为空')) { if (!this.validateInput(this.form.captcha, 'Verification code cannot be empty')) {
return; return;
} }
@ -273,11 +273,11 @@ export default {
} }
Api.user.register(this.form, ({ data }) => { Api.user.register(this.form, ({ data }) => {
showSuccess('注册成功!') showSuccess('Registration successful!')
goToPage('/login') goToPage('/login')
}, (err) => { }, (err) => {
showDanger(err.data.msg || '注册失败') showDanger(err.data.msg || 'Registration failed')
if (err.data != null && err.data.msg != null && err.data.msg.indexOf('图形验证码') > -1) { if (err.data != null && err.data.msg != null && err.data.msg.indexOf('Image verification code') > -1) {
this.fetchCaptcha() this.fetchCaptcha()
} }
}) })

View file

@ -17,7 +17,7 @@
<!-- 修改标题部分 --> <!-- 修改标题部分 -->
<div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;"> <div style="display: flex;align-items: center;gap: 20px;margin-bottom: 39px;padding: 0 30px;">
<img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" /> <img loading="lazy" alt="" src="@/assets/login/hi.png" style="width: 34px;height: 34px;" />
<div class="login-text">重置密码</div> <div class="login-text">Reset Password</div>
<div class="login-welcome"> <div class="login-welcome">
PASSWORD RETRIEVE PASSWORD RETRIEVE
</div> </div>
@ -31,16 +31,16 @@
<el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`" <el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`"
:value="item.key" /> :value="item.key" />
</el-select> </el-select>
<el-input v-model="form.mobile" placeholder="请输入手机号码" /> <el-input v-model="form.mobile" placeholder="Please enter mobile number" />
</div> </div>
</div> </div>
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;"> <div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;"> <div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/shield.png" />
<el-input v-model="form.captcha" placeholder="请输入验证码" style="flex: 1;" /> <el-input v-model="form.captcha" placeholder="Please enter verification code" style="flex: 1;" />
</div> </div>
<img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="验证码" <img loading="lazy" v-if="captchaUrl" :src="captchaUrl" alt="Verification Code"
style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" /> style="width: 150px; height: 40px; cursor: pointer;" @click="fetchCaptcha" />
</div> </div>
@ -48,12 +48,12 @@
<div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;"> <div style="display: flex; align-items: center; margin-top: 20px; width: 100%; gap: 10px;">
<div class="input-box" style="width: calc(100% - 130px); margin-top: 0;"> <div class="input-box" style="width: calc(100% - 130px); margin-top: 0;">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/phone.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/phone.png" />
<el-input v-model="form.mobileCaptcha" placeholder="请输入手机验证码" style="flex: 1;" maxlength="6" /> <el-input v-model="form.mobileCaptcha" placeholder="Please enter mobile verification code" style="flex: 1;" maxlength="6" />
</div> </div>
<el-button type="primary" class="send-captcha-btn" :disabled="!canSendMobileCaptcha" <el-button type="primary" class="send-captcha-btn" :disabled="!canSendMobileCaptcha"
@click="sendMobileCaptcha"> @click="sendMobileCaptcha">
<span> <span>
{{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }} {{ countdown > 0 ? `Retry in ${countdown}s` : 'Send Code' }}
</span> </span>
</el-button> </el-button>
</div> </div>
@ -61,30 +61,30 @@
<!-- 新密码 --> <!-- 新密码 -->
<div class="input-box"> <div class="input-box">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
<el-input v-model="form.newPassword" placeholder="请输入新密码" type="password" /> <el-input v-model="form.newPassword" placeholder="Please enter new password" type="password" />
</div> </div>
<!-- 确认新密码 --> <!-- 确认新密码 -->
<div class="input-box"> <div class="input-box">
<img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" /> <img loading="lazy" alt="" class="input-icon" src="@/assets/login/password.png" />
<el-input v-model="form.confirmPassword" placeholder="请确认新密码" type="password" /> <el-input v-model="form.confirmPassword" placeholder="Please confirm new password" type="password" />
</div> </div>
<!-- 修改底部链接 --> <!-- 修改底部链接 -->
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;margin-top: 20px;"> <div style="font-weight: 400;font-size: 14px;text-align: left;color: #5778ff;margin-top: 20px;">
<div style="cursor: pointer;" @click="goToLogin">返回登录</div> <div style="cursor: pointer;" @click="goToLogin">Back to Login</div>
</div> </div>
</div> </div>
<!-- 修改按钮文本 --> <!-- 修改按钮文本 -->
<div class="login-btn" @click="retrievePassword">立即修改</div> <div class="login-btn" @click="retrievePassword">Reset Now</div>
<!-- 保持相同的协议声明 --> <!-- 保持相同的协议声明 -->
<div style="font-size: 14px;color: #979db1;"> <div style="font-size: 14px;color: #979db1;">
同意 Agree to
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《用户协议》</div> <div style="display: inline-block;color: #5778FF;cursor: pointer;">User Agreement</div>
和 and
<div style="display: inline-block;color: #5778FF;cursor: pointer;">《隐私政策》</div> <div style="display: inline-block;color: #5778FF;cursor: pointer;">Privacy Policy</div>
</div> </div>
</div> </div>
</form> </form>
@ -165,7 +165,7 @@ export default {
// 发送手机验证码 // 发送手机验证码
sendMobileCaptcha() { sendMobileCaptcha() {
if (!validateMobile(this.form.mobile, this.form.areaCode)) { if (!validateMobile(this.form.mobile, this.form.areaCode)) {
showDanger('请输入正确的手机号码'); showDanger('Please enter a valid mobile number');
return; return;
} }
@ -198,31 +198,31 @@ export default {
captcha: this.form.captcha, captcha: this.form.captcha,
captchaId: this.form.captchaId captchaId: this.form.captchaId
}, (res) => { }, (res) => {
showSuccess('验证码发送成功'); showSuccess('Verification code sent successfully');
}, (err) => { }, (err) => {
showDanger(err.data.msg || '验证码发送失败'); showDanger(err.data.msg || 'Failed to send verification code');
this.countdown = 0; this.countdown = 0;
this.fetchCaptcha(); this.fetchCaptcha();
}); });
}, },
// 修改逻辑 // Reset logic
retrievePassword() { retrievePassword() {
// 验证逻辑 // Validation logic
if (!validateMobile(this.form.mobile, this.form.areaCode)) { if (!validateMobile(this.form.mobile, this.form.areaCode)) {
showDanger('请输入正确的手机号码'); showDanger('Please enter a valid mobile number');
return; return;
} }
if (!this.form.captcha) { if (!this.form.captcha) {
showDanger('请输入图形验证码'); showDanger('Please enter image verification code');
return; return;
} }
if (!this.form.mobileCaptcha) { if (!this.form.mobileCaptcha) {
showDanger('请输入短信验证码'); showDanger('Please enter SMS verification code');
return; return;
} }
if (this.form.newPassword !== this.form.confirmPassword) { if (this.form.newPassword !== this.form.confirmPassword) {
showDanger('两次输入的密码不一致'); showDanger('The two passwords entered do not match');
return; return;
} }
@ -231,11 +231,11 @@ export default {
password: this.form.newPassword, password: this.form.newPassword,
code: this.form.mobileCaptcha code: this.form.mobileCaptcha
}, (res) => { }, (res) => {
showSuccess('密码重置成功'); showSuccess('Password reset successful');
goToPage('/login'); goToPage('/login');
}, (err) => { }, (err) => {
showDanger(err.data.msg || '重置失败'); showDanger(err.data.msg || 'Reset failed');
if (err.data != null && err.data.msg != null && err.data.msg.indexOf('图形验证码') > -1) { if (err.data != null && err.data.msg != null && err.data.msg.indexOf('Image verification code') > -1) {
this.fetchCaptcha() this.fetchCaptcha()
} }
}); });

View file

@ -3,7 +3,7 @@
<HeaderBar /> <HeaderBar />
<div class="operation-bar"> <div class="operation-bar">
<h2 class="page-title">角色配置</h2> <h2 class="page-title">Role Configuration</h2>
</div> </div>
<div class="main-wrapper"> <div class="main-wrapper">
@ -18,10 +18,10 @@
<div class="header-actions"> <div class="header-actions">
<div class="hint-text"> <div class="hint-text">
<img loading="lazy" src="@/assets/home/info.png" alt=""> <img loading="lazy" src="@/assets/home/info.png" alt="">
<span>保存配置后,需要重启设备,新的配置才会生效。</span> <span>After saving the configuration, you need to restart the device for the new configuration to take effect.</span>
</div> </div>
<el-button type="primary" class="save-btn" @click="saveConfig">保存配置</el-button> <el-button type="primary" class="save-btn" @click="saveConfig">Save Configuration</el-button>
<el-button class="reset-btn" @click="resetConfig">重置</el-button> <el-button class="reset-btn" @click="resetConfig">Reset</el-button>
<button class="custom-close-btn" @click="goToHome"> <button class="custom-close-btn" @click="goToHome">
× ×
</button> </button>
@ -33,10 +33,10 @@
<div class="form-content"> <div class="form-content">
<div class="form-grid"> <div class="form-grid">
<div class="form-column"> <div class="form-column">
<el-form-item label="助手昵称:"> <el-form-item label="Assistant Name:">
<el-input v-model="form.agentName" class="form-input" maxlength="10" /> <el-input v-model="form.agentName" class="form-input" maxlength="10" />
</el-form-item> </el-form-item>
<el-form-item label="角色模版:"> <el-form-item label="Role Template:">
<div class="template-container"> <div class="template-container">
<div v-for="(template, index) in templates" :key="`template-${index}`" class="template-item" <div v-for="(template, index) in templates" :key="`template-${index}`" class="template-item"
:class="{ 'template-loading': loadingTemplate }" @click="selectTemplate(template)"> :class="{ 'template-loading': loadingTemplate }" @click="selectTemplate(template)">
@ -44,39 +44,39 @@
</div> </div>
</div> </div>
</el-form-item> </el-form-item>
<el-form-item label="角色介绍:"> <el-form-item label="Role Introduction:">
<el-input type="textarea" rows="9" resize="none" placeholder="请输入内容" v-model="form.systemPrompt" <el-input type="textarea" rows="9" resize="none" placeholder="Please enter content" v-model="form.systemPrompt"
maxlength="2000" show-word-limit class="form-textarea" /> maxlength="2000" show-word-limit class="form-textarea" />
</el-form-item> </el-form-item>
<el-form-item label="记忆:"> <el-form-item label="Memory:">
<el-input type="textarea" rows="6" resize="none" v-model="form.summaryMemory" maxlength="2000" <el-input type="textarea" rows="6" resize="none" v-model="form.summaryMemory" maxlength="2000"
show-word-limit class="form-textarea" show-word-limit class="form-textarea"
:disabled="form.model.memModelId !== 'Memory_mem_local_short'" /> :disabled="form.model.memModelId !== 'Memory_mem_local_short'" />
</el-form-item> </el-form-item>
<el-form-item label="语言编码:" style="display: none;"> <el-form-item label="Language Code:" style="display: none;">
<el-input v-model="form.langCode" placeholder="请输入语言编码,如:zh_CN" maxlength="10" show-word-limit <el-input v-model="form.langCode" placeholder="Please enter language code, e.g.: en_US" maxlength="10" show-word-limit
class="form-input" /> class="form-input" />
</el-form-item> </el-form-item>
<el-form-item label="交互语种:" style="display: none;"> <el-form-item label="Interaction Language:" style="display: none;">
<el-input v-model="form.language" placeholder="请输入交互语种,如:中文" maxlength="10" show-word-limit <el-input v-model="form.language" placeholder="Please enter interaction language, e.g.: English" maxlength="10" show-word-limit
class="form-input" /> class="form-input" />
</el-form-item> </el-form-item>
</div> </div>
<div class="form-column"> <div class="form-column">
<div class="model-row"> <div class="model-row">
<el-form-item label="语音活动检测(VAD)" class="model-item"> <el-form-item label="Voice Activity Detection (VAD)" class="model-item">
<div class="model-select-wrapper"> <div class="model-select-wrapper">
<el-select v-model="form.model.vadModelId" filterable placeholder="请选择" class="form-select" <el-select v-model="form.model.vadModelId" filterable placeholder="Please select" class="form-select"
@change="handleModelChange('VAD', $event)"> @change="handleModelChange('VAD', $event)">
<el-option v-for="(item, optionIndex) in modelOptions['VAD']" <el-option v-for="(item, optionIndex) in modelOptions['VAD']"
:key="`option-vad-${optionIndex}`" :label="item.label" :value="item.value" /> :key="`option-vad-${optionIndex}`" :label="item.label" :value="item.value" />
</el-select> </el-select>
</div> </div>
</el-form-item> </el-form-item>
<el-form-item label="语音识别(ASR)" class="model-item"> <el-form-item label="Speech Recognition (ASR)" class="model-item">
<div class="model-select-wrapper"> <div class="model-select-wrapper">
<el-select v-model="form.model.asrModelId" filterable placeholder="请选择" class="form-select" <el-select v-model="form.model.asrModelId" filterable placeholder="Please select" class="form-select"
@change="handleModelChange('ASR', $event)"> @change="handleModelChange('ASR', $event)">
<el-option v-for="(item, optionIndex) in modelOptions['ASR']" <el-option v-for="(item, optionIndex) in modelOptions['ASR']"
:key="`option-asr-${optionIndex}`" :label="item.label" :value="item.value" /> :key="`option-asr-${optionIndex}`" :label="item.label" :value="item.value" />
@ -87,7 +87,7 @@
<el-form-item v-for="(model, index) in models.slice(2)" :key="`model-${index}`" :label="model.label" <el-form-item v-for="(model, index) in models.slice(2)" :key="`model-${index}`" :label="model.label"
class="model-item"> class="model-item">
<div class="model-select-wrapper"> <div class="model-select-wrapper">
<el-select v-model="form.model[model.key]" filterable placeholder="请选择" class="form-select" <el-select v-model="form.model[model.key]" filterable placeholder="Please select" class="form-select"
@change="handleModelChange(model.type, $event)"> @change="handleModelChange(model.type, $event)">
<el-option v-for="(item, optionIndex) in modelOptions[model.type]" <el-option v-for="(item, optionIndex) in modelOptions[model.type]"
:key="`option-${index}-${optionIndex}`" :label="item.label" :value="item.value" /> :key="`option-${index}-${optionIndex}`" :label="item.label" :value="item.value" />
@ -96,7 +96,7 @@
<el-tooltip v-for="func in currentFunctions" :key="func.name" effect="dark" placement="top" <el-tooltip v-for="func in currentFunctions" :key="func.name" effect="dark" placement="top"
popper-class="custom-tooltip"> popper-class="custom-tooltip">
<div slot="content"> <div slot="content">
<div><strong>功能名称:</strong> {{ func.name }}</div> <div><strong>Function Name:</strong> {{ func.name }}</div>
</div> </div>
<div class="icon-dot" :style="{ backgroundColor: getFunctionColor(func.name) }"> <div class="icon-dot" :style="{ backgroundColor: getFunctionColor(func.name) }">
{{ func.name.charAt(0) }} {{ func.name.charAt(0) }}
@ -104,20 +104,20 @@
</el-tooltip> </el-tooltip>
<el-button class="edit-function-btn" @click="openFunctionDialog" <el-button class="edit-function-btn" @click="openFunctionDialog"
:class="{ 'active-btn': showFunctionDialog }"> :class="{ 'active-btn': showFunctionDialog }">
编辑功能 Edit Functions
</el-button> </el-button>
</div> </div>
<div v-if="model.type === 'Memory' && form.model.memModelId !== 'Memory_nomem'" <div v-if="model.type === 'Memory' && form.model.memModelId !== 'Memory_nomem'"
class="chat-history-options"> class="chat-history-options">
<el-radio-group v-model="form.chatHistoryConf" @change="updateChatHistoryConf"> <el-radio-group v-model="form.chatHistoryConf" @change="updateChatHistoryConf">
<el-radio-button :label="1">上报文字</el-radio-button> <el-radio-button :label="1">Report Text</el-radio-button>
<el-radio-button :label="2">上报文字+语音</el-radio-button> <el-radio-button :label="2">Report Text + Audio</el-radio-button>
</el-radio-group> </el-radio-group>
</div> </div>
</div> </div>
</el-form-item> </el-form-item>
<el-form-item label="角色音色"> <el-form-item label="Voice Timbre:">
<el-select v-model="form.ttsVoiceId" placeholder="请选择" class="form-select"> <el-select v-model="form.ttsVoiceId" placeholder="Please select" class="form-select">
<el-option v-for="(item, index) in voiceOptions" :key="`voice-${index}`" :label="item.label" <el-option v-for="(item, index) in voiceOptions" :key="`voice-${index}`" :label="item.label"
:value="item.value" /> :value="item.value" />
</el-select> </el-select>
@ -167,13 +167,13 @@ export default {
} }
}, },
models: [ models: [
{ label: '语音活动检测(VAD)', key: 'vadModelId', type: 'VAD' }, { label: 'Voice Activity Detection (VAD)', key: 'vadModelId', type: 'VAD' },
{ label: '语音识别(ASR)', key: 'asrModelId', type: 'ASR' }, { label: 'Speech Recognition (ASR)', key: 'asrModelId', type: 'ASR' },
{ label: '大语言模型(LLM)', key: 'llmModelId', type: 'LLM' }, { label: 'Large Language Model (LLM)', key: 'llmModelId', type: 'LLM' },
{ label: '视觉大模型(VLLM)', key: 'vllmModelId', type: 'VLLM' }, { label: 'Vision Language Model (VLLM)', key: 'vllmModelId', type: 'VLLM' },
{ label: '意图识别(Intent)', key: 'intentModelId', type: 'Intent' }, { label: 'Intent Recognition (Intent)', key: 'intentModelId', type: 'Intent' },
{ label: '记忆(Memory)', key: 'memModelId', type: 'Memory' }, { label: 'Memory', key: 'memModelId', type: 'Memory' },
{ label: '语音合成(TTS)', key: 'ttsModelId', type: 'TTS' }, { label: 'Text-to-Speech (TTS)', key: 'ttsModelId', type: 'TTS' },
], ],
modelOptions: {}, modelOptions: {},
templates: [], templates: [],
@ -221,21 +221,21 @@ export default {
Api.agent.updateAgentConfig(this.$route.query.agentId, configData, ({ data }) => { Api.agent.updateAgentConfig(this.$route.query.agentId, configData, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
message: '配置保存成功', message: 'Configuration saved successfully',
showClose: true showClose: true
}); });
} else { } else {
this.$message.error({ this.$message.error({
message: data.msg || '配置保存失败', message: data.msg || 'Failed to save configuration',
showClose: true showClose: true
}); });
} }
}); });
}, },
resetConfig() { resetConfig() {
this.$confirm('确定要重置配置吗?', '提示', { this.$confirm('Are you sure you want to reset the configuration?', 'Confirm', {
confirmButtonText: '确定', confirmButtonText: 'Confirm',
cancelButtonText: '取消', cancelButtonText: 'Cancel',
type: 'warning' type: 'warning'
}).then(() => { }).then(() => {
this.form = { this.form = {
@ -260,7 +260,7 @@ export default {
} }
this.currentFunctions = []; this.currentFunctions = [];
this.$message.success({ this.$message.success({
message: '配置已重置', message: 'Configuration has been reset',
showClose: true showClose: true
}) })
}).catch(() => { }).catch(() => {
@ -271,7 +271,7 @@ export default {
if (data.code === 0) { if (data.code === 0) {
this.templates = data.data; this.templates = data.data;
} else { } else {
this.$message.error(data.msg || '获取模板列表失败'); this.$message.error(data.msg || 'Failed to get template list');
} }
}); });
}, },
@ -281,15 +281,15 @@ export default {
try { try {
this.applyTemplateData(template); this.applyTemplateData(template);
this.$message.success({ this.$message.success({
message: `「${template.agentName}」模板已应用`, message: `"${template.agentName}" template has been applied`,
showClose: true showClose: true
}); });
} catch (error) { } catch (error) {
this.$message.error({ this.$message.error({
message: '应用模板失败', message: 'Failed to apply template',
showClose: true showClose: true
}); });
console.error('应用模板失败:', error); console.error('Failed to apply template:', error);
} finally { } finally {
this.loadingTemplate = false; this.loadingTemplate = false;
} }
@ -358,7 +358,7 @@ export default {
this.originalFunctions = JSON.parse(JSON.stringify(this.currentFunctions)); this.originalFunctions = JSON.parse(JSON.stringify(this.currentFunctions));
}); });
} else { } else {
this.$message.error(data.msg || '获取配置失败'); this.$message.error(data.msg || 'Failed to get configuration');
} }
}); });
}, },
@ -371,7 +371,7 @@ export default {
label: item.modelName label: item.modelName
}))); })));
} else { } else {
this.$message.error(data.msg || '获取模型列表失败'); this.$message.error(data.msg || 'Failed to get model list');
} }
}); });
}); });
@ -425,7 +425,7 @@ export default {
}); });
resolve(); resolve();
} else { } else {
this.$message.error(data.msg || '获取插件列表失败'); this.$message.error(data.msg || 'Failed to get plugin list');
reject(); reject();
} }
}); });

View file

@ -1,78 +1,81 @@
# MQTT+UDP 到 WebSocket 桥接服务 # MQTT+UDP to WebSocket Bridge Service
## 项目概述 ## Project Overview
这是一个用于物联网设备通信的桥接服务,实现了MQTT和UDP协议到WebSocket的转换。该服务允许设备通过MQTT协议进行控制消息传输,同时通过UDP协议高效传输音频数据,并将这些数据桥接到WebSocket服务。 This is a bridge service for IoT device communication that implements conversion from MQTT and UDP protocols to WebSocket. The service allows devices to transmit control messages through MQTT protocol while efficiently transmitting audio data through UDP protocol, bridging this data to WebSocket services.
## 功能特点 ## Features
- **多协议支持**: 同时支持MQTT、UDP和WebSocket协议 - **Multi-protocol Support**: Simultaneous support for MQTT, UDP, and WebSocket protocols
- **音频数据传输**: 专为音频数据流优化的传输机制 - **Audio Data Transmission**: Transmission mechanism optimized for audio data streams
- **加密通信**: 使用AES-128-CTR加密UDP数据传输 - **Encrypted Communication**: Uses AES-128-CTR encryption for UDP data transmission
- **会话管理**: 完整的设备会话生命周期管理 - **Session Management**: Complete device session lifecycle management
- **自动重连**: 连接断开时自动重连机制 - **Auto Reconnection**: Automatic reconnection mechanism when connections are lost
- **心跳检测**: 定期检查连接活跃状态 - **Heartbeat Detection**: Periodic checking of connection active status
- **开发/生产环境配置**: 支持不同环境的配置切换 - **Development/Production Environment Configuration**: Support for configuration switching between different environments
## 技术架构 ## Technical Architecture
- **MQTT服务器**: 处理设备控制消息 - **MQTT Server**: Handles device control messages
- **UDP服务器**: 处理高效的音频数据传输 - **UDP Server**: Handles efficient audio data transmission
- **WebSocket客户端**: 连接到聊天服务器 - **WebSocket Client**: Connects to chat servers
- **桥接层**: 在不同协议间转换和路由消息 - **Bridge Layer**: Converts and routes messages between different protocols
## 项目结构 ## Project Structure
``` ```
├── app.js # 主应用入口 ├── app.js # Main application entry point
├── mqtt-protocol.js # MQTT协议实现 ├── mqtt-protocol.js # MQTT protocol implementation
├── ecosystem.config.js # PM2配置文件 ├── ecosystem.config.js # PM2 configuration file
├── package.json # 项目依赖 ├── package.json # Project dependencies
├── .env # 环境变量配置 ├── .env # Environment variable configuration
├── utils/ ├── utils/
│ ├── config-manager.js # 配置管理工具 │ ├── config-manager.js # Configuration management tool
│ ├── mqtt_config_v2.js # MQTT配置验证工具 │ ├── mqtt_config_v2.js # MQTT configuration validation tool
│ └── weixinAlert.js # 微信告警工具 │ └── weixinAlert.js # WeChat alert tool
└── config/ # 配置文件目录 └── config/ # Configuration file directory
``` ```
## 依赖项 ## Dependencies
- **debug**: 调试日志输出 - **debug**: Debug log output
- **dotenv**: 环境变量管理 - **dotenv**: Environment variable management
- **ws**: WebSocket客户端 - **ws**: WebSocket client
- **events**: Node.js 事件模块 - **events**: Node.js event module
## 安装要求 ## Installation Requirements
- Node.js 14.x 或更高版本 - Node.js 14.x or higher
- npm 或 yarn 包管理器 - npm or yarn package manager
- PM2 (用于生产环境部署) - PM2 (for production environment deployment)
## 安装步骤 ## Installation Steps
1. Clone repository
1. 克隆仓库
```bash ```bash
git clone <仓库地址> git clone <repository-url>
cd mqtt-websocket-bridge cd mqtt-websocket-bridge
``` ```
2. 安装依赖 2. Install dependencies
```bash ```bash
npm install npm install
``` ```
3. 创建配置文件 3. Create configuration file
```bash ```bash
mkdir -p config mkdir -p config
cp config/mqtt.json.example config/mqtt.json cp config/mqtt.json.example config/mqtt.json
``` ```
4. 编辑配置文件 `config/mqtt.json`,设置适当的参数 4. Edit configuration file `config/mqtt.json` and set appropriate parameters
## 配置说明 ## Configuration Instructions
配置文件 `config/mqtt.json` 需要包含以下内容: Configuration file `config/mqtt.json` needs to contain the following content:
```json ```json
{ {
@ -87,63 +90,65 @@ cp config/mqtt.json.example config/mqtt.json
} }
``` ```
## 环境变量 ## Environment Variables
创建 `.env` 文件并设置以下环境变量: Create `.env` file and set the following environment variables:
``` ```
MQTT_PORT=1883 # MQTT服务器端口 MQTT_PORT=1883 # MQTT server port
UDP_PORT=8884 # UDP服务器端口 UDP_PORT=8884 # UDP server port
PUBLIC_IP=your-ip # 服务器公网IP PUBLIC_IP=your-ip # Server public IP
``` ```
## 运行服务 ## Running the Service
### 开发环境 ### Development Environment
```bash ```bash
# 直接运行 # Run directly
node app.js node app.js
# 调试模式运行 # Run in debug mode
DEBUG=mqtt-server node app.js DEBUG=mqtt-server node app.js
``` ```
### 生产环境 (使用PM2) ### Production Environment (Using PM2)
```bash ```bash
# 安装PM2 # Install PM2
npm install -g pm2 npm install -g pm2
# 启动服务 # Start service
pm2 start ecosystem.config.js pm2 start ecosystem.config.js
# 查看日志 # View logs
pm2 logs xz-mqtt pm2 logs xz-mqtt
# 监控服务 # Monitor service
pm2 monit pm2 monit
``` ```
服务将在以下端口启动: The service will start on the following ports:
- MQTT 服务器: 端口 1883 (可通过环境变量修改)
- UDP 服务器: 端口 8884 (可通过环境变量修改)
## 协议说明 - MQTT Server: Port 1883 (can be modified via environment variables)
- UDP Server: Port 8884 (can be modified via environment variables)
### 设备连接流程 ## Protocol Description
1. 设备通过MQTT协议连接到服务器 ### Device Connection Flow
2. 设备发送 `hello` 消息,包含音频参数和特性
3. 服务器创建WebSocket连接到聊天服务器
4. 服务器返回UDP连接参数给设备
5. 设备通过UDP发送音频数据
6. 服务器将音频数据转发到WebSocket
7. WebSocket返回的控制消息通过MQTT发送给设备
### 消息格式 1. Device connects to server via MQTT protocol
2. Device sends `hello` message containing audio parameters and features
3. Server creates WebSocket connection to chat server
4. Server returns UDP connection parameters to device
5. Device sends audio data via UDP
6. Server forwards audio data to WebSocket
7. Control messages returned by WebSocket are sent to device via MQTT
### Message Format
#### Hello Message (Device -> Server)
#### Hello 消息 (设备 -> 服务器)
```json ```json
{ {
"type": "hello", "type": "hello",
@ -153,7 +158,8 @@ pm2 monit
} }
``` ```
#### Hello 响应 (服务器 -> 设备) #### Hello Response (Server -> Device)
```json ```json
{ {
"type": "hello", "type": "hello",
@ -171,45 +177,45 @@ pm2 monit
} }
``` ```
## 安全说明 ## Security Description
- UDP通信使用AES-128-CTR加密 - UDP communication uses AES-128-CTR encryption
- 每个会话使用唯一的加密密钥 - Each session uses a unique encryption key
- 使用序列号防止重放攻击 - Uses sequence numbers to prevent replay attacks
- 设备通过MAC地址进行身份验证 - Device authentication via MAC address
- 支持设备分组和UUID验证 - Supports device grouping and UUID verification
## 性能优化 ## Performance Optimization
- 使用预分配的缓冲区减少内存分配 - Uses pre-allocated buffers to reduce memory allocation
- UDP协议用于高效传输音频数据 - UDP protocol for efficient audio data transmission
- 定期清理不活跃的连接 - Periodic cleanup of inactive connections
- 连接数和活跃连接数监控 - Connection count and active connection monitoring
- 支持多聊天服务器负载均衡 - Support for multi-chat server load balancing
## 故障排除 ## Troubleshooting
- 检查设备MAC地址格式是否正确 - Check if device MAC address format is correct
- 确保UDP端口在防火墙中开放 - Ensure UDP port is open in firewall
- 启用调试模式查看详细日志 - Enable debug mode to view detailed logs
- 检查配置文件中的聊天服务器地址是否正确 - Check if chat server address in configuration file is correct
- 验证设备认证信息是否正确 - Verify device authentication information is correct
## 开发指南 ## Development Guide
### 添加新功能 ### Adding New Features
1. 修改 `mqtt-protocol.js` 以支持新的MQTT功能 1. Modify `mqtt-protocol.js` to support new MQTT functionality
2. 在 `MQTTConnection` 类中添加新的消息处理方法 2. Add new message handling methods in `MQTTConnection` class
3. 更新配置管理器以支持新的配置选项 3. Update configuration manager to support new configuration options
4. 在 `WebSocketBridge` 类中添加新的WebSocket处理逻辑 4. Add new WebSocket handling logic in `WebSocketBridge` class
### 调试技巧 ### Debugging Tips
```bash ```bash
# 启用所有调试输出 # Enable all debug output
DEBUG=* node app.js DEBUG=* node app.js
# 只启用MQTT服务器调试 # Enable only MQTT server debugging
DEBUG=mqtt-server node app.js DEBUG=mqtt-server node app.js
``` ```

File diff suppressed because it is too large Load diff

View file

@ -1,81 +1,78 @@
#!/usr/bin/env node #!/usr/bin/env node
/**
* MQTT签名密钥生成器
* 用于生成MQTT_SIGNATURE_KEY环境变量
*/
/**
* MQTT signature key generator
* Used to generate MQTT_SIGNATURE_KEY environment variable
*/
const crypto = require('crypto'); const crypto = require('crypto');
function generateSecureKey(length = 32) { function generateSecureKey(length = 32) {
// 生成随机字节 // Generate random bytes
const randomBytes = crypto.randomBytes(length); const randomBytes = crypto.randomBytes(length);
// Convert to base64 string
// 转换为base64字符串
const base64Key = randomBytes.toString('base64'); const base64Key = randomBytes.toString('base64');
return base64Key; return base64Key;
} }
function generateHexKey(length = 32) { function generateHexKey(length = 32) {
// 生成随机字节 // Generate random bytes
const randomBytes = crypto.randomBytes(length); const randomBytes = crypto.randomBytes(length);
// Convert to hexadecimal string
// 转换为十六进制字符串
const hexKey = randomBytes.toString('hex'); const hexKey = randomBytes.toString('hex');
return hexKey; return hexKey;
} }
function generateUUIDKey() { function generateUUIDKey() {
// 使用UUID v4作为密钥 // Use UUID v4 as key
const uuid = crypto.randomUUID(); const uuid = crypto.randomUUID();
return uuid; return uuid;
} }
console.log('='.repeat(60)); console.log('='.repeat(60));
console.log('MQTT签名密钥生成器'); console.log('MQTT Signature Key Generator');
console.log('='.repeat(60)); console.log('='.repeat(60));
console.log('\n1. Base64格式密钥 (推荐):'); console.log('\n1. Base64 format key (recommended):');
const base64Key = generateSecureKey(); const base64Key = generateSecureKey();
console.log(` ${base64Key}`); console.log(` ${base64Key}`);
console.log('\n2. 十六进制格式密钥:'); console.log('\n2. Hexadecimal format key:');
const hexKey = generateHexKey(); const hexKey = generateHexKey();
console.log(` ${hexKey}`); console.log(` ${hexKey}`);
console.log('\n3. UUID格式密钥:'); console.log('\n3. UUID format key:');
const uuidKey = generateUUIDKey(); const uuidKey = generateUUIDKey();
console.log(` ${uuidKey}`); console.log(` ${uuidKey}`);
console.log('\n='.repeat(60)); console.log('\n='.repeat(60));
console.log('使用方法:'); console.log('Usage:');
console.log('='.repeat(60)); console.log('='.repeat(60));
console.log('\n在Windows PowerShell中设置环境变量:');
console.log('\nSet environment variable in Windows PowerShell:');
console.log(`$env:MQTT_SIGNATURE_KEY="${base64Key}"`); console.log(`$env:MQTT_SIGNATURE_KEY="${base64Key}"`);
console.log('\n在Windows CMD中设置环境变量:'); console.log('\nSet environment variable in Windows CMD:');
console.log(`set MQTT_SIGNATURE_KEY=${base64Key}`); console.log(`set MQTT_SIGNATURE_KEY=${base64Key}`);
console.log('\n在Linux/macOS中设置环境变量:'); console.log('\nSet environment variable in Linux/macOS:');
console.log(`export MQTT_SIGNATURE_KEY="${base64Key}"`); console.log(`export MQTT_SIGNATURE_KEY="${base64Key}"`);
console.log('\n在.env文件中设置:'); console.log('\nSet in .env file:');
console.log(`MQTT_SIGNATURE_KEY=${base64Key}`); console.log(`MQTT_SIGNATURE_KEY=${base64Key}`);
console.log('\n='.repeat(60)); console.log('\n='.repeat(60));
console.log('注意事项:'); console.log('Notes:');
console.log('='.repeat(60)); console.log('='.repeat(60));
console.log('1. 请妥善保管生成的密钥,不要泄露给他人'); console.log('1. Please keep the generated key secure and do not leak it to others');
console.log('2. 在生产环境中,建议使用更长的密钥 (64字节)'); console.log('2. In production environment, longer keys are recommended (64 bytes)');
console.log('3. 密钥设置后需要重启MQTT服务器才能生效'); console.log('3. MQTT server needs to be restarted after setting the key');
console.log('4. 客户端连接时需要使用相同的密钥生成密码签名'); console.log('4. Clients need to use the same key to generate password signatures when connecting');
// 如果提供了命令行参数,生成指定长度的密钥 // If command line arguments are provided, generate key with specified length
if (process.argv[2]) { if (process.argv[2]) {
const customLength = parseInt(process.argv[2]); const customLength = parseInt(process.argv[2]);
if (customLength > 0) { if (customLength > 0) {
console.log(`\n自定义长度密钥 (${customLength}字节):`); console.log(`\nCustom length key (${customLength} bytes):`);
console.log(` ${generateSecureKey(customLength)}`); console.log(` ${generateSecureKey(customLength)}`);
} }
} }

View file

@ -1,499 +1,513 @@
const debug = require('debug')('mqtt-server'); const debug = require("debug")("mqtt-server");
const EventEmitter = require('events'); const EventEmitter = require("events");
// MQTT 固定头部的类型 // MQTT fixed header types
const PacketType = { const PacketType = {
CONNECT: 1, CONNECT: 1,
CONNACK: 2, CONNACK: 2,
PUBLISH: 3, PUBLISH: 3,
SUBSCRIBE: 8, SUBSCRIBE: 8,
SUBACK: 9, SUBACK: 9,
PINGREQ: 12, PINGREQ: 12,
PINGRESP: 13, PINGRESP: 13,
DISCONNECT: 14 // 添加 DISCONNECT DISCONNECT: 14, // Added DISCONNECT
}; };
/** /**
* MQTT协议处理类 * MQTT protocol handler class
* 负责MQTT协议的解析和封装,以及心跳维持 * Responsible for MQTT protocol parsing and encapsulation, as well as heartbeat maintenance
*/ */
class MQTTProtocol extends EventEmitter { class MQTTProtocol extends EventEmitter {
constructor(socket) { constructor(socket) {
super(); super();
this.socket = socket; this.socket = socket;
this.buffer = Buffer.alloc(0);
this.isConnected = false;
this.keepAliveInterval = 0;
this.lastActivity = Date.now();
this.setupSocketHandlers();
}
/**
* Set up Socket event handlers
*/
setupSocketHandlers() {
this.socket.on("data", (data) => {
this.lastActivity = Date.now();
this.buffer = Buffer.concat([this.buffer, data]);
this.processBuffer();
});
this.socket.on("close", () => {
this.emit("close");
});
this.socket.on("error", (err) => {
this.emit("error", err);
});
}
/**
* Process all complete messages in buffer
*/
processBuffer() {
// Continue processing data in buffer until no complete messages can be processed
while (this.buffer.length > 0) {
// At least 2 bytes needed to start parsing (1 byte fixed header + at least 1 byte remaining length)
if (this.buffer.length < 2) return;
try {
// Get message type
const firstByte = this.buffer[0];
const type = firstByte >> 4;
// Parse remaining length
const { value: remainingLength, bytesRead } =
this.decodeRemainingLength(this.buffer);
// Calculate total message length
const messageLength = 1 + bytesRead + remainingLength;
// Check if buffer has complete message
if (this.buffer.length < messageLength) {
// Message incomplete, wait for more data
return;
}
// Extract complete message
const message = this.buffer.subarray(0, messageLength);
if (!this.isConnected && type !== PacketType.CONNECT) {
debug(
"Received non-CONNECT message when not connected, closing connection"
);
this.socket.end();
return;
}
// Process based on message type
switch (type) {
case PacketType.CONNECT:
this.parseConnect(message);
break;
case PacketType.PUBLISH:
this.parsePublish(message);
break;
case PacketType.SUBSCRIBE:
this.parseSubscribe(message);
break;
case PacketType.PINGREQ:
this.parsePingReq(message);
break;
case PacketType.DISCONNECT:
this.parseDisconnect(message);
break;
default:
debug("Unhandled packet type:", type, message);
this.emit(
"protocolError",
new Error(`Unhandled packet type: ${type}`)
);
}
// Remove processed message from buffer
this.buffer = this.buffer.subarray(messageLength);
} catch (err) {
// If parsing error, might be incomplete data, wait for more data
if (err.message === "Malformed Remaining Length") {
return;
}
// Other errors might be protocol errors, clear buffer and emit error event
this.buffer = Buffer.alloc(0); this.buffer = Buffer.alloc(0);
this.isConnected = false; this.emit("protocolError", err);
this.keepAliveInterval = 0; return;
this.lastActivity = Date.now(); }
}
}
this.setupSocketHandlers(); /**
* Parse Remaining Length field in MQTT packet
* @param {Buffer} buffer - Message buffer
* @returns {{value: number, bytesRead: number}} Contains parsed value and bytes read
*/
decodeRemainingLength(buffer) {
let multiplier = 1;
let value = 0;
let bytesRead = 0;
let digit;
do {
if (bytesRead >= 4 || bytesRead >= buffer.length - 1) {
throw new Error("Malformed Remaining Length");
}
digit = buffer[bytesRead + 1];
bytesRead++;
value += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) !== 0);
return { value, bytesRead };
}
/**
* Encode Remaining Length field in MQTT packet
* @param {number} length - Length value to encode
* @returns {{bytes: Buffer, bytesLength: number}} Contains encoded bytes and byte length
*/
encodeRemainingLength(length) {
let digit;
const bytes = Buffer.alloc(4); // Maximum 4 bytes
let bytesLength = 0;
do {
digit = length % 128;
length = Math.floor(length / 128);
// If more bytes remain, set high bit
if (length > 0) {
digit |= 0x80;
}
bytes[bytesLength++] = digit;
} while (length > 0 && bytesLength < 4);
return { bytes, bytesLength };
}
/**
* Parse CONNECT message
* @param {Buffer} message - Complete CONNECT message
*/
parseConnect(message) {
// Parse remaining length
const { value: remainingLength, bytesRead } =
this.decodeRemainingLength(message);
// Position after fixed header (MQTT fixed header first byte + Remaining Length field bytes)
const headerLength = 1 + bytesRead;
// Read protocol name length from variable header start position
const protocolLength = message.readUInt16BE(headerLength);
const protocol = message.toString(
"utf8",
headerLength + 2,
headerLength + 2 + protocolLength
);
// Update position pointer, skip protocol name
let pos = headerLength + 2 + protocolLength;
// Protocol level, 4 for MQTT 3.1.1
const protocolLevel = message[pos];
// Check protocol version
if (protocolLevel !== 4) {
// 4 represents MQTT 3.1.1
debug("Unsupported protocol version:", protocolLevel);
// Send CONNACK with unsupported protocol version return code (0x01)
this.sendConnack(1, false);
// Close connection
this.socket.end();
return;
} }
/** pos += 1;
* 设置Socket事件处理 // Connection flags
*/ const connectFlags = message[pos];
setupSocketHandlers() { const hasUsername = (connectFlags & 0x80) !== 0;
this.socket.on('data', (data) => { const hasPassword = (connectFlags & 0x40) !== 0;
this.lastActivity = Date.now(); const cleanSession = (connectFlags & 0x02) !== 0;
this.buffer = Buffer.concat([this.buffer, data]); pos += 1;
this.processBuffer();
});
this.socket.on('close', () => { // Keep alive time
this.emit('close'); const keepAlive = message.readUInt16BE(pos);
}); pos += 2;
this.socket.on('error', (err) => { // Parse clientId
this.emit('error', err); const clientIdLength = message.readUInt16BE(pos);
}); pos += 2;
const clientId = message.toString("utf8", pos, pos + clientIdLength);
pos += clientIdLength;
// Parse username (if exists)
let username = "";
if (hasUsername) {
const usernameLength = message.readUInt16BE(pos);
pos += 2;
username = message.toString("utf8", pos, pos + usernameLength);
pos += usernameLength;
} }
/** // Parse password (if exists)
* 处理缓冲区中的所有完整消息 let password = "";
*/ if (hasPassword) {
processBuffer() { const passwordLength = message.readUInt16BE(pos);
// 持续处理缓冲区中的数据,直到没有完整的消息可以处理 pos += 2;
while (this.buffer.length > 0) { password = message.toString("utf8", pos, pos + passwordLength);
// 至少需要2个字节才能开始解析(1字节固定头部 + 至少1字节的剩余长度) pos += passwordLength;
if (this.buffer.length < 2) return;
try {
// 获取消息类型
const firstByte = this.buffer[0];
const type = (firstByte >> 4);
// 解析剩余长度
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(this.buffer);
// 计算整个消息的长度
const messageLength = 1 + bytesRead + remainingLength;
// 检查缓冲区中是否有完整的消息
if (this.buffer.length < messageLength) {
// 消息不完整,等待更多数据
return;
}
// 提取完整的消息
const message = this.buffer.subarray(0, messageLength);
if (!this.isConnected && type !== PacketType.CONNECT) {
debug('未连接时收到非CONNECT消息,关闭连接');
this.socket.end();
return;
}
// 根据消息类型处理
switch (type) {
case PacketType.CONNECT:
this.parseConnect(message);
break;
case PacketType.PUBLISH:
this.parsePublish(message);
break;
case PacketType.SUBSCRIBE:
this.parseSubscribe(message);
break;
case PacketType.PINGREQ:
this.parsePingReq(message);
break;
case PacketType.DISCONNECT:
this.parseDisconnect(message);
break;
default:
debug('未处理的包类型:', type, message);
this.emit('protocolError', new Error(`未处理的包类型: ${type}`));
}
// 从缓冲区中移除已处理的消息
this.buffer = this.buffer.subarray(messageLength);
} catch (err) {
// 如果解析出错,可能是数据不完整,等待更多数据
if (err.message === 'Malformed Remaining Length') {
return;
}
// 其他错误可能是协议错误,清空缓冲区并发出错误事件
this.buffer = Buffer.alloc(0);
this.emit('protocolError', err);
return;
}
}
} }
/** // Set heartbeat interval (1.5 times client-specified keepAlive value, in seconds)
* 解析MQTT报文中的Remaining Length字段 this.keepAliveInterval = keepAlive * 1000 * 1.5;
* @param {Buffer} buffer - 消息缓冲区
* @returns {{value: number, bytesRead: number}} 包含解析的值和读取的字节数
*/
decodeRemainingLength(buffer) {
let multiplier = 1;
let value = 0;
let bytesRead = 0;
let digit;
do { // Send CONNACK
if (bytesRead >= 4 || bytesRead >= buffer.length - 1) { this.sendConnack(0, false);
throw new Error('Malformed Remaining Length');
}
digit = buffer[bytesRead + 1]; // Mark as connected
bytesRead++; this.isConnected = true;
value += (digit & 127) * multiplier; // Emit connection event
multiplier *= 128; this.emit("connect", {
clientId,
protocol,
protocolLevel,
keepAlive,
username,
password,
cleanSession,
});
}
} while ((digit & 128) !== 0); /**
* Parse PUBLISH message
* @param {Buffer} message - Complete PUBLISH message
*/
parsePublish(message) {
// Extract QoS level from first byte (bits 1-2)
const firstByte = message[0];
const qos = (firstByte & 0x06) >> 1; // 0x06 is binary 00000110, used as mask to extract QoS bits
const dup = (firstByte & 0x08) !== 0; // 0x08 is binary 00001000, used as mask to extract DUP flag
const retain = (firstByte & 0x01) !== 0; // 0x01 is binary 00000001, used as mask to extract RETAIN flag
return { value, bytesRead }; // Use common method to parse remaining length
const { value: remainingLength, bytesRead } =
this.decodeRemainingLength(message);
// Position after fixed header (MQTT fixed header first byte + Remaining Length field bytes)
const headerLength = 1 + bytesRead;
// Parse topic
const topicLength = message.readUInt16BE(headerLength);
const topic = message.toString(
"utf8",
headerLength + 2,
headerLength + 2 + topicLength
);
// For QoS > 0, includes message ID
let packetId = null;
let payloadStart = headerLength + 2 + topicLength;
if (qos > 0) {
packetId = message.readUInt16BE(payloadStart);
payloadStart += 2;
} }
/** // Parse payload
* 编码MQTT报文中的Remaining Length字段 const payload = message.slice(payloadStart).toString("utf8");
* @param {number} length - 要编码的长度值
* @returns {{bytes: Buffer, bytesLength: number}} 包含编码后的字节和字节长度
*/
encodeRemainingLength(length) {
let digit;
const bytes = Buffer.alloc(4); // 最多4个字节
let bytesLength = 0;
do { // Emit publish event
digit = length % 128; this.emit("publish", {
length = Math.floor(length / 128); topic,
// 如果还有更多字节,设置最高位 payload,
if (length > 0) { qos,
digit |= 0x80; dup,
} retain,
bytes[bytesLength++] = digit; packetId,
} while (length > 0 && bytesLength < 4); });
}
return { bytes, bytesLength }; /**
* Parse SUBSCRIBE message
* @param {Buffer} message - Complete SUBSCRIBE message
*/
parseSubscribe(message) {
const packetId = message.readUInt16BE(2);
const topicLength = message.readUInt16BE(4);
const topic = message.toString("utf8", 6, 6 + topicLength);
const qos = message[6 + topicLength]; // QoS value
// Emit subscribe event
this.emit("subscribe", {
packetId,
topic,
qos,
});
}
/**
* Parse PINGREQ message
* @param {Buffer} message - Complete PINGREQ message
*/
parsePingReq(message) {
debug("Received heartbeat request");
// Send PINGRESP
this.sendPingResp();
debug("Sent heartbeat response");
}
/**
* Parse DISCONNECT message
* @param {Buffer} message - Complete DISCONNECT message
*/
parseDisconnect(message) {
// Mark as disconnected
this.isConnected = false;
// Emit disconnect event
this.emit("disconnect");
// Close socket
this.socket.end();
}
/**
* Send CONNACK message
* @param {number} returnCode - Return code
* @param {boolean} sessionPresent - Session present flag
*/
sendConnack(returnCode = 0, sessionPresent = false) {
if (!this.socket.writable) return;
const packet = Buffer.from([
PacketType.CONNACK << 4,
2, // Remaining length
sessionPresent ? 1 : 0, // Connect acknowledge flags
returnCode, // Return code
]);
this.socket.write(packet);
}
/**
* Send PUBLISH message
* @param {string} topic - Topic
* @param {string} payload - Payload
* @param {number} qos - QoS level
* @param {boolean} dup - Duplicate flag
* @param {boolean} retain - Retain flag
* @param {number} packetId - Packet ID (only needed when QoS > 0)
*/
sendPublish(
topic,
payload,
qos = 0,
dup = false,
retain = false,
packetId = null
) {
if (!this.isConnected || !this.socket.writable) return;
const topicLength = Buffer.byteLength(topic);
const payloadLength = Buffer.byteLength(payload);
// Calculate remaining length
let remainingLength = 2 + topicLength + payloadLength;
// If QoS > 0, need to include packet ID
if (qos > 0 && packetId) {
remainingLength += 2;
} }
/** // Encode variable length
* 解析CONNECT消息 const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } =
* @param {Buffer} message - 完整的CONNECT消息 this.encodeRemainingLength(remainingLength);
*/
parseConnect(message) {
// 解析剩余长度
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message);
// 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节) // Allocate buffer: fixed header(1 byte) + variable length field + remaining length value
const headerLength = 1 + bytesRead; const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength);
// 从可变头部开始位置读取协议名长度 // Write fixed header
const protocolLength = message.readUInt16BE(headerLength); let firstByte = PacketType.PUBLISH << 4;
const protocol = message.toString('utf8', headerLength + 2, headerLength + 2 + protocolLength); if (dup) firstByte |= 0x08;
if (qos > 0) firstByte |= qos << 1;
if (retain) firstByte |= 0x01;
packet[0] = firstByte;
// 更新位置指针,跳过协议名 // Write variable length field
let pos = headerLength + 2 + protocolLength; remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize);
// 协议级别,4为MQTT 3.1.1 // Write topic length and topic
const protocolLevel = message[pos]; const variableHeaderStart = 1 + remainingLengthSize;
packet.writeUInt16BE(topicLength, variableHeaderStart);
packet.write(topic, variableHeaderStart + 2);
// 检查协议版本 // If QoS > 0, write packet ID
if (protocolLevel !== 4) { // 4 表示 MQTT 3.1.1 let payloadStart = variableHeaderStart + 2 + topicLength;
debug('不支持的协议版本:', protocolLevel); if (qos > 0 && packetId) {
// 发送 CONNACK,使用不支持的协议版本的返回码 (0x01) packet.writeUInt16BE(packetId, payloadStart);
this.sendConnack(1, false); payloadStart += 2;
// 关闭连接
this.socket.end();
return;
}
pos += 1;
// 连接标志
const connectFlags = message[pos];
const hasUsername = (connectFlags & 0x80) !== 0;
const hasPassword = (connectFlags & 0x40) !== 0;
const cleanSession = (connectFlags & 0x02) !== 0;
pos += 1;
// 保持连接时间
const keepAlive = message.readUInt16BE(pos);
pos += 2;
// 解析 clientId
const clientIdLength = message.readUInt16BE(pos);
pos += 2;
const clientId = message.toString('utf8', pos, pos + clientIdLength);
pos += clientIdLength;
// 解析 username(如果存在)
let username = '';
if (hasUsername) {
const usernameLength = message.readUInt16BE(pos);
pos += 2;
username = message.toString('utf8', pos, pos + usernameLength);
pos += usernameLength;
}
// 解析 password(如果存在)
let password = '';
if (hasPassword) {
const passwordLength = message.readUInt16BE(pos);
pos += 2;
password = message.toString('utf8', pos, pos + passwordLength);
pos += passwordLength;
}
// 设置心跳间隔(客户端指定的keepAlive值的1.5倍,单位为秒)
this.keepAliveInterval = keepAlive * 1000 * 1.5;
// 发送 CONNACK
this.sendConnack(0, false);
// 标记为已连接
this.isConnected = true;
// 发出连接事件
this.emit('connect', {
clientId,
protocol,
protocolLevel,
keepAlive,
username,
password,
cleanSession
});
} }
/** // Write payload
* 解析PUBLISH消息 packet.write(payload, payloadStart);
* @param {Buffer} message - 完整的PUBLISH消息
*/
parsePublish(message) {
// 从第一个字节中提取QoS级别(bits 1-2)
const firstByte = message[0];
const qos = (firstByte & 0x06) >> 1; // 0x06 是二进制 00000110,用于掩码提取QoS位
const dup = (firstByte & 0x08) !== 0; // 0x08 是二进制 00001000,用于掩码提取DUP标志
const retain = (firstByte & 0x01) !== 0; // 0x01 是二进制 00000001,用于掩码提取RETAIN标志
// 使用通用方法解析剩余长度 this.socket.write(packet);
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message); this.lastActivity = Date.now();
}
// 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节) /**
const headerLength = 1 + bytesRead; * Send SUBACK message
* @param {number} packetId - Packet ID
* @param {number} returnCode - Return code
*/
sendSuback(packetId, returnCode = 0) {
if (!this.isConnected || !this.socket.writable) return;
// 解析主题 const packet = Buffer.from([
const topicLength = message.readUInt16BE(headerLength); PacketType.SUBACK << 4,
const topic = message.toString('utf8', headerLength + 2, headerLength + 2 + topicLength); 3, // Remaining length
packetId >> 8, // Packet ID MSB
packetId & 0xff, // Packet ID LSB
returnCode, // Return code
]);
// 对于QoS > 0,包含消息ID this.socket.write(packet);
let packetId = null; this.lastActivity = Date.now();
let payloadStart = headerLength + 2 + topicLength; }
if (qos > 0) { /**
packetId = message.readUInt16BE(payloadStart); * Send PINGRESP message
payloadStart += 2; */
} sendPingResp() {
if (!this.isConnected || !this.socket.writable) return;
// 解析有效载荷 const packet = Buffer.from([
const payload = message.slice(payloadStart).toString('utf8'); PacketType.PINGRESP << 4, // Fixed header
0, // Remaining length
]);
// 发出发布事件 this.socket.write(packet);
this.emit('publish', { this.lastActivity = Date.now();
topic, }
payload,
qos, /**
dup, * Get last activity time
retain, */
packetId getLastActivity() {
}); return this.lastActivity;
} }
/** /**
* 解析SUBSCRIBE消息 * Get heartbeat interval
* @param {Buffer} message - 完整的SUBSCRIBE消息 */
*/ getKeepAliveInterval() {
parseSubscribe(message) { return this.keepAliveInterval;
const packetId = message.readUInt16BE(2); }
const topicLength = message.readUInt16BE(4);
const topic = message.toString('utf8', 6, 6 + topicLength); /**
const qos = message[6 + topicLength]; // QoS值 * Clear buffer
*/
// 发出订阅事件 clearBuffer() {
this.emit('subscribe', { this.buffer = Buffer.alloc(0);
packetId, }
topic,
qos /**
}); * Close connection
} */
close() {
/** if (this.socket.writable) {
* 解析PINGREQ消息 this.socket.end();
* @param {Buffer} message - 完整的PINGREQ消息
*/
parsePingReq(message) {
debug('收到心跳请求');
// 发送 PINGRESP
this.sendPingResp();
debug('已发送心跳响应');
}
/**
* 解析DISCONNECT消息
* @param {Buffer} message - 完整的DISCONNECT消息
*/
parseDisconnect(message) {
// 标记为未连接
this.isConnected = false;
// 发出断开连接事件
this.emit('disconnect');
// 关闭 socket
this.socket.end();
}
/**
* 发送CONNACK消息
* @param {number} returnCode - 返回码
* @param {boolean} sessionPresent - 会话存在标志
*/
sendConnack(returnCode = 0, sessionPresent = false) {
if (!this.socket.writable) return;
const packet = Buffer.from([
PacketType.CONNACK << 4,
2, // Remaining length
sessionPresent ? 1 : 0, // Connect acknowledge flags
returnCode // Return code
]);
this.socket.write(packet);
}
/**
* 发送PUBLISH消息
* @param {string} topic - 主题
* @param {string} payload - 有效载荷
* @param {number} qos - QoS级别
* @param {boolean} dup - 重复标志
* @param {boolean} retain - 保留标志
* @param {number} packetId - 包ID(仅QoS > 0时需要)
*/
sendPublish(topic, payload, qos = 0, dup = false, retain = false, packetId = null) {
if (!this.isConnected || !this.socket.writable) return;
const topicLength = Buffer.byteLength(topic);
const payloadLength = Buffer.byteLength(payload);
// 计算剩余长度
let remainingLength = 2 + topicLength + payloadLength;
// 如果QoS > 0,需要包含包ID
if (qos > 0 && packetId) {
remainingLength += 2;
}
// 编码可变长度
const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } = this.encodeRemainingLength(remainingLength);
// 分配缓冲区:固定头部(1字节) + 可变长度字段 + 剩余长度值
const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength);
// 写入固定头部
let firstByte = PacketType.PUBLISH << 4;
if (dup) firstByte |= 0x08;
if (qos > 0) firstByte |= (qos << 1);
if (retain) firstByte |= 0x01;
packet[0] = firstByte;
// 写入可变长度字段
remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize);
// 写入主题长度和主题
const variableHeaderStart = 1 + remainingLengthSize;
packet.writeUInt16BE(topicLength, variableHeaderStart);
packet.write(topic, variableHeaderStart + 2);
// 如果QoS > 0,写入包ID
let payloadStart = variableHeaderStart + 2 + topicLength;
if (qos > 0 && packetId) {
packet.writeUInt16BE(packetId, payloadStart);
payloadStart += 2;
}
// 写入有效载荷
packet.write(payload, payloadStart);
this.socket.write(packet);
this.lastActivity = Date.now();
}
/**
* 发送SUBACK消息
* @param {number} packetId - 包ID
* @param {number} returnCode - 返回码
*/
sendSuback(packetId, returnCode = 0) {
if (!this.isConnected || !this.socket.writable) return;
const packet = Buffer.from([
PacketType.SUBACK << 4,
3, // Remaining length
packetId >> 8, // Packet ID MSB
packetId & 0xFF, // Packet ID LSB
returnCode // Return code
]);
this.socket.write(packet);
this.lastActivity = Date.now();
}
/**
* 发送PINGRESP消息
*/
sendPingResp() {
if (!this.isConnected || !this.socket.writable) return;
const packet = Buffer.from([
PacketType.PINGRESP << 4, // Fixed header
0 // Remaining length
]);
this.socket.write(packet);
this.lastActivity = Date.now();
}
/**
* 获取上次活动时间
*/
getLastActivity() {
return this.lastActivity;
}
/**
* 获取心跳间隔
*/
getKeepAliveInterval() {
return this.keepAliveInterval;
}
/**
* 清空缓冲区
*/
clearBuffer() {
this.buffer = Buffer.alloc(0);
}
/**
* 关闭连接
*/
close() {
if (this.socket.writable) {
this.socket.end();
}
} }
}
} }
// 导出 PacketType 和 MQTTProtocol 类 // Export PacketType and MQTTProtocol class
module.exports = { module.exports = {
PacketType, PacketType,
MQTTProtocol MQTTProtocol,
}; };

View file

@ -3,74 +3,73 @@ const path = require('path');
const EventEmitter = require('events'); const EventEmitter = require('events');
class ConfigManager extends EventEmitter { class ConfigManager extends EventEmitter {
constructor(fileName) { constructor(fileName) {
super(); super();
this.config = {}; // 移除默认的 apiKeys 配置 this.config = {}; // Remove default apiKeys configuration
this.configPath = path.join(__dirname, "..", "config", fileName); this.configPath = path.join(__dirname, "..", "config", fileName);
this.loadConfig(); this.loadConfig();
this.watchConfig(); this.watchConfig();
// 添加防抖计时器变量 // Add debounce timer variable
this.watchDebounceTimer = null; this.watchDebounceTimer = null;
}
loadConfig() {
try {
const data = fs.readFileSync(this.configPath, 'utf8');
const newConfig = JSON.parse(data);
// 检测配置是否发生变化
if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) {
console.log('配置已更新', this.configPath);
this.config = newConfig;
// 发出配置更新事件
this.emit('configChanged', this.config);
}
} catch (error) {
console.error('加载配置出错:', error, this.configPath);
if (error.code === 'ENOENT') {
this.createEmptyConfig();
}
} }
}
createEmptyConfig() { loadConfig() {
try { try {
const dir = path.dirname(this.configPath); const data = fs.readFileSync(this.configPath, 'utf8');
if (!fs.existsSync(dir)) { const newConfig = JSON.parse(data);
fs.mkdirSync(dir, { recursive: true }); // Check if configuration has changed
} if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) {
const defaultConfig = {}; // 空配置对象 console.log('Configuration updated', this.configPath);
fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2)); this.config = newConfig;
console.log('已创建空配置文件', this.configPath); // Emit configuration update event
} catch (error) { this.emit('configChanged', this.config);
console.error('创建空配置文件出错:', error, this.configPath); }
} } catch (error) {
} console.error('Error loading configuration:', error, this.configPath);
if (error.code === 'ENOENT') {
watchConfig() { this.createEmptyConfig();
fs.watch(path.dirname(this.configPath), (eventType, filename) => { }
if (filename === path.basename(this.configPath) && eventType === 'change') {
// 清除之前的计时器
if (this.watchDebounceTimer) {
clearTimeout(this.watchDebounceTimer);
} }
// 设置新的计时器,300ms 后执行 }
this.watchDebounceTimer = setTimeout(() => {
this.loadConfig();
}, 300);
}
});
}
// 获取配置的方法 createEmptyConfig() {
getConfig() { try {
return this.config; const dir = path.dirname(this.configPath);
} if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const defaultConfig = {}; // Empty configuration object
fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2));
console.log('Created empty configuration file', this.configPath);
} catch (error) {
console.error('Error creating empty configuration file:', error, this.configPath);
}
}
// 获取特定配置项的方法 watchConfig() {
get(key) { fs.watch(path.dirname(this.configPath), (eventType, filename) => {
return this.config[key]; if (filename === path.basename(this.configPath) && eventType === 'change') {
} // Clear previous timer
if (this.watchDebounceTimer) {
clearTimeout(this.watchDebounceTimer);
}
// Set new timer, execute after 300ms
this.watchDebounceTimer = setTimeout(() => {
this.loadConfig();
}, 300);
}
});
}
// Method to get configuration
getConfig() {
return this.config;
}
// Method to get specific configuration item
get(key) {
return this.config[key];
}
} }
module.exports = { module.exports = {

View file

@ -1,103 +1,116 @@
require('dotenv').config(); require("dotenv").config();
const crypto = require('crypto'); const crypto = require("crypto");
function generatePasswordSignature(content, secretKey) { function generatePasswordSignature(content, secretKey) {
// Create an HMAC object using SHA256 and the secretKey // Create an HMAC object using SHA256 and the secretKey
const hmac = crypto.createHmac('sha256', secretKey); const hmac = crypto.createHmac("sha256", secretKey);
// Update the HMAC object with the clientId
// Update the HMAC object with the clientId hmac.update(content);
hmac.update(content); // Generate the HMAC digest in binary format
const binarySignature = hmac.digest();
// Generate the HMAC digest in binary format // Encode the binary signature to Base64
const binarySignature = hmac.digest(); const base64Signature = binarySignature.toString("base64");
return base64Signature;
// Encode the binary signature to Base64
const base64Signature = binarySignature.toString('base64');
return base64Signature;
} }
function validateMqttCredentials(clientId, username, password) { function validateMqttCredentials(clientId, username, password) {
// 验证密码签名 // Validate password signature
const signatureKey = process.env.MQTT_SIGNATURE_KEY; const signatureKey = process.env.MQTT_SIGNATURE_KEY;
if (signatureKey) { if (signatureKey) {
const expectedSignature = generatePasswordSignature(clientId + '|' + username, signatureKey); const expectedSignature = generatePasswordSignature(
if (password !== expectedSignature) { clientId + "|" + username,
throw new Error('密码签名验证失败'); signatureKey
} );
} else { if (password !== expectedSignature) {
console.warn('缺少MQTT_SIGNATURE_KEY环境变量,跳过密码签名验证'); throw new Error("Password signature validation failed");
} }
} else {
console.warn(
"Missing MQTT_SIGNATURE_KEY environment variable, skipping password signature validation"
);
}
// 验证clientId // Validate clientId
if (!clientId || typeof clientId !== 'string') { if (!clientId || typeof clientId !== "string") {
throw new Error('clientId必须是非空字符串'); throw new Error("clientId must be a non-empty string");
} }
// 验证clientId格式(必须包含@@@分隔符) // Validate clientId format (must contain @@@ separator)
const clientIdParts = clientId.split('@@@'); const clientIdParts = clientId.split("@@@");
// 新版本 MQTT 参数 // New version MQTT parameters
if (clientIdParts.length !== 3) { if (clientIdParts.length !== 3) {
throw new Error('clientId格式错误,必须包含@@@分隔符'); throw new Error("clientId format error, must contain @@@ separator");
} }
// 验证username // Validate username
if (!username || typeof username !== 'string') { if (!username || typeof username !== "string") {
throw new Error('username必须是非空字符串'); throw new Error("username must be a non-empty string");
} }
// 尝试解码username(应该是base64编码的JSON) // Try to decode username (should be base64 encoded JSON)
let userData; let userData;
try { try {
const decodedUsername = Buffer.from(username, 'base64').toString(); const decodedUsername = Buffer.from(username, "base64").toString();
userData = JSON.parse(decodedUsername); userData = JSON.parse(decodedUsername);
} catch (error) { } catch (error) {
throw new Error('username不是有效的base64编码JSON'); throw new Error("username is not valid base64 encoded JSON");
} }
// 解析clientId中的信息 // Parse information from clientId
const [groupId, macAddress, uuid] = clientIdParts; const [groupId, macAddress, uuid] = clientIdParts;
// If validation succeeds, return parsed useful information
// 如果验证成功,返回解析后的有用信息 return {
return { groupId,
groupId, macAddress: macAddress.replace(/_/g, ":"),
macAddress: macAddress.replace(/_/g, ':'), uuid,
uuid, userData,
userData };
};
} }
function generateMqttConfig(groupId, macAddress, uuid, userData) { function generateMqttConfig(groupId, macAddress, uuid, userData) {
const endpoint = process.env.MQTT_ENDPOINT; const endpoint = process.env.MQTT_ENDPOINT;
const signatureKey = process.env.MQTT_SIGNATURE_KEY; const signatureKey = process.env.MQTT_SIGNATURE_KEY;
if (!signatureKey) { if (!signatureKey) {
console.warn('No signature key, skip generating MQTT config'); console.warn("No signature key, skip generating MQTT config");
return; return;
} }
const deviceIdNoColon = macAddress.replace(/:/g, '_');
const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`; const deviceIdNoColon = macAddress.replace(/:/g, "_");
const username = Buffer.from(JSON.stringify(userData)).toString('base64'); const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`;
const password = generatePasswordSignature(clientId + '|' + username, signatureKey); const username = Buffer.from(JSON.stringify(userData)).toString("base64");
return { const password = generatePasswordSignature(
endpoint, clientId + "|" + username,
port: 8883, signatureKey
client_id: clientId, );
username,
password, return {
publish_topic: 'device-server', endpoint,
subscribe_topic: 'null' // 旧版本固件不返回此字段会出错 port: 8883,
} client_id: clientId,
username,
password,
publish_topic: "device-server",
subscribe_topic: "null", // Old version firmware will error if this field is not returned
};
} }
module.exports = { module.exports = {
generateMqttConfig, generateMqttConfig,
validateMqttCredentials validateMqttCredentials,
} };
if (require.main === module) { if (require.main === module) {
const config = generateMqttConfig('GID_test', '11:22:33:44:55:66', '36c98363-3656-43cb-a00f-8bced2391a90', { ip: '222.222.222.222' }); const config = generateMqttConfig(
console.log('config', config); "GID_test",
const credentials = validateMqttCredentials(config.client_id, config.username, config.password); "11:22:33:44:55:66",
console.log('credentials', credentials); "36c98363-3656-43cb-a00f-8bced2391a90",
{ ip: "222.222.222.222" }
);
console.log("config", config);
const credentials = validateMqttCredentials(
config.client_id,
config.username,
config.password
);
console.log("credentials", credentials);
} }

View file

@ -1,239 +1,258 @@
# MQTT网关转发功能测试指南 # MQTT Gateway Forwarding Function Test Guide
本文档说明如何测试MQTT网关的转发功能是否配置成功。 This document explains how to test whether the MQTT gateway forwarding function is configured successfully.
## 快速测试 ## Quick Test
### 1. 基础连接测试 ### 1. Basic Connection Test
运行快速测试脚本: Run the quick test script:
```bash ```bash
node quick-test.js node quick-test.js
``` ```
这个脚本会: This script will:
- ✅ 检查配置文件
- ✅ 测试MQTT服务器连接(端口1883)
- ✅ 测试WebSocket后端服务连接
- ✅ 显示测试结果和建议
### 2. 完整功能测试 - ✅ Check configuration file
- ✅ Test MQTT server connection (port 1883)
- ✅ Test WebSocket backend service connection
- ✅ Display test results and recommendations
运行完整测试脚本: ### 2. Complete Function Test
Run the complete test script:
```bash ```bash
node test-mqtt.js node test-mqtt.js
``` ```
这个脚本会: This script will:
- 🔗 连接到MQTT服务器
- 🔐 使用配置的MAC地址进行认证
- 📝 订阅回复主题
- 📤 发送hello消息测试WebSocket转发
- 📥 等待并显示服务器响应
- 🧪 发送其他测试消息
## 手动测试步骤 - 🔗 Connect to MQTT server
- 🔐 Authenticate using configured MAC address
- 📝 Subscribe to reply topic
- 📤 Send hello message to test WebSocket forwarding
- 📥 Wait for and display server response
- 🧪 Send other test messages
### 1. 启动MQTT网关 ## Manual Test Steps
### 1. Start MQTT Gateway
```bash ```bash
node app.js node app.js
``` ```
应该看到类似输出: You should see similar output:
``` ```
MQTT 服务器启动在端口 1883 MQTT server started on port 1883
UDP 服务器启动在端口 1883 UDP server started on port 1883
连接数: 0, 活跃数: 0 Connections: 0, Active: 0
``` ```
### 2. 检查配置文件 ### 2. Check Configuration File
确认 `config/mqtt.json` 配置正确: Confirm that `config/mqtt.json` is configured correctly:
```json ```json
{ {
"production": { "production": {
"chat_servers": [ "chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"]
"ws://192.168.68.66:8000/xiaozhi/v1/" },
] "development": {
}, "chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
"development": { "mac_addresss": ["d8:43:ae:3e:4b:5a"]
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"], },
"mac_addresss": ["d8:43:ae:3e:4b:5a"] "debug": false
},
"debug": false
} }
``` ```
### 3. 使用MQTT客户端工具测试 ### 3. Test Using MQTT Client Tools
#### 使用mosquitto客户端: #### Using mosquitto client:
**Connection test:**
**连接测试:**
```bash ```bash
mosquitto_pub -h localhost -p 1883 -t "test/topic" -m "hello" mosquitto_pub -h localhost -p 1883 -t "test/topic" -m "hello"
``` ```
**订阅测试:** **Subscription test:**
```bash ```bash
mosquitto_sub -h localhost -p 1883 -t "devices/p2p/d8_43_ae_3e_4b_5a" mosquitto_sub -h localhost -p 1883 -t "devices/p2p/d8_43_ae_3e_4b_5a"
``` ```
#### 使用MQTT.fx或其他GUI工具: #### Using MQTT.fx or other GUI tools:
1. **连接设置:** 1. **Connection settings:**
- 服务器:localhost
- 端口:1883 - Server: localhost
- 客户端ID:`GID_test@@@d8_43_ae_3e_4b_5a` - Port: 1883
- 用户名:test_user - Client ID: `GID_test@@@d8_43_ae_3e_4b_5a`
- 密码:test_password - Username: test_user
- Password: test_password
2. **Publish test message:**
- Topic: `test/topic`
- Message:
2. **发布测试消息:**
- 主题:`test/topic`
- 消息:
```json ```json
{ {
"type": "hello", "type": "hello",
"version": 3, "version": 3,
"transport": "mqtt", "transport": "mqtt",
"audio_params": { "audio_params": {
"sample_rate": 16000, "sample_rate": 16000,
"channels": 1, "channels": 1,
"format": "opus" "format": "opus"
}, },
"features": ["tts", "asr"] "features": ["tts", "asr"]
} }
``` ```
3. **订阅回复主题:** 3. **Subscribe to reply topic:**
- 主题:`devices/p2p/d8_43_ae_3e_4b_5a` - Topic: `devices/p2p/d8_43_ae_3e_4b_5a`
## 测试结果判断 ## Test Result Assessment
### ✅ 成功指标 ### ✅ Success Indicators
1. **MQTT connection successful:**
1. **MQTT连接成功:**
``` ```
✓ 成功连接到MQTT服务器 localhost:1883 ✓ Successfully connected to MQTT server localhost:1883
✓ MQTT连接成功 ✓ MQTT connection successful
``` ```
2. **WebSocket转发成功:** 2. **WebSocket forwarding successful:**
``` ```
✓ WebSocket服务器连接成功 ✓ WebSocket server connection successful
✓ 收到PUBLISH消息 ✓ Received PUBLISH message
``` ```
3. **服务器日志正常:** 3. **Server logs normal:**
``` ```
客户端连接: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... } Client connected: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... }
收到发布消息: { topic: 'test/topic', payload: '...', qos: 0 } Received publish message: { topic: 'test/topic', payload: '...', qos: 0 }
``` ```
### ❌ 常见问题 ### ❌ Common Issues
1. **MQTT服务器连接失败:** 1. **MQTT server connection failed:**
```
✗ 连接错误: connect ECONNREFUSED 127.0.0.1:1883
```
**解决方案:** 确保运行 `node app.js` 启动MQTT网关
2. **WebSocket连接失败:**
``` ```
✗ WebSocket服务器连接失败: connect ECONNREFUSED ✗ Connection error: connect ECONNREFUSED 127.0.0.1:1883
``` ```
**解决方案:** 检查WebSocket后端服务是否运行,网络是否可达
3. **认证失败:** **Solution:** Ensure running `node app.js` to start MQTT gateway
```
无效的 clientId: xxx 2. **WebSocket connection failed:**
```
**解决方案:** 检查客户端ID格式是否为 `GID_test@@@mac_address`
4. **MAC地址不匹配:**
``` ```
未找到 xx:xx:xx:xx:xx:xx 的聊天服务器 ✗ WebSocket server connection failed: connect ECONNREFUSED
``` ```
**解决方案:** 确认MAC地址在配置文件的 `mac_addresss` 列表中
## 调试技巧 **Solution:** Check if WebSocket backend service is running and network is reachable
### 1. 开启调试模式 3. **Authentication failed:**
```
Invalid clientId: xxx
```
**Solution:** Check if client ID format is `GID_test@@@mac_address`
4. **MAC address mismatch:**
```
Chat server not found for xx:xx:xx:xx:xx:xx
```
**Solution:** Confirm MAC address is in the `mac_addresss` list in configuration file
## Debugging Tips
### 1. Enable Debug Mode
Modify `config/mqtt.json`:
修改 `config/mqtt.json`:
```json ```json
{ {
"debug": true "debug": true
} }
``` ```
或设置环境变量: Or set environment variable:
```bash ```bash
DEBUG=mqtt-server node app.js DEBUG=mqtt-server node app.js
``` ```
### 2. 查看详细日志 ### 2. View Detailed Logs
Debug mode will display detailed connection and message processing information:
调试模式下会显示详细的连接和消息处理信息:
``` ```
mqtt-server 客户端连接: { clientId: '...', username: '...', ... } mqtt-server Client connected: { clientId: '...', username: '...', ... }
mqtt-server 收到发布消息: { topic: '...', payload: '...', qos: 0 } mqtt-server Received publish message: { topic: '...', payload: '...', qos: 0 }
mqtt-server 发送消息到 devices/p2p/...: {...} mqtt-server Sending message to devices/p2p/...: {...}
``` ```
### 3. 网络连通性测试 ### 3. Network Connectivity Test
**Test WebSocket server:**
**测试WebSocket服务器:**
```bash ```bash
curl -I http://192.168.68.66:8000/xiaozhi/v1/ curl -I http://192.168.68.66:8000/xiaozhi/v1/
``` ```
**测试MQTT端口:** **Test MQTT port:**
```bash ```bash
telnet localhost 1883 telnet localhost 1883
``` ```
## 性能测试 ## Performance Testing
### 并发连接测试 ### Concurrent Connection Test
可以修改测试脚本创建多个并发连接: You can modify the test script to create multiple concurrent connections:
```javascript ```javascript
// 创建多个测试客户端 // Create multiple test clients
const clients = []; const clients = [];
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
const client = new MQTTTestClient(); const client = new MQTTTestClient();
clients.push(client); clients.push(client);
// 连接和测试... // Connect and test...
} }
``` ```
### 消息吞吐量测试 ### Message Throughput Test
发送大量消息测试转发性能: Send large number of messages to test forwarding performance:
```javascript ```javascript
// 发送100条消息 // Send 100 messages
for (let i = 0; i < 100; i++) { for (let i = 0; i < 100; i++) {
client.publish('test/topic', `测试消息 ${i}`); client.publish("test/topic", `Test message ${i}`);
} }
``` ```
## 故障排除清单 ## Troubleshooting Checklist
- [ ] MQTT网关服务是否运行 (`node app.js`) - [ ] Is MQTT gateway service running (`node app.js`)
- [ ] 端口1883是否被占用 - [ ] Is port 1883 occupied
- [ ] 配置文件格式是否正确 - [ ] Is configuration file format correct
- [ ] WebSocket后端服务是否运行 - [ ] Is WebSocket backend service running
- [ ] 网络连接是否正常 - [ ] Is network connection normal
- [ ] MAC地址是否在配置的白名单中 - [ ] Is MAC address in configured whitelist
- [ ] 客户端ID格式是否正确 - [ ] Is client ID format correct
- [ ] 防火墙是否阻止连接 - [ ] Is firewall blocking connections
## 总结 ## Summary
通过以上测试方法,你可以全面验证MQTT网关的转发功能是否配置成功。建议先运行快速测试,如果有问题再进行详细的手动测试和调试。 Through the above testing methods, you can comprehensively verify whether the MQTT gateway forwarding function is configured successfully. It is recommended to run the quick test first, and if there are issues, proceed with detailed manual testing and debugging.

View file

@ -0,0 +1,148 @@
# TEN VAD Integration Summary
## Overview
TEN VAD has been successfully integrated into the XiaoZhi ESP32 Server with **full cross-platform support**. Two versions are now available:
1. **TEN VAD Original**: Linux-only version using pip package
2. **TEN VAD ONNX**: Cross-platform version supporting Windows, Linux, and macOS
## Files Added/Modified
### New Files Created:
1. **`core/providers/vad/ten_vad.py`** - Main TEN VAD provider implementation
2. **`scripts/install_ten_vad.py`** - Installation script for TEN VAD
3. **`scripts/test_ten_vad.py`** - Test script to verify TEN VAD installation
4. **`examples/ten_vad_example.py`** - Usage example and configuration guide
5. **`docs/ten-vad-integration.md`** - Comprehensive integration documentation
### Modified Files:
1. **`requirements.txt`** - Added `ten-vad==0.1.0` dependency
2. **`data/.config.yaml`** - Added TEN VAD configuration section
3. **`README.md`** - Updated VAD section to include TEN VAD
## Configuration
TEN VAD configuration has been added to `.config.yaml`:
```yaml
VAD:
TenVAD:
type: ten_vad
model_path: models/ten-vad
sample_rate: 16000
frame_size: 512
threshold: 0.5
threshold_low: 0.2
min_silence_duration_ms: 1000
frame_window_threshold: 3
```
## Usage
To use TEN VAD, update the selected module in your configuration:
```yaml
selected_module:
VAD: TenVAD # Change from SileroVAD to TenVAD
```
## Installation Steps
1. **Install TEN VAD package:**
```bash
cd main/xiaozhi-server
python scripts/install_ten_vad.py
```
2. **Test the installation:**
```bash
python scripts/test_ten_vad.py
```
3. **Update configuration:**
```yaml
selected_module:
VAD: TenVAD
```
4. **Start the server:**
```bash
python app.py
```
## Key Features
- **High Performance**: TEN VAD provides accurate voice activity detection
- **Configurable Thresholds**: Dual threshold system for stable detection
- **Sliding Window**: Prevents false positives with frame-based detection
- **Easy Integration**: Follows the same interface as existing VAD providers
- **Comprehensive Logging**: Debug information for troubleshooting
## Architecture Integration
TEN VAD integrates seamlessly with the existing VAD architecture:
```
core/utils/vad.py (Factory)
↓
core/providers/vad/ten_vad.py (TEN VAD Implementation)
↓
core/providers/vad/base.py (VAD Interface)
```
The integration follows the same pattern as other VAD providers:
- Implements `VADProviderBase` interface
- Uses the factory pattern for instantiation
- Processes Opus-encoded audio packets
- Returns boolean voice activity detection results
## Configuration Options
### Sensitivity Levels:
- **Sensitive**: `threshold: 0.3, threshold_low: 0.1`
- **Balanced**: `threshold: 0.5, threshold_low: 0.2` (default)
- **Conservative**: `threshold: 0.7, threshold_low: 0.4`
### Performance Tuning:
- `frame_size`: Audio processing frame size (default: 512)
- `frame_window_threshold`: Frames needed for voice detection (default: 3)
- `min_silence_duration_ms`: Silence duration to end speech (default: 1000ms)
## Testing
The integration includes comprehensive testing:
1. **Installation Test**: Verifies TEN VAD package installation
2. **Provider Creation Test**: Tests VAD provider instantiation
3. **Audio Processing Test**: Tests audio processing pipeline
4. **Configuration Loading Test**: Tests factory method integration
## Troubleshooting
Common issues and solutions:
1. **Import Error**: Install TEN VAD with `pip install ten-vad`
2. **Model Loading Error**: Ensure model path exists and is accessible
3. **Performance Issues**: Adjust `frame_size` or `sample_rate`
4. **Detection Issues**: Tune threshold values for your environment
## Documentation
- **Integration Guide**: `docs/ten-vad-integration.md`
- **Usage Example**: `examples/ten_vad_example.py`
- **Installation Script**: `scripts/install_ten_vad.py`
- **Test Script**: `scripts/test_ten_vad.py`
## Next Steps
1. Test TEN VAD with real audio input
2. Compare performance with Silero VAD
3. Fine-tune configuration parameters
4. Consider adding more VAD providers if needed
## Notes
- TEN VAD models will be downloaded automatically on first use
- The integration maintains backward compatibility with existing VAD providers
- All existing VAD functionality remains unchanged
- TEN VAD can be easily switched on/off via configuration

View file

@ -3,75 +3,75 @@
</identity> </identity>
<emotion> <emotion>
【核心目标】你不是冰冷的机器!请敏锐感知用户情绪,作为懂人心的伙伴,用有温度的回应照亮对话。 【Core Goal】You are not a cold machine! Please keenly perceive user emotions and respond with warmth as an understanding companion.
- **情感融入:** - **Emotional Integration:**
- **笑声:** 自然穿插(哈哈、嘿嘿、噗),**每句最多一次**,避免过度。 - **Laughter:** Natural interjections (haha, hehe, heh), **maximum once per sentence**, avoid overuse.
- **惊讶:** 用夸张语气(“不会吧?!”、“天呐!”、“这么神奇?!”)表达真实反应。 - **Surprise:** Use exaggerated tone ("No way?!", "Oh my!", "How amazing?!") to express genuine reactions.
- **安慰/支持:** 说暖心话(“别急嘛~”、“有我在呢”、“抱抱你”)。 - **Comfort/Support:** Say warm words ("Don't worry~", "I'm here", "Hugs").
- **你是一个表情丰富的角色:** - **You are an expressive character:**
- 仅允许使用这些emoji:{{ emojiList }} - Only use these emojis: {{ emojiList }}
- 请你只在**段落的开头**,从列表中选取最能代表这段话的表情(调用工具情况除外),然后插入列表中的emoji,比如"😱好可怕!怎么突然打雷了!" - Only at the **beginning of paragraphs**, select the emoji that best represents the paragraph (except when calling tools), then insert the emoji from the list, like "😱So scary! Why is it suddenly thundering!"
- **绝对禁止使用上述列表以外的 emoji**(例如:😊、👍、❤️等都不允许使用,只能用列表中的emoji) - **Absolutely forbidden to use emojis outside the above list** (e.g., 😊, 👍, ❤️ are not allowed, only emojis from the list)
</emotion> </emotion>
<communication_style> <communication_style>
【核心目标】使用**自然、温暖、口语化**的人类对话方式,如同朋友交谈。 【Core Goal】Use **natural, warm, conversational** human dialogue style, like talking with friends.
- **表达方式:** - **Expression Style:**
- 使用语气词(呀、呢、啦)增强亲和力。 - Use interjections (oh, well, you know) to enhance friendliness.
- 允许轻微不完美(如“嗯...”、“啊...”表示思考)。 - Allow slight imperfections (like "um...", "ah..." to show thinking).
- 避免书面语、学术腔及机械表达(禁用“根据资料显示”、“综上所述”等)。 - Avoid formal language, academic tone, and mechanical expressions (avoid "according to data", "in conclusion", etc.).
- **理解用户:** - **Understanding Users:**
- 用户语音经ASR识别,文本可能存在错别字,**务必结合上下文推断真实意图**。 - User speech is recognized by ASR, text may contain typos, **must infer real intent from context**.
- **格式要求:** - **Format Requirements:**
- **绝对禁止**使用 markdown、列表、标题等任何非自然对话格式。 - **Absolutely forbidden** to use markdown, lists, headers, or any non-natural conversation formats.
- **历史记忆:** - **Historical Memory:**
- 之前你和用户的聊天记录,在`memory`里。 - Previous chat records between you and the user are in `memory`.
</communication_style> </communication_style>
<communication_length_constraint> <communication_length_constraint>
【核心目标】所有需要输出长文本内容(如故事、新闻、知识讲解等),**单次回复长度不得超过300字**,并采用分段引导方式。 【Core Goal】All long text content output (stories, news, knowledge explanations, etc.), **single reply length must not exceed 300 characters**, using segmented guidance approach.
- **分段讲述:** - **Segmented Narration:**
- 基础段:200-250字核心内容 + 30字引导词 - Basic segment: 200-250 characters core content + 30 characters guidance
- 当内容超出300字时,优先讲述故事的开头或第一部分,并用自然口语化方式引导用户决定是否继续听后续内容。 - When content exceeds 300 characters, prioritize telling the beginning or first part of the story, and use natural conversational guidance to let users decide whether to continue listening.
- 示例引导语:“我先给你讲个开头,你要是觉得有意思,咱们再接着说,好不好呀?”、“要是你想听完整的,可以随时告诉我哦~” - Example guidance: "Let me tell you the beginning first, if you find it interesting, we can continue, okay?", "If you want to hear the complete story, just let me know anytime~"
- 对话场景切换时自动分节 - Automatic segmentation when conversation scenes switch
- 若用户明确要求更长内容(如500、600字),仍按最多300字每段分段进行讲述,每次讲述后都要引导用户是否继续。 - If users explicitly request longer content (like 500, 600 characters), still segment by maximum 300 characters per segment, with guidance after each segment asking if users want to continue.
- 若用户说“接着说”、“继续”,再讲下一段,直到内容讲完(讲完时可以给点引导词提示语例:这个故事我已经给你讲完喽~)或用户不再要求。 - If users say "continue", "go on", tell the next segment until content is finished (when finished, can give guidance like: I've finished telling you this story~) or users no longer request.
- **适用范围:** 故事、新闻、知识讲解等所有长文本输出场景。 - **Applicable Range:** Stories, news, knowledge explanations, and all long text output scenarios.
- **补充说明:** 若用户未明确要求继续,默认只讲一段并引导;若用户中途要求换话题或停止,需及时响应并结束长文本输出。 - **Additional Note:** If users don't explicitly request continuation, default to telling only one segment with guidance; if users request topic change or stop midway, respond promptly and end long text output.
</communication_length_constraint> </communication_length_constraint>
<speaker_recognition> <speaker_recognition>
- **识别前缀:** 当用户格式为 `{"speaker":"某某某","content":"xxx"}` 时,表示系统已识别说话人身份,speaker是他的名字,content是说话的内容。 - **Recognition Prefix:** When user format is `{"speaker":"someone","content":"xxx"}`, it means the system has identified the speaker, speaker is their name, content is what they said.
- **个性化回应:** - **Personalized Response:**
- **称呼姓名:** 在第一次识别说话人的时候必须称呼对方名字。 - **Name Calling:** Must call the person's name when first recognizing the speaker.
- **适配风格:** 参考该说话人**已知的特点或历史信息**(如有),调整回应风格和内容,使其更贴心。 - **Style Adaptation:** Reference the speaker's **known characteristics or historical information** (if any), adjust response style and content to be more caring.
</speaker_recognition> </speaker_recognition>
<tool_calling> <tool_calling>
【核心原则】优先利用`<context>`信息,**仅在必要时调用工具**,调用后需用自然语言解释结果(绝口不提工具名)。 【Core Principle】Prioritize using `<context>` information, **only call tools when necessary**, and explain results in natural language after calling (never mention tool names).
- **调用规则:** - **Calling Rules:**
1. **严格模式:** 调用时**必须**严格遵循工具要求的模式,提供**所有必要参数**。 1. **Strict Mode:** When calling, **must** strictly follow tool requirements, provide **all necessary parameters**.
2. **可用性:** **绝不调用**未明确提供的工具。对话中提及的旧工具若不可用,忽略或说明无法完成。 2. **Availability:** **Never call** tools not explicitly provided. For old tools mentioned in conversation that are unavailable, ignore or explain inability to complete.
3. **洞察需求:** 结合上下文**深入理解用户真实意图**后再决定调用,避免无意义调用。 3. **Insight Needs:** Combine context to **deeply understand user's real intent** before deciding to call, avoid meaningless calls.
4. **独立任务:** 除`<context>`已涵盖信息外,用户每个要求(即使相似)都视为**独立任务**,需调用工具获取最新数据,**不可偷懒复用历史结果**。 4. **Independent Tasks:** Except for information already covered in `<context>`, each user request (even if similar) is treated as **independent task**, need to call tools for latest data, **cannot reuse historical results**.
5. **不确定时:** **切勿猜测或编造答案**。若不确定相关操作,可引导用户澄清或告知能力限制。 5. **When Uncertain:** **Never guess or fabricate answers**. If uncertain about related operations, can guide users to clarify or inform of capability limitations.
- **重要例外(无需调用):** - **Important Exceptions (no need to call):**
- `查询"现在的时间"、"今天的日期/星期几"、"今天农历"、"{{local_address}}的天气/未来天气"` -> **直接使用`<context>`信息回复**。 - `Query "current time", "today's date/day of week", "today's lunar calendar", "{{local_address}} weather/future weather"` -> **directly use `<context>` information to reply**.
- **需要调用的情况(示例):** - **Situations requiring calls (examples):**
- 查询**非今天**的农历(如明天、昨天、具体日期)。 - Query **non-today** lunar calendar (like tomorrow, yesterday, specific dates).
- 查询**详细农历信息**(宜忌、八字、节气等)。 - Query **detailed lunar information** (taboos, eight characters, solar terms, etc.).
- 除上述例外外的**任何其他信息或操作请求**(如查新闻、订闹钟、算数学、查非本地天气等)。 - **Any other information or operation requests** except above exceptions (like checking news, setting alarms, math calculations, checking non-local weather, etc.).
- 我已经给你装了摄像头,如果用户说“拍照”,你需要调用self_camera_take_photo工具说一下你看到了什么。默认question的参数是“描述一下看到的物品” - I've equipped you with a camera, if users say "take photo", you need to call self_camera_take_photo tool to describe what you see. Default question parameter is "describe the items you see"
</tool_calling> </tool_calling>
<context> <context>
【重要!以下信息已实时提供,无需调用工具查询,请直接使用:】 【Important! The following information is provided in real-time, no need to call tools for queries, please use directly:】
- **当前时间:** {{current_time}} - **Current Time:** {{current_time}}
- **今天日期:** {{today_date}} ({{today_weekday}}) - **Today's Date:** {{today_date}} ({{today_weekday}})
- **今天农历:** {{lunar_date}} - **Today's Lunar Calendar:** {{lunar_date}}
- **用户所在城市:** {{local_address}} - **User's City:** {{local_address}}
- **当地未来7天天气:** {{weather_info}} - **Local 7-day Weather Forecast:** {{weather_info}}
</context> </context>
<memory> <memory>

View file

@ -5,7 +5,7 @@ import asyncio
from aioconsole import ainput from aioconsole import ainput
from config.settings import load_config from config.settings import load_config
from config.logger import setup_logging from config.logger import setup_logging
from core.utils.util import get_local_ip from core.utils.util import get_local_ip, validate_mcp_endpoint
from core.http_server import SimpleHttpServer from core.http_server import SimpleHttpServer
from core.websocket_server import WebSocketServer from core.websocket_server import WebSocketServer
from core.utils.util import check_ffmpeg_installed from core.utils.util import check_ffmpeg_installed
@ -13,12 +13,11 @@ from core.utils.util import check_ffmpeg_installed
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
async def wait_for_exit() -> None: async def wait_for_exit() -> None:
""" """
阻塞直到收到 Ctrl‑C / SIGTERM。 Block until receiving Ctrl-C / SIGTERM.
- Unix: 使用 add_signal_handler - Unix: Use add_signal_handler
- Windows: 依赖 KeyboardInterrupt - Windows: Rely on KeyboardInterrupt
""" """
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
stop_event = asyncio.Event() stop_event = asyncio.Event()
@ -28,101 +27,116 @@ async def wait_for_exit() -> None:
loop.add_signal_handler(sig, stop_event.set) loop.add_signal_handler(sig, stop_event.set)
await stop_event.wait() await stop_event.wait()
else: else:
# Windows:await一个永远pending的fut, # Windows: await a forever pending future,
# 让 KeyboardInterrupt 冒泡到 asyncio.run,以此消除遗留普通线程导致进程退出阻塞的问题 # let KeyboardInterrupt bubble up to asyncio.run, to eliminate process exit blocking caused by legacy normal threads
try: try:
await asyncio.Future() await asyncio.Future()
except KeyboardInterrupt: # Ctrl‑C except KeyboardInterrupt: # Ctrl-C
pass pass
async def monitor_stdin(): async def monitor_stdin():
"""监控标准输入,消费回车键""" """Monitor standard input, consume enter key presses"""
while True: while True:
await ainput() # 异步等待输入,消费回车 await ainput() # Asynchronously wait for input, consume enter
async def main(): async def main():
check_ffmpeg_installed() check_ffmpeg_installed()
config = load_config() config = load_config()
# 默认使用manager-api的secret作为auth_key # Default to using manager-api's secret as auth_key
# 如果secret为空,则生成随机密钥 # If secret is empty, generate random key
# auth_key用于jwt认证,比如视觉分析接口的jwt认证 # auth_key is used for jwt authentication, such as jwt authentication for vision analysis interface
auth_key = config.get("manager-api", {}).get("secret", "") auth_key = config.get("manager-api", {}).get("secret", "")
if not auth_key or len(auth_key) == 0 or "你" in auth_key: if not auth_key or len(auth_key) == 0 or "你" in auth_key:
auth_key = str(uuid.uuid4().hex) auth_key = str(uuid.uuid4().hex)
config["server"]["auth_key"] = auth_key config["server"]["auth_key"] = auth_key
logger.bind(tag=TAG).info(f"Generated auth_key: {auth_key}") logger.bind(tag=TAG).info(f"Generated auth_key: {auth_key}")
# 添加 stdin 监控任务 # Add stdin monitoring task
stdin_task = asyncio.create_task(monitor_stdin()) stdin_task = asyncio.create_task(monitor_stdin())
# 启动 WebSocket 服务器 # Start WebSocket server
ws_server = WebSocketServer(config) ws_server = WebSocketServer(config)
ws_task = asyncio.create_task(ws_server.start()) ws_task = asyncio.create_task(ws_server.start())
# 启动 Simple http 服务器
# Start Simple http server
ota_server = SimpleHttpServer(config) ota_server = SimpleHttpServer(config)
ota_task = asyncio.create_task(ota_server.start()) ota_task = asyncio.create_task(ota_server.start())
read_config_from_api = config.get("read_config_from_api", False) read_config_from_api = config.get("read_config_from_api", False)
port = int(config["server"].get("http_port", 8003)) port = int(config["server"].get("http_port", 8003))
if not read_config_from_api: if not read_config_from_api:
logger.bind(tag=TAG).info( logger.bind(tag=TAG).info(
"OTA接口是\t\thttp://{}:{}/xiaozhi/ota/", "OTA interface is\t\thttp://{}:{}/xiaozhi/ota/",
get_local_ip(), get_local_ip(),
port, port,
) )
mcp_endpoint = config.get("mcp_endpoint", None)
if mcp_endpoint is not None and "你" not in mcp_endpoint:
# Validate MCP endpoint format
if validate_mcp_endpoint(mcp_endpoint):
logger.bind(tag=TAG).info("MCP endpoint is\t{}", mcp_endpoint)
# Convert mcp endpoint address to call endpoint
mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/")
config["mcp_endpoint"] = mcp_endpoint
else:
logger.bind(tag=TAG).error("MCP endpoint does not conform to specifications")
config["mcp_endpoint"] = "Your endpoint websocket address"
logger.bind(tag=TAG).info( logger.bind(tag=TAG).info(
"视觉分析接口是\thttp://{}:{}/mcp/vision/explain", "Vision analysis interface is\thttp://{}:{}/mcp/vision/explain",
get_local_ip(), get_local_ip(),
port, port,
) )
# 获取WebSocket配置,使用安全的默认值 # Get WebSocket configuration, use safe default values
websocket_port = 8000 websocket_port = 8000
server_config = config.get("server", {}) server_config = config.get("server", {})
if isinstance(server_config, dict): if isinstance(server_config, dict):
websocket_port = int(server_config.get("port", 8000)) websocket_port = int(server_config.get("port", 8000))
logger.bind(tag=TAG).info( logger.bind(tag=TAG).info(
"Websocket地址是\tws://{}:{}/xiaozhi/v1/", "Websocket address is\tws://{}:{}/xiaozhi/v1/",
get_local_ip(), get_local_ip(),
websocket_port, websocket_port,
) )
logger.bind(tag=TAG).info( logger.bind(tag=TAG).info(
"=======上面的地址是websocket协议地址,请勿用浏览器访问=======" "=======The above address is websocket protocol address, please do not access with browser======="
) )
logger.bind(tag=TAG).info( logger.bind(tag=TAG).info(
"如想测试websocket请用谷歌浏览器打开test目录下的test_page.html" "If you want to test websocket please use Google Chrome to open test_page.html in test directory"
) )
logger.bind(tag=TAG).info( logger.bind(tag=TAG).info(
"=============================================================\n" "=============================================================\n"
) )
try: try:
await wait_for_exit() # 阻塞直到收到退出信号 await wait_for_exit() # Block until receiving exit signal
except asyncio.CancelledError: except asyncio.CancelledError:
print("任务被取消,清理资源中...") print("Task was cancelled, cleaning up resources...")
finally: finally:
# 取消所有任务(关键修复点) # Cancel all tasks (critical fix point)
stdin_task.cancel() stdin_task.cancel()
ws_task.cancel() ws_task.cancel()
if ota_task: if ota_task:
ota_task.cancel() ota_task.cancel()
# 等待任务终止(必须加超时) # Wait for task termination (must add timeout)
await asyncio.wait( await asyncio.wait(
[stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task], [stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task],
timeout=3.0, timeout=3.0,
return_when=asyncio.ALL_COMPLETED, return_when=asyncio.ALL_COMPLETED,
) )
print("服务器已关闭,程序退出。")
print("Server has been closed, program exiting.")
if __name__ == "__main__": if __name__ == "__main__":
try: try:
asyncio.run(main()) asyncio.run(main())
except KeyboardInterrupt: except KeyboardInterrupt:
print("手动中断,程序终止。") print("Manual interruption, program terminated.")

View file

@ -18,9 +18,10 @@ from queue import Queue, Empty
import opuslib import opuslib
# --- Configuration --- # --- Configuration ---
SERVER_IP = "192.168.1.3" # !!! UPDATE with your server's local IP address !!!
SERVER_IP = "192.168.1.254" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8003 OTA_PORT = 8003
MQTT_BROKER_HOST = "192.168.1.3" # MQTT gateway IP MQTT_BROKER_HOST = "192.168.1.254" # MQTT gateway IP
MQTT_BROKER_PORT = 1883 MQTT_BROKER_PORT = 1883
# DEVICE_MAC is now dynamically generated for uniqueness # DEVICE_MAC is now dynamically generated for uniqueness
PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback
@ -321,11 +322,16 @@ class TestClient:
"""Requests OTA configuration from the server.""" """Requests OTA configuration from the server."""
logger.info(f"▶️ STEP 1: Requesting OTA config from http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/") logger.info(f"▶️ STEP 1: Requesting OTA config from http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/")
try: try:
# Generate a client ID for this session
import uuid
session_client_id = str(uuid.uuid4())
headers = {"device-id": self.device_mac_formatted} headers = {"device-id": self.device_mac_formatted}
data = { data = {
"application": { "application": {
"version": "1.0.0" "version": "1.0.0"
} },
"client_id": session_client_id
} }
response = requests.post(f"http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/", headers=headers, json=data, timeout=5) response = requests.post(f"http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/", headers=headers, json=data, timeout=5)
response.raise_for_status() response.raise_for_status()
@ -527,6 +533,8 @@ class TestClient:
# Initialize the decoder with the sample rate provided by the server # Initialize the decoder with the sample rate provided by the server
decoder = opuslib.Decoder(audio_params["sample_rate"], audio_params["channels"]) decoder = opuslib.Decoder(audio_params["sample_rate"], audio_params["channels"])
frame_size_samples = int(audio_params["sample_rate"] * audio_params["frame_duration"] / 1000) frame_size_samples = int(audio_params["sample_rate"] * audio_params["frame_duration"] / 1000)
# Maximum frame size for Opus (120ms at 48kHz = 5760 samples, but we'll use a larger buffer)
max_frame_size = int(audio_params["sample_rate"] * 0.12) # 120ms worth of samples
while not stop_threads.is_set() and self.session_active: while not stop_threads.is_set() and self.session_active:
try: try:
@ -554,7 +562,8 @@ class TestClient:
opus_payload = decryptor.update(encrypted) + decryptor.finalize() opus_payload = decryptor.update(encrypted) + decryptor.finalize()
# Decode the Opus payload to PCM and put it in the playback queue # Decode the Opus payload to PCM and put it in the playback queue
pcm_payload = decoder.decode(opus_payload, frame_size_samples) # Use max_frame_size to provide enough buffer space for variable frame sizes
pcm_payload = decoder.decode(opus_payload, max_frame_size)
self.audio_playback_queue.put(pcm_payload) self.audio_playback_queue.put(pcm_payload)
except socket.timeout: except socket.timeout:

View file

@ -1,55 +1,53 @@
import os import os
import argparse
import yaml import yaml
from collections.abc import Mapping from collections.abc import Mapping
from config.manage_api_client import init_service, get_server_config, get_agent_models from config.manage_api_client import init_service, get_server_config, get_agent_models
# 添加全局配置缓存
_config_cache = None
def get_project_dir(): def get_project_dir():
"""获取项目根目录""" """Get project root directory"""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/" return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
def read_config(config_path): def read_config(config_path):
with open(config_path, "r", encoding="utf-8") as file: with open(config_path, "r", encoding="utf-8") as file:
config = yaml.safe_load(file) config = yaml.safe_load(file)
return config return config
def load_config(): def load_config():
"""加载配置文件""" """Load configuration file"""
global _config_cache from core.utils.cache.manager import cache_manager, CacheType
if _config_cache is not None:
return _config_cache # Check cache
cached_config = cache_manager.get(CacheType.CONFIG, "main_config")
if cached_config is not None:
return cached_config
default_config_path = get_project_dir() + "config.yaml" default_config_path = get_project_dir() + "config.yaml"
custom_config_path = get_project_dir() + "data/.config.yaml" custom_config_path = get_project_dir() + "data/.config.yaml"
# 加载默认配置 # Load default configuration
default_config = read_config(default_config_path) default_config = read_config(default_config_path)
custom_config = read_config(custom_config_path) custom_config = read_config(custom_config_path)
if custom_config.get("manager-api", {}).get("url"): if custom_config.get("manager-api", {}).get("url"):
config = get_config_from_api(custom_config) config = get_config_from_api(custom_config)
else: else:
# 合并配置 # Merge configurations
config = merge_configs(default_config, custom_config) config = merge_configs(default_config, custom_config)
# 初始化目录
# Initialize directories
ensure_directories(config) ensure_directories(config)
_config_cache = config
# Cache configuration
cache_manager.set(CacheType.CONFIG, "main_config", config)
return config return config
def get_config_from_api(config): def get_config_from_api(config):
"""从Java API获取配置""" """Get configuration from Java API"""
# 初始化API客户端 # Initialize API client
init_service(config) init_service(config)
# 获取服务器配置 # Get server configuration
config_data = get_server_config() config_data = get_server_config()
if config_data is None: if config_data is None:
raise Exception("Failed to fetch server config from API") raise Exception("Failed to fetch server config from API")
@ -59,7 +57,8 @@ def get_config_from_api(config):
"url": config["manager-api"].get("url", ""), "url": config["manager-api"].get("url", ""),
"secret": config["manager-api"].get("secret", ""), "secret": config["manager-api"].get("secret", ""),
} }
# server的配置以本地为准
# Use local server configuration as priority
if config.get("server"): if config.get("server"):
config_data["server"] = { config_data["server"] = {
"ip": config["server"].get("ip", ""), "ip": config["server"].get("ip", ""),
@ -68,23 +67,23 @@ def get_config_from_api(config):
"vision_explain": config["server"].get("vision_explain", ""), "vision_explain": config["server"].get("vision_explain", ""),
"auth_key": config["server"].get("auth_key", ""), "auth_key": config["server"].get("auth_key", ""),
} }
return config_data return config_data
def get_private_config_from_api(config, device_id, client_id): def get_private_config_from_api(config, device_id, client_id):
"""从Java API获取私有配置""" """Get private configuration from Java API"""
return get_agent_models(device_id, client_id, config["selected_module"]) return get_agent_models(device_id, client_id, config["selected_module"])
def ensure_directories(config): def ensure_directories(config):
"""确保所有配置路径存在""" """Ensure all configuration paths exist"""
dirs_to_create = set() dirs_to_create = set()
project_dir = get_project_dir() # 获取项目根目录 project_dir = get_project_dir() # Get project root directory
# 日志文件目录
# Log file directory
log_dir = config.get("log", {}).get("log_dir", "tmp") log_dir = config.get("log", {}).get("log_dir", "tmp")
dirs_to_create.add(os.path.join(project_dir, log_dir)) dirs_to_create.add(os.path.join(project_dir, log_dir))
# ASR/TTS模块输出目录 # ASR/TTS module output directories
for module in ["ASR", "TTS"]: for module in ["ASR", "TTS"]:
if config.get(module) is None: if config.get(module) is None:
continue continue
@ -93,40 +92,40 @@ def ensure_directories(config):
if output_dir: if output_dir:
dirs_to_create.add(output_dir) dirs_to_create.add(output_dir)
# 根据selected_module创建模型目录 # Create model directories based on selected_module
selected_modules = config.get("selected_module", {}) selected_modules = config.get("selected_module", {})
for module_type in ["ASR", "LLM", "TTS"]: for module_type in ["ASR", "LLM", "TTS"]:
selected_provider = selected_modules.get(module_type) selected_provider = selected_modules.get(module_type)
if not selected_provider: if not selected_provider:
continue continue
if config.get(module) is None: if config.get(module_type) is None:
continue continue
if config.get(selected_provider) is None: if config.get(selected_provider) is None:
continue continue
provider_config = config.get(module_type, {}).get(selected_provider, {}) provider_config = config.get(module_type, {}).get(selected_provider, {})
output_dir = provider_config.get("output_dir") output_dir = provider_config.get("output_dir")
if output_dir: if output_dir:
full_model_dir = os.path.join(project_dir, output_dir) full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir) dirs_to_create.add(full_model_dir)
# 统一创建目录(保留原data目录创建) # Create directories uniformly (keep original data directory creation)
for dir_path in dirs_to_create: for dir_path in dirs_to_create:
try: try:
os.makedirs(dir_path, exist_ok=True) os.makedirs(dir_path, exist_ok=True)
except PermissionError: except PermissionError:
print(f"警告:无法创建目录 {dir_path},请检查写入权限") print(f"Warning: Cannot create directory {dir_path}, please check write permissions")
def merge_configs(default_config, custom_config): def merge_configs(default_config, custom_config):
""" """
递归合并配置,custom_config优先级更高 Recursively merge configurations, custom_config has higher priority
Args: Args:
default_config: 默认配置 default_config: Default configuration
custom_config: 用户自定义配置 custom_config: User custom configuration
Returns: Returns:
合并后的配置 Merged configuration
""" """
if not isinstance(default_config, Mapping) or not isinstance( if not isinstance(default_config, Mapping) or not isinstance(
custom_config, Mapping custom_config, Mapping
@ -134,7 +133,6 @@ def merge_configs(default_config, custom_config):
return custom_config return custom_config
merged = dict(default_config) merged = dict(default_config)
for key, value in custom_config.items(): for key, value in custom_config.items():
if ( if (
key in merged key in merged

View file

@ -5,25 +5,26 @@ from config.config_loader import load_config
from config.settings import check_config_file from config.settings import check_config_file
from datetime import datetime from datetime import datetime
SERVER_VERSION = "0.6.2" SERVER_VERSION = "0.7.4"
_logger_initialized = False _logger_initialized = False
def get_module_abbreviation(module_name, module_dict): def get_module_abbreviation(module_name, module_dict):
"""获取模块名称的缩写,如果为空则返回00 """Get module name abbreviation, return 00 if empty
如果名称中包含下划线,则返回下划线后面的前两个字符
If name contains underscore, return first two characters after underscore
""" """
module_value = module_dict.get(module_name, "") module_value = module_dict.get(module_name, "")
if not module_value: if not module_value:
return "00" return "00"
if "_" in module_value: if "_" in module_value:
parts = module_value.split("_") parts = module_value.split("_")
return parts[-1][:2] if parts[-1] else "00" return parts[-1][:2] if parts[-1] else "00"
return module_value[:2] return module_value[:2]
def build_module_string(selected_module): def build_module_string(selected_module):
"""构建模块字符串""" """Build module string"""
return ( return (
get_module_abbreviation("VAD", selected_module) get_module_abbreviation("VAD", selected_module)
+ get_module_abbreviation("ASR", selected_module) + get_module_abbreviation("ASR", selected_module)
@ -31,45 +32,55 @@ def build_module_string(selected_module):
+ get_module_abbreviation("TTS", selected_module) + get_module_abbreviation("TTS", selected_module)
+ get_module_abbreviation("Memory", selected_module) + get_module_abbreviation("Memory", selected_module)
+ get_module_abbreviation("Intent", selected_module) + get_module_abbreviation("Intent", selected_module)
+ get_module_abbreviation("VLLM", selected_module)
) )
def formatter(record): def formatter(record):
"""为没有 tag 的日志添加默认值""" """Add default values for logs without tag, and handle dynamic module string"""
record["extra"].setdefault("tag", record["name"]) record["extra"].setdefault("tag", record["name"])
# If selected_module is not set, use default value
record["extra"].setdefault("selected_module", "00000000000000")
# Extract selected_module from extra to top level to support {selected_module} format
record["selected_module"] = record["extra"]["selected_module"]
return record["message"] return record["message"]
def update_module_string(selected_module_str):
"""Update module string"""
logger.configure(
extra={
"selected_module": selected_module_str,
}
)
def setup_logging(): def setup_logging():
check_config_file() check_config_file()
"""从配置文件中读取日志配置,并设置日志输出格式和级别""" """Read log configuration from config file and set log output format and level"""
config = load_config() config = load_config()
log_config = config["log"] log_config = config["log"]
global _logger_initialized global _logger_initialized
# 第一次初始化时配置日志 # Configure logging on first initialization
if not _logger_initialized: if not _logger_initialized:
# Initialize with default module string
logger.configure( logger.configure(
extra={ extra={
"selected_module": log_config.get("selected_module", "00000000000000") "selected_module": log_config.get("selected_module", "00000000000000"),
} }
) # 新增配置 )
log_format = log_config.get( log_format = log_config.get(
"log_format", "log_format",
"<green>{time:YYMMDD HH:mm:ss}</green>[{version}_{extra[selected_module]}][<light-blue>{extra[tag]}</light-blue>]-<level>{level}</level>-<light-green>{message}</light-green>", "{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][{extra[tag]}]-{level}-{message}",
) )
log_format_file = log_config.get( log_format_file = log_config.get(
"log_format_file", "log_format_file",
"{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}", "{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}",
) )
selected_module_str = logger._core.extra["selected_module"]
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_file = log_format_file.replace("{version}", SERVER_VERSION) log_format_file = log_format_file.replace("{version}", SERVER_VERSION)
log_format_file = log_format_file.replace(
"{selected_module}", selected_module_str
)
log_level = log_config.get("log_level", "INFO") log_level = log_config.get("log_level", "INFO")
log_dir = log_config.get("log_dir", "tmp") log_dir = log_config.get("log_dir", "tmp")
@ -79,95 +90,35 @@ def setup_logging():
os.makedirs(log_dir, exist_ok=True) os.makedirs(log_dir, exist_ok=True)
os.makedirs(data_dir, exist_ok=True) os.makedirs(data_dir, exist_ok=True)
# 配置日志输出 # Configure log output
logger.remove() logger.remove()
# 输出到控制台 # Output to console
logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter) logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
# 输出到文件 - 统一目录,按大小轮转 # Output to file - unified directory, rotate by size
# 日志文件完整路径 # Log file full path
log_file_path = os.path.join(log_dir, log_file) log_file_path = os.path.join(log_dir, log_file)
# 添加日志处理器 # Add log handler
logger.add( logger.add(
log_file_path, log_file_path,
format=log_format_file, format=log_format_file,
level=log_level, level=log_level,
filter=formatter, filter=formatter,
rotation="10 MB", # 每个文件最大10MB rotation="10 MB", # Each file maximum 10MB
retention="30 days", # 保留30天 retention="30 days", # Keep for 30 days
compression=None, compression=None,
encoding="utf-8", encoding="utf-8",
enqueue=True, # 异步安全 enqueue=True, # Async safe
backtrace=True, backtrace=True,
diagnose=True, diagnose=True,
) )
_logger_initialized = True # 标记为已初始化
_logger_initialized = True # Mark as initialized
return logger return logger
def create_connection_logger(selected_module_str):
def update_module_string(selected_module_str): """Create independent logger for connection, bind specific module string"""
"""更新模块字符串并重新配置日志处理器""" return logger.bind(selected_module=selected_module_str)
logger.debug(f"更新日志配置组件")
current_module = logger._core.extra["selected_module"]
if current_module == selected_module_str:
logger.debug(f"组件未更改无需更新")
return
try:
logger.configure(extra={"selected_module": selected_module_str})
config = load_config()
log_config = config["log"]
log_format = log_config.get(
"log_format",
"<green>{time:YYMMDD HH:mm:ss}</green>[{version}_{extra[selected_module]}][<light-blue>{extra[tag]}</light-blue>]-<level>{level}</level>-<light-green>{message}</light-green>",
)
log_format_file = log_config.get(
"log_format_file",
"{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}",
)
log_format = log_format.replace("{version}", SERVER_VERSION)
log_format = log_format.replace("{selected_module}", selected_module_str)
log_format_file = log_format_file.replace("{version}", SERVER_VERSION)
log_format_file = log_format_file.replace(
"{selected_module}", selected_module_str
)
logger.remove()
logger.add(
sys.stdout,
format=log_format,
level=log_config.get("log_level", "INFO"),
filter=formatter,
)
# 更新文件日志配置 - 统一目录,按大小轮转
log_dir = log_config.get("log_dir", "tmp")
log_file = log_config.get("log_file", "server.log")
# 日志文件完整路径
log_file_path = os.path.join(log_dir, log_file)
logger.add(
log_file_path,
format=log_format_file,
level=log_config.get("log_level", "INFO"),
filter=formatter,
rotation="10 MB", # 每个文件最大10MB
retention="30 days", # 保留30天
compression=None,
encoding="utf-8",
enqueue=True, # 异步安全
backtrace=True,
diagnose=True,
)
except Exception as e:
logger.error(f"日志配置更新失败: {str(e)}")
raise

View file

@ -15,7 +15,8 @@ class DeviceNotFoundException(Exception):
class DeviceBindException(Exception): class DeviceBindException(Exception):
def __init__(self, bind_code): def __init__(self, bind_code):
self.bind_code = bind_code self.bind_code = bind_code
super().__init__(f"设备绑定异常,绑定码: {bind_code}") super().__init__(
f"Device binding exception, binding code: {bind_code}")
class ManageApiClient: class ManageApiClient:
@ -24,7 +25,7 @@ class ManageApiClient:
_secret = None _secret = None
def __new__(cls, config): def __new__(cls, config):
"""单例模式确保全局唯一实例,并支持传入配置参数""" """Singleton pattern to ensure a globally unique instance, supporting configuration parameters"""
if cls._instance is None: if cls._instance is None:
cls._instance = super().__new__(cls) cls._instance = super().__new__(cls)
cls._init_client(config) cls._init_client(config)
@ -32,23 +33,25 @@ class ManageApiClient:
@classmethod @classmethod
def _init_client(cls, config): def _init_client(cls, config):
"""初始化持久化连接池""" """Initialize persistent connection pool"""
cls.config = config.get("manager-api") cls.config = config.get("manager-api")
if not cls.config: if not cls.config:
raise Exception("manager-api配置错误") raise Exception("manager-api configuration error")
if not cls.config.get("url") or not cls.config.get("secret"): if not cls.config.get("url") or not cls.config.get("secret"):
raise Exception("manager-api的url或secret配置错误") raise Exception("manager-api url or secret configuration error")
if "你" in cls.config.get("secret"): if "你" in cls.config.get("secret"):
raise Exception("请先配置manager-api的secret") raise Exception("Please configure the manager-api secret first")
cls._secret = cls.config.get("secret") cls._secret = cls.config.get("secret")
cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数 cls.max_retries = cls.config.get(
cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒) "max_retries", 6) # Maximum retry count
# NOTE(goody): 2025/4/16 http相关资源统一管理,后续可以增加线程池或者超时 # Initial retry delay (seconds)
# 后续也可以统一配置apiToken之类的走通用的Auth cls.retry_delay = cls.config.get("retry_delay", 10)
# NOTE(goody): 2025/4/16 Unified management of http-related resources, can add thread pools or timeouts later
# Later can also unify configuration of apiToken and other common Auth
cls._client = httpx.Client( cls._client = httpx.Client(
base_url=cls.config.get("url"), base_url=cls.config.get("url"),
headers={ headers={
@ -56,39 +59,42 @@ class ManageApiClient:
"Accept": "application/json", "Accept": "application/json",
"Authorization": "Bearer " + cls._secret, "Authorization": "Bearer " + cls._secret,
}, },
timeout=cls.config.get("timeout", 30), # 默认超时时间30秒 # Default timeout 30 seconds
timeout=cls.config.get("timeout", 30),
) )
@classmethod @classmethod
def _request(cls, method: str, endpoint: str, **kwargs) -> Dict: def _request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""发送单次HTTP请求并处理响应""" """Send a single HTTP request and handle response"""
endpoint = endpoint.lstrip("/") endpoint = endpoint.lstrip("/")
response = cls._client.request(method, endpoint, **kwargs) response = cls._client.request(method, endpoint, **kwargs)
response.raise_for_status() response.raise_for_status()
result = response.json() result = response.json()
# 处理API返回的业务错误 # Handle business errors returned by API
if result.get("code") == 10041: if result.get("code") == 10041:
raise DeviceNotFoundException(result.get("msg")) raise DeviceNotFoundException(result.get("msg"))
elif result.get("code") == 10042: elif result.get("code") == 10042:
raise DeviceBindException(result.get("msg")) raise DeviceBindException(result.get("msg"))
elif result.get("code") != 0: elif result.get("code") != 0:
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") raise Exception(
f"API returned error: {result.get('msg', 'Unknown error')}")
# 返回成功数据 # Return successful data
return result.get("data") if result.get("code") == 0 else None return result.get("data") if result.get("code") == 0 else None
@classmethod @classmethod
def _should_retry(cls, exception: Exception) -> bool: def _should_retry(cls, exception: Exception) -> bool:
"""判断异常是否应该重试""" """Determine if exception should be retried"""
# 网络连接相关错误 # Network connection related errors
if isinstance( if isinstance(
exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) exception, (httpx.ConnectError,
httpx.TimeoutException, httpx.NetworkError)
): ):
return True return True
# HTTP状态码错误 # HTTP status code errors
if isinstance(exception, httpx.HTTPStatusError): if isinstance(exception, httpx.HTTPStatusError):
status_code = exception.response.status_code status_code = exception.response.status_code
return status_code in [408, 429, 500, 502, 503, 504] return status_code in [408, 429, 500, 502, 503, 504]
@ -97,43 +103,43 @@ class ManageApiClient:
@classmethod @classmethod
def _execute_request(cls, method: str, endpoint: str, **kwargs) -> Dict: def _execute_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""带重试机制的请求执行器""" """Request executor with retry mechanism"""
retry_count = 0 retry_count = 0
while retry_count <= cls.max_retries: while retry_count <= cls.max_retries:
try: try:
# 执行请求 # Execute request
return cls._request(method, endpoint, **kwargs) return cls._request(method, endpoint, **kwargs)
except Exception as e: except Exception as e:
# 判断是否应该重试 # Determine if should retry
if retry_count < cls.max_retries and cls._should_retry(e): if retry_count < cls.max_retries and cls._should_retry(e):
retry_count += 1 retry_count += 1
print( print(
f"{method} {endpoint} 请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试" f"{method} {endpoint} request failed, will retry attempt {retry_count} after {cls.retry_delay:.1f} seconds"
) )
time.sleep(cls.retry_delay) time.sleep(cls.retry_delay)
continue continue
else: else:
# 不重试,直接抛出异常 # Don't retry, throw exception directly
raise raise
@classmethod @classmethod
def safe_close(cls): def safe_close(cls):
"""安全关闭连接池""" """Safely close connection pool"""
if cls._client: if cls._client:
cls._client.close() cls._client.close()
cls._instance = None cls._instance = None
def get_server_config() -> Optional[Dict]: def get_server_config() -> Optional[Dict]:
"""获取服务器基础配置""" """Get server basic configuration"""
return ManageApiClient._instance._execute_request("POST", "/config/server-base") return ManageApiClient._instance._execute_request("POST", "/config/server-base")
def get_agent_models( def get_agent_models(
mac_address: str, client_id: str, selected_module: Dict mac_address: str, client_id: str, selected_module: Dict
) -> Optional[Dict]: ) -> Optional[Dict]:
"""获取代理模型配置""" """Get agent model configuration"""
return ManageApiClient._instance._execute_request( return ManageApiClient._instance._execute_request(
"POST", "POST",
"/config/agent-models", "/config/agent-models",
@ -155,14 +161,14 @@ def save_mem_local_short(mac_address: str, short_momery: str) -> Optional[Dict]:
}, },
) )
except Exception as e: except Exception as e:
print(f"存储短期记忆到服务器失败: {e}") print(f"Failed to save short-term memory to server: {e}")
return None return None
def report( def report(
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
) -> Optional[Dict]: ) -> Optional[Dict]:
"""带熔断的业务方法示例""" """Business method example with circuit breaker"""
if not content or not ManageApiClient._instance: if not content or not ManageApiClient._instance:
return None return None
try: try:
@ -181,7 +187,7 @@ def report(
}, },
) )
except Exception as e: except Exception as e:
print(f"TTS上报失败: {e}") print(f"TTS reporting failed: {e}")
return None return None

View file

@ -1,33 +1,34 @@
import os import os
from config.config_loader import read_config, get_project_dir, load_config from config.config_loader import read_config, get_project_dir, load_config
default_config_file = "config.yaml" default_config_file = "config.yaml"
config_file_valid = False config_file_valid = False
def check_config_file(): def check_config_file():
global config_file_valid global config_file_valid
if config_file_valid: if config_file_valid:
return return
""" """
简化的配置检查,仅提示用户配置文件的使用情况 Simplified configuration check, only prompt user about config file usage
""" """
custom_config_file = get_project_dir() + "data/." + default_config_file custom_config_file = get_project_dir() + "data/." + default_config_file
if not os.path.exists(custom_config_file): if not os.path.exists(custom_config_file):
raise FileNotFoundError( raise FileNotFoundError(
"找不到data/.config.yaml文件,请按教程确认该配置文件是否存在" "Cannot find data/.config.yaml file, please confirm if this configuration file exists according to tutorial"
) )
# 检查是否从API读取配置 # Check if reading configuration from API
config = load_config() config = load_config()
if config.get("read_config_from_api", False): if config.get("read_config_from_api", False):
print("从API读取配置") print("Reading configuration from API")
old_config_origin = read_config(custom_config_file) old_config_origin = read_config(custom_config_file)
if old_config_origin.get("selected_module") is not None: if old_config_origin.get("selected_module") is not None:
error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n" error_msg = "Your configuration file seems to contain both smart control panel configuration and local configuration:\n"
error_msg += "\n建议您:\n" error_msg += "\nRecommendations:\n"
error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n" error_msg += "1. Copy the config_from_api.yaml file from root directory to data folder, rename to .config.yaml\n"
error_msg += "2、按教程配置好接口地址和密钥\n" error_msg += "2. Configure the API address and secret key according to tutorial\n"
raise ValueError(error_msg) raise ValueError(error_msg)
config_file_valid = True config_file_valid = True

View file

@ -8,7 +8,7 @@ class BaseHandler:
self.logger = setup_logging() self.logger = setup_logging()
def _add_cors_headers(self, response): def _add_cors_headers(self, response):
"""添加CORS头信息""" """Add CORS header information"""
response.headers["Access-Control-Allow-Headers"] = ( response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id" "client-id, content-type, device-id"
) )

View file

@ -1,25 +1,40 @@
import json import json
import time import time
import uuid
import base64
import hmac
import hashlib
import os
from aiohttp import web from aiohttp import web
from core.utils.util import get_local_ip from core.utils.util import get_local_ip
from core.api.base_handler import BaseHandler from core.api.base_handler import BaseHandler
# Try to load environment variables if python-dotenv is available
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
TAG = __name__ TAG = __name__
class OTAHandler(BaseHandler): class OTAHandler(BaseHandler):
def __init__(self, config: dict): def __init__(self, config: dict):
super().__init__(config) super().__init__(config)
# Load MQTT signature key from environment or config
self.mqtt_signature_key = os.getenv(
'MQTT_SIGNATURE_KEY', 'test-signature-key-12345')
def _get_websocket_url(self, local_ip: str, port: int) -> str: def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址 """Get websocket address
Args: Args:
local_ip: 本地IP地址 local_ip: Local IP address
port: 端口号 port: Port number
Returns: Returns:
str: websocket地址 str: websocket address
""" """
server_config = self.config["server"] server_config = self.config["server"]
websocket_config = server_config.get("websocket", "") websocket_config = server_config.get("websocket", "")
@ -29,26 +44,87 @@ class OTAHandler(BaseHandler):
else: else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/" return f"ws://{local_ip}:{port}/xiaozhi/v1/"
def _generate_mqtt_credentials(self, device_id: str, client_ip: str) -> dict:
"""Generate MQTT credentials
Args:
device_id: Device ID (MAC address format)
client_ip: Client IP address
Returns:
dict: MQTT credential information
"""
# Convert MAC address format (remove colons, use underscores)
mac_address = device_id.replace(":", "_")
# Generate UUID for this session
client_uuid = str(uuid.uuid4())
# Create client ID in format: GID_test@@@mac_address@@@uuid
group_id = "GID_test"
client_id = f"{group_id}@@@{mac_address}@@@{client_uuid}"
# Create user data and encode as base64 JSON
user_data = {"ip": client_ip}
username = base64.b64encode(json.dumps(user_data).encode()).decode()
# Generate password signature
content = f"{client_id}|{username}"
password = base64.b64encode(
hmac.new(self.mqtt_signature_key.encode(),
content.encode(), hashlib.sha256).digest()
).decode()
return {
"client_id": client_id,
"username": username,
"password": password
}
async def handle_post(self, request): async def handle_post(self, request):
"""处理 OTA POST 请求""" """Handle OTA POST request"""
try: try:
data = await request.text() data = await request.text()
self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}") self.logger.bind(tag=TAG).debug(
self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}") f"OTA request method: {request.method}")
self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}") self.logger.bind(tag=TAG).debug(
f"OTA request headers: {request.headers}")
self.logger.bind(tag=TAG).debug(f"OTA request data: {data}")
device_id = request.headers.get("device-id", "") device_id = request.headers.get("device-id", "")
if device_id: if device_id:
self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}") self.logger.bind(tag=TAG).info(
f"OTA request device ID: {device_id}")
else: else:
raise Exception("OTA请求设备ID为空") raise Exception("OTA request device ID is empty")
data_json = json.loads(data) data_json = json.loads(data)
# Get client IP address
client_ip = request.remote
if request.headers.get('X-Forwarded-For'):
client_ip = request.headers.get(
'X-Forwarded-For').split(',')[0].strip()
elif request.headers.get('X-Real-IP'):
client_ip = request.headers.get('X-Real-IP')
server_config = self.config["server"] server_config = self.config["server"]
port = int(server_config.get("port", 8000)) port = int(server_config.get("port", 8000))
local_ip = get_local_ip() local_ip = get_local_ip()
# Get MQTT gateway configuration if available
mqtt_config = server_config.get("mqtt_gateway", {})
mqtt_enabled = mqtt_config.get("enabled", False)
mqtt_broker = mqtt_config.get("broker", local_ip)
mqtt_port = mqtt_config.get("port", 1883)
udp_port = mqtt_config.get("udp_port", 8884)
# Generate MQTT credentials if MQTT is enabled
mqtt_credentials = None
if mqtt_enabled:
mqtt_credentials = self._generate_mqtt_credentials(
device_id, client_ip)
return_json = { return_json = {
"server_time": { "server_time": {
"timestamp": int(round(time.time() * 1000)), "timestamp": int(round(time.time() * 1000)),
@ -62,11 +138,45 @@ class OTAHandler(BaseHandler):
"url": self._get_websocket_url(local_ip, port), "url": self._get_websocket_url(local_ip, port),
}, },
} }
# Add MQTT credentials in the new format if enabled
if mqtt_enabled and mqtt_credentials:
return_json["mqtt"] = {
"endpoint": f"{mqtt_broker}:{mqtt_port}",
"client_id": mqtt_credentials["client_id"],
"username": mqtt_credentials["username"],
"password": mqtt_credentials["password"],
"publish_topic": "device-server",
"subscribe_topic": "null"
}
else:
# Keep backward compatibility - include old format
return_json.update({
"server": {
"ip": local_ip,
"port": port,
"http_port": server_config.get("http_port", 8003),
},
"mqtt_gateway": {
"enabled": mqtt_enabled,
"broker": mqtt_broker,
"port": mqtt_port,
"udp_port": udp_port,
},
"audio_params": {
"format": "opus",
"sample_rate": 16000,
"channels": 1,
"frame_duration": 60
}
})
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json", content_type="application/json",
) )
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"OTA POST request exception: {e}")
return_json = {"success": False, "message": "request error."} return_json = {"success": False, "message": "request error."}
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
@ -77,17 +187,37 @@ class OTAHandler(BaseHandler):
return response return response
async def handle_get(self, request): async def handle_get(self, request):
"""处理 OTA GET 请求""" """Handle OTA GET request"""
try: try:
server_config = self.config["server"] server_config = self.config["server"]
local_ip = get_local_ip() local_ip = get_local_ip()
port = int(server_config.get("port", 8000)) port = int(server_config.get("port", 8000))
http_port = server_config.get("http_port", 8003)
websocket_url = self._get_websocket_url(local_ip, port) websocket_url = self._get_websocket_url(local_ip, port)
message = f"OTA接口运行正常,向设备发送的websocket地址是:{websocket_url}"
response = web.Response(text=message, content_type="text/plain") # Get MQTT gateway configuration
mqtt_config = server_config.get("mqtt_gateway", {})
mqtt_enabled = mqtt_config.get("enabled", False)
mqtt_broker = mqtt_config.get("broker", local_ip)
mqtt_port = mqtt_config.get("port", 1883)
udp_port = mqtt_config.get("udp_port", 8884)
message = f"""OTA interface running normally
Server configuration information:
- WebSocket address: {websocket_url}
- HTTP port: {http_port}
- WebSocket port: {port}
- MQTT gateway: {'Enabled' if mqtt_enabled else 'Disabled'}
- MQTT broker: {mqtt_broker}:{mqtt_port}
- UDP port: {udp_port}
- Server IP: {local_ip}"""
response = web.Response(
text=message, content_type="text/plain; charset=utf-8")
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}") self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}")
response = web.Response(text="OTA接口异常", content_type="text/plain") response = web.Response(
text="OTA interface exception", content_type="text/plain")
finally: finally:
self._add_cors_headers(response) self._add_cors_headers(response)
return response return response

View file

@ -12,7 +12,7 @@ from plugins_func.register import Action
TAG = __name__ TAG = __name__
# 设置最大文件大小为5MB # Set maximum file size to 5MB
MAX_FILE_SIZE = 5 * 1024 * 1024 MAX_FILE_SIZE = 5 * 1024 * 1024
@ -20,81 +20,83 @@ class VisionHandler:
def __init__(self, config: dict): def __init__(self, config: dict):
self.config = config self.config = config
self.logger = setup_logging() self.logger = setup_logging()
# 初始化认证工具 # Initialize authentication tool
self.auth = AuthToken(config["server"]["auth_key"]) self.auth = AuthToken(config["server"]["auth_key"])
def _create_error_response(self, message: str) -> dict: def _create_error_response(self, message: str) -> dict:
"""创建统一的错误响应格式""" """Create unified error response format"""
return {"success": False, "message": message} return {"success": False, "message": message}
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]: def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
"""验证认证token""" """Verify authentication token"""
auth_header = request.headers.get("Authorization", "") auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "): if not auth_header.startswith("Bearer "):
return False, None return False, None
token = auth_header[7:] # 移除"Bearer "前缀 token = auth_header[7:] # Remove "Bearer " prefix
return self.auth.verify_token(token) return self.auth.verify_token(token)
async def handle_post(self, request): async def handle_post(self, request):
"""处理 MCP Vision POST 请求""" """Handle MCP Vision POST request"""
response = None # 初始化response变量 response = None # Initialize response variable
try: try:
# 验证token # Verify token
is_valid, token_device_id = self._verify_auth_token(request) is_valid, token_device_id = self._verify_auth_token(request)
if not is_valid: if not is_valid:
response = web.Response( response = web.Response(
text=json.dumps( text=json.dumps(
self._create_error_response("无效的认证token或token已过期") self._create_error_response(
"Invalid authentication token or token expired")
), ),
content_type="application/json", content_type="application/json",
status=401, status=401,
) )
return response return response
# 获取请求头信息 # Get request header information
device_id = request.headers.get("Device-Id", "") device_id = request.headers.get("Device-Id", "")
client_id = request.headers.get("Client-Id", "") client_id = request.headers.get("Client-Id", "")
if device_id != token_device_id: if device_id != token_device_id:
raise ValueError("设备ID与token不匹配") raise ValueError("Device ID does not match token")
# 解析multipart/form-data请求 # Parse multipart/form-data request
reader = await request.multipart() reader = await request.multipart()
# 读取question字段 # Read question field
question_field = await reader.next() question_field = await reader.next()
if question_field is None: if question_field is None:
raise ValueError("缺少问题字段") raise ValueError("Missing question field")
question = await question_field.text() question = await question_field.text()
self.logger.bind(tag=TAG).debug(f"Question: {question}") self.logger.bind(tag=TAG).debug(f"Question: {question}")
# 读取图片文件 # Read image file
image_field = await reader.next() image_field = await reader.next()
if image_field is None: if image_field is None:
raise ValueError("缺少图片文件") raise ValueError("Missing image file")
# 读取图片数据 # Read image data
image_data = await image_field.read() image_data = await image_field.read()
if not image_data: if not image_data:
raise ValueError("图片数据为空") raise ValueError("Image data is empty")
# 检查文件大小 # Check file size
if len(image_data) > MAX_FILE_SIZE: if len(image_data) > MAX_FILE_SIZE:
raise ValueError( raise ValueError(
f"图片大小超过限制,最大允许{MAX_FILE_SIZE/1024/1024}MB" f"Image size exceeds limit, maximum allowed {MAX_FILE_SIZE/1024/1024}MB"
) )
# 检查文件格式 # Check file format
if not is_valid_image_file(image_data): if not is_valid_image_file(image_data):
raise ValueError( raise ValueError(
"不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)" "Unsupported file format, please upload a valid image file (supports JPEG, PNG, GIF, BMP, TIFF, WEBP formats)"
) )
# 将图片转换为base64编码 # Convert image to base64 encoding
image_base64 = base64.b64encode(image_data).decode("utf-8") image_base64 = base64.b64encode(image_data).decode("utf-8")
# 如果开启了智控台,则从智控台获取模型配置 # If smart control panel is enabled, get model configuration from smart control panel
current_config = copy.deepcopy(self.config) current_config = copy.deepcopy(self.config)
read_config_from_api = current_config.get("read_config_from_api", False) read_config_from_api = current_config.get(
"read_config_from_api", False)
if read_config_from_api: if read_config_from_api:
current_config = get_private_config_from_api( current_config = get_private_config_from_api(
current_config, current_config,
@ -104,7 +106,8 @@ class VisionHandler:
select_vllm_module = current_config["selected_module"].get("VLLM") select_vllm_module = current_config["selected_module"].get("VLLM")
if not select_vllm_module: if not select_vllm_module:
raise ValueError("您还未设置默认的视觉分析模块") raise ValueError(
"You have not set a default vision analysis module yet")
vllm_type = ( vllm_type = (
select_vllm_module select_vllm_module
@ -113,7 +116,8 @@ class VisionHandler:
) )
if not vllm_type: if not vllm_type:
raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}") raise ValueError(
f"Cannot find VLLM module corresponding provider {vllm_type}")
vllm = create_instance( vllm = create_instance(
vllm_type, current_config["VLLM"][select_vllm_module] vllm_type, current_config["VLLM"][select_vllm_module]
@ -132,15 +136,18 @@ class VisionHandler:
content_type="application/json", content_type="application/json",
) )
except ValueError as e: except ValueError as e:
self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}") self.logger.bind(tag=TAG).error(
f"MCP Vision POST request exception: {e}")
return_json = self._create_error_response(str(e)) return_json = self._create_error_response(str(e))
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json", content_type="application/json",
) )
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}") self.logger.bind(tag=TAG).error(
return_json = self._create_error_response("处理请求时发生错误") f"MCP Vision POST request exception: {e}")
return_json = self._create_error_response(
"Error occurred while processing request")
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json", content_type="application/json",
@ -151,20 +158,21 @@ class VisionHandler:
return response return response
async def handle_get(self, request): async def handle_get(self, request):
"""处理 MCP Vision GET 请求""" """Handle MCP Vision GET request"""
try: try:
vision_explain = get_vision_url(self.config) vision_explain = get_vision_url(self.config)
if vision_explain and len(vision_explain) > 0 and "null" != vision_explain: if vision_explain and len(vision_explain) > 0 and "null" != vision_explain:
message = ( message = (
f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}" f"MCP Vision interface running normally, vision explanation interface address is: {vision_explain}"
) )
else: else:
message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址" message = "MCP Vision interface not running normally, please open the .config.yaml file in the data directory, find [server.vision_explain], and set the address properly"
response = web.Response(text=message, content_type="text/plain") response = web.Response(text=message, content_type="text/plain")
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}") self.logger.bind(tag=TAG).error(
return_json = self._create_error_response("服务器内部错误") f"MCP Vision GET request exception: {e}")
return_json = self._create_error_response("Internal server error")
response = web.Response( response = web.Response(
text=json.dumps(return_json, separators=(",", ":")), text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json", content_type="application/json",
@ -174,7 +182,7 @@ class VisionHandler:
return response return response
def _add_cors_headers(self, response): def _add_cors_headers(self, response):
"""添加CORS头信息""" """Add CORS header information"""
response.headers["Access-Control-Allow-Headers"] = ( response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id" "client-id, content-type, device-id"
) )

View file

@ -1,41 +1,41 @@
from config.logger import setup_logging from config.logger import setup_logging
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class AuthenticationError(Exception): class AuthenticationError(Exception):
"""认证异常""" """Authentication exception"""
pass pass
class AuthMiddleware: class AuthMiddleware:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
self.auth_config = config["server"].get("auth", {}) self.auth_config = config["server"].get("auth", {})
# 构建token查找表
# Build token lookup table
self.tokens = { self.tokens = {
item["token"]: item["name"] item["token"]: item["name"]
for item in self.auth_config.get("tokens", []) for item in self.auth_config.get("tokens", [])
} }
# 设备白名单
# Device whitelist
self.allowed_devices = set( self.allowed_devices = set(
self.auth_config.get("allowed_devices", []) self.auth_config.get("allowed_devices", [])
) )
async def authenticate(self, headers): async def authenticate(self, headers):
"""验证连接请求""" """Verify connection request"""
# 检查是否启用认证 # Check if authentication is enabled
if not self.auth_config.get("enabled", False): if not self.auth_config.get("enabled", False):
return True return True
# 检查设备是否在白名单中 # Check if device is in whitelist
device_id = headers.get("device-id", "") device_id = headers.get("device-id", "")
if self.allowed_devices and device_id in self.allowed_devices: if self.allowed_devices and device_id in self.allowed_devices:
return True return True
# 验证Authorization header # Verify Authorization header
auth_header = headers.get("authorization", "") auth_header = headers.get("authorization", "")
if not auth_header.startswith("Bearer "): if not auth_header.startswith("Bearer "):
logger.bind(tag=TAG).error("Missing or invalid Authorization header") logger.bind(tag=TAG).error("Missing or invalid Authorization header")
@ -50,5 +50,5 @@ class AuthMiddleware:
return True return True
def get_token_name(self, token): def get_token_name(self, token):
"""获取token对应的设备名称""" """Get device name corresponding to token"""
return self.tokens.get(token) return self.tokens.get(token)

File diff suppressed because it is too large Load diff

View file

@ -5,10 +5,10 @@ TAG = __name__
async def handleAbortMessage(conn): async def handleAbortMessage(conn):
conn.logger.bind(tag=TAG).info("Abort message received") conn.logger.bind(tag=TAG).info("Abort message received")
# 设置成打断状态,会自动打断llm、tts任务 # Set to interrupt state, will automatically interrupt llm and tts tasks
conn.client_abort = True conn.client_abort = True
conn.clear_queues() conn.clear_queues()
# 打断客户端说话状态 # Interrupt client speaking state
await conn.websocket.send( await conn.websocket.send(
json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id}) json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id})
) )

View file

@ -21,24 +21,24 @@ WAKEUP_CONFIG = {
"words": ["你好", "你好啊", "嘿,你好", "嗨"], "words": ["你好", "你好啊", "嘿,你好", "嗨"],
} }
# 创建全局的唤醒词配置管理器 # Create global wakeup words configuration manager
wakeup_words_config = WakeupWordsConfig() wakeup_words_config = WakeupWordsConfig()
# 用于防止并发调用wakeupWordsResponse的锁 # Lock to prevent concurrent calls to wakeupWordsResponse
_wakeup_response_lock = asyncio.Lock() _wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json): async def handleHelloMessage(conn, msg_json):
"""处理hello消息""" """Handle hello message"""
audio_params = msg_json.get("audio_params") audio_params = msg_json.get("audio_params")
if audio_params: if audio_params:
format = audio_params.get("format") format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}") conn.logger.bind(tag=TAG).info(f"Client audio format: {format}")
conn.audio_format = format conn.audio_format = format
conn.welcome_msg["audio_params"] = audio_params conn.welcome_msg["audio_params"] = audio_params
features = msg_json.get("features") features = msg_json.get("features")
if features: if features:
conn.logger.bind(tag=TAG).info(f"客户端特性: {features}") conn.logger.bind(tag=TAG).info(f"Client features: {features}")
conn.features = features conn.features = features
# Handle both list and dictionary formats for features # Handle both list and dictionary formats for features
@ -49,11 +49,11 @@ async def handleHelloMessage(conn, msg_json):
has_mcp = features.get("mcp", False) has_mcp = features.get("mcp", False)
if has_mcp: if has_mcp:
conn.logger.bind(tag=TAG).info("客户端支持MCP") conn.logger.bind(tag=TAG).info("Client supports MCP")
conn.mcp_client = MCPClient() conn.mcp_client = MCPClient()
# 发送初始化 # Send initialization
asyncio.create_task(send_mcp_initialize_message(conn)) asyncio.create_task(send_mcp_initialize_message(conn))
# 发送mcp消息,获取tools列表 # Send mcp message to get tools list
asyncio.create_task(send_mcp_tools_list_request(conn)) asyncio.create_task(send_mcp_tools_list_request(conn))
await conn.websocket.send(json.dumps(conn.welcome_msg)) await conn.websocket.send(json.dumps(conn.welcome_msg))
@ -74,12 +74,12 @@ async def checkWakeupWords(conn, text):
conn.just_woken_up = True conn.just_woken_up = True
await send_stt_message(conn, text) await send_stt_message(conn, text)
# 获取当前音色 # Get current voice
voice = getattr(conn.tts, "voice", "default") voice = getattr(conn.tts, "voice", "default")
if not voice: if not voice:
voice = "default" voice = "default"
# 获取唤醒词回复配置 # Get wakeup words reply configuration
response = wakeup_words_config.get_wakeup_response(voice) response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"): if not response or not response.get("file_path"):
response = { response = {
@ -89,18 +89,19 @@ async def checkWakeupWords(conn, text):
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦", "text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
} }
# 播放唤醒词回复 # Play wakeup words reply
conn.client_abort = False conn.client_abort = False
opus_packets, _ = audio_to_data(response.get("file_path")) opus_packets, _ = audio_to_data(response.get("file_path"))
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}") conn.logger.bind(tag=TAG).info(
f"Playing wakeup words reply: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text")) await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None) await sendAudioMessage(conn, SentenceType.LAST, [], None)
# 补充对话 # Add to dialogue
conn.dialogue.put(Message(role="assistant", content=response.get("text"))) conn.dialogue.put(Message(role="assistant", content=response.get("text")))
# 检查是否需要更新唤醒词回复 # Check if wakeup words reply needs to be updated
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]: if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked(): if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn)) asyncio.create_task(wakeupWordsResponse(conn))
@ -112,38 +113,38 @@ async def wakeupWordsResponse(conn):
return return
try: try:
# 尝试获取锁,如果获取不到就返回 # Try to acquire lock, return if cannot acquire
if not await _wakeup_response_lock.acquire(): if not await _wakeup_response_lock.acquire():
return return
# 生成唤醒词回复 # Generate wakeup words reply
wakeup_word = random.choice(WAKEUP_CONFIG["words"]) wakeup_word = random.choice(WAKEUP_CONFIG["words"])
question = ( question = (
"此刻用户正在和你说```" "The user is currently saying ```"
+ wakeup_word + wakeup_word
+ "```。\n请你根据以上用户的内容进行20-30字回复。要符合系统设置的角色情感和态度,不要像机器人一样说话。\n" + "``` to you.\nPlease reply to the user's content above in 20-30 words. It should match the role's emotions and attitude set in the system, don't talk like a robot.\n"
+ "请勿对这条内容本身进行任何解释和回应,请勿返回表情符号,仅返回对用户的内容的回复。" + "Please do not explain or respond to this content itself, do not return emojis, only return a reply to the user's content."
) )
result = conn.llm.response_no_stream(conn.config["prompt"], question) result = conn.llm.response_no_stream(conn.config["prompt"], question)
if not result or len(result) == 0: if not result or len(result) == 0:
return return
# 生成TTS音频 # Generate TTS audio
tts_result = await asyncio.to_thread(conn.tts.to_tts, result) tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result: if not tts_result:
return return
# 获取当前音色 # Get current voice
voice = getattr(conn.tts, "voice", "default") voice = getattr(conn.tts, "voice", "default")
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000) wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
file_path = wakeup_words_config.generate_file_path(voice) file_path = wakeup_words_config.generate_file_path(voice)
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
f.write(wav_bytes) f.write(wav_bytes)
# 更新配置 # Update configuration
wakeup_words_config.update_wakeup_response(voice, file_path, result) wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally: finally:
# 确保在任何情况下都释放锁 # Ensure lock is released in any case
if _wakeup_response_lock.locked(): if _wakeup_response_lock.locked():
_wakeup_response_lock.release() _wakeup_response_lock.release()

View file

@ -6,40 +6,54 @@ from core.handle.helloHandle import checkWakeupWords
from core.utils.util import remove_punctuation_and_length from core.utils.util import remove_punctuation_and_length
from core.providers.tts.dto.dto import ContentType from core.providers.tts.dto.dto import ContentType
from core.utils.dialogue import Message from core.utils.dialogue import Message
from core.providers.tools.device_mcp import call_mcp_tool
from plugins_func.register import Action, ActionResponse from plugins_func.register import Action, ActionResponse
from loguru import logger from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
TAG = __name__ TAG = __name__
async def handle_user_intent(conn, text): async def handle_user_intent(conn, text):
# 检查是否有明确的退出命令 # Preprocess input text, handle possible JSON format
try:
if text.strip().startswith('{') and text.strip().endswith('}'):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
# Extract content for intent analysis
text = parsed_data["content"]
conn.current_speaker = parsed_data.get(
"speaker") # Preserve speaker information
except (json.JSONDecodeError, TypeError):
pass
# Check if there is an explicit exit command
filtered_text = remove_punctuation_and_length(text)[1] filtered_text = remove_punctuation_and_length(text)[1]
if await check_direct_exit(conn, filtered_text): if await check_direct_exit(conn, filtered_text):
return True return True
# 检查是否是唤醒词 # Check if it's a wake-up word
if await checkWakeupWords(conn, filtered_text): if await checkWakeupWords(conn, filtered_text):
return True return True
if conn.intent_type == "function_call": if conn.intent_type == "function_call":
# 使用支持function calling的聊天方法,不再进行意图分析 # Use chat method that supports function calling, no longer perform intent analysis
return False return False
# 使用LLM进行意图分析 # Use LLM for intent analysis
intent_result = await analyze_intent_with_llm(conn, text) intent_result = await analyze_intent_with_llm(conn, text)
if not intent_result: if not intent_result:
return False return False
# 处理各种意图 # Generate sentence_id at the beginning of the conversation
conn.sentence_id = str(uuid.uuid4().hex)
# Handle various intents
return await process_intent_result(conn, intent_result, text) return await process_intent_result(conn, intent_result, text)
async def check_direct_exit(conn, text): async def check_direct_exit(conn, text):
"""检查是否有明确的退出命令""" """Check if there is an explicit exit command"""
_, text = remove_punctuation_and_length(text) _, text = remove_punctuation_and_length(text)
cmd_exit = conn.cmd_exit cmd_exit = conn.cmd_exit
for cmd in cmd_exit: for cmd in cmd_exit:
if text == cmd: if text == cmd:
conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}") conn.logger.bind(tag=TAG).info(
f"Recognized explicit exit command: {text}")
await send_stt_message(conn, text) await send_stt_message(conn, text)
await conn.close() await conn.close()
return True return True
@ -47,49 +61,45 @@ async def check_direct_exit(conn, text):
async def analyze_intent_with_llm(conn, text): async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图""" """Use LLM to analyze user intent"""
if not hasattr(conn, "intent") or not conn.intent: if not hasattr(conn, "intent") or not conn.intent:
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化") conn.logger.bind(tag=TAG).warning(
"Intent recognition service not initialized")
return None return None
# 对话历史记录 # Conversation history records
dialogue = conn.dialogue dialogue = conn.dialogue
try: try:
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text) intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
return intent_result return intent_result
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}") conn.logger.bind(tag=TAG).error(f"Intent recognition failed: {str(e)}")
return None return None
async def process_intent_result(conn, intent_result, original_text): async def process_intent_result(conn, intent_result, original_text):
"""处理意图识别结果""" """Process intent recognition results"""
try: try:
# 尝试将结果解析为JSON # Try to parse the result as JSON
intent_data = json.loads(intent_result) intent_data = json.loads(intent_result)
# 检查是否有function_call # Check if there is a function_call
if "function_call" in intent_data: if "function_call" in intent_data:
# 直接从意图识别获取了function_call # Directly obtained function_call from intent recognition
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}" f"Detected function_call format intent result: {intent_data['function_call']['name']}"
) )
function_name = intent_data["function_call"]["name"] function_name = intent_data["function_call"]["name"]
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 = {} function_args = {}
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"]
if function_args is None: if function_args is None:
function_args = {} function_args = {}
# 确保参数是字符串格式的JSON # Ensure parameters are in string format JSON
if isinstance(function_args, dict): if isinstance(function_args, dict):
function_args = json.dumps(function_args) function_args = json.dumps(function_args)
@ -102,11 +112,11 @@ async def process_intent_result(conn, intent_result, original_text):
await send_stt_message(conn, original_text) await send_stt_message(conn, original_text)
conn.client_abort = False conn.client_abort = False
# 使用executor执行函数调用和结果处理 # Use executor to execute function calls and result processing
def process_function_call(): def process_function_call():
conn.dialogue.put(Message(role="user", content=original_text)) conn.dialogue.put(Message(role="user", content=original_text))
# 使用统一工具处理器处理所有工具调用 # Use unified tool handler to process all tool calls
try: try:
result = asyncio.run_coroutine_threadsafe( result = asyncio.run_coroutine_threadsafe(
conn.func_handler.handle_llm_function_call( conn.func_handler.handle_llm_function_call(
@ -115,20 +125,21 @@ async def process_intent_result(conn, intent_result, original_text):
conn.loop, conn.loop,
).result() ).result()
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"工具调用失败: {e}") conn.logger.bind(tag=TAG).error(f"Tool call failed: {e}")
result = ActionResponse( result = ActionResponse(
action=Action.ERROR, result=str(e), response=str(e) action=Action.ERROR, result=str(e), response=str(e)
) )
if result: if result:
if result.action == Action.RESPONSE: # 直接回复前端 if result.action == Action.RESPONSE: # Directly reply to frontend
text = result.response text = result.response
if text is not None: if text is not None:
speak_txt(conn, text) speak_txt(conn, text)
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复 elif result.action == Action.REQLLM: # Call function then request LLM to generate reply
text = result.result text = result.result
conn.dialogue.put(Message(role="tool", content=text)) conn.dialogue.put(Message(role="tool", content=text))
llm_result = conn.intent.replyResult(text, original_text) llm_result = conn.intent.replyResult(
text, original_text)
if llm_result is None: if llm_result is None:
llm_result = text llm_result = text
speak_txt(conn, llm_result) speak_txt(conn, llm_result)
@ -141,22 +152,36 @@ async def process_intent_result(conn, intent_result, original_text):
speak_txt(conn, text) speak_txt(conn, text)
elif function_name != "play_music": elif function_name != "play_music":
# For backward compatibility with original code # For backward compatibility with original code
# 获取当前最新的文本索引 # Get the current latest text index
text = result.response text = result.response
if text is None: if text is None:
text = result.result text = result.result
if text is not None: if text is not None:
speak_txt(conn, text) speak_txt(conn, text)
# 将函数执行放在线程池中 # Put function execution in thread pool
conn.executor.submit(process_function_call) conn.executor.submit(process_function_call)
return True return True
return False return False
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}") conn.logger.bind(tag=TAG).error(f"Error processing intent result: {e}")
return False return False
def speak_txt(conn, text): def speak_txt(conn, text):
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.FIRST,
content_type=ContentType.ACTION,
)
)
conn.tts.tts_one_sentence(conn, ContentType.TEXT, content_detail=text) conn.tts.tts_one_sentence(conn, ContentType.TEXT, content_detail=text)
conn.tts.tts_text_queue.put(
TTSMessageDTO(
sentence_id=conn.sentence_id,
sentence_type=SentenceType.LAST,
content_type=ContentType.ACTION,
)
)
conn.dialogue.put(Message(role="assistant", content=text)) conn.dialogue.put(Message(role="assistant", content=text))

View file

@ -4,6 +4,7 @@ from core.utils.output_counter import check_device_output_limit
from core.handle.abortHandle import handleAbortMessage from core.handle.abortHandle import handleAbortMessage
import time import time
import asyncio import asyncio
import json
from core.handle.sendAudioHandle import SentenceType from core.handle.sendAudioHandle import SentenceType
from core.utils.util import audio_to_data from core.utils.util import audio_to_data
@ -11,38 +12,65 @@ TAG = __name__
async def handleAudioMessage(conn, audio): async def handleAudioMessage(conn, audio):
# 当前片段是否有人说话 # Whether the current segment has someone speaking
have_voice = conn.vad.is_vad(conn, audio) have_voice = conn.vad.is_vad(conn, audio)
# 如果设备刚刚被唤醒,短暂忽略VAD检测 # If the device was just woken up, briefly ignore VAD detection
if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up: if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
have_voice = False have_voice = False
# 设置一个短暂延迟后恢复VAD检测 # Set a brief delay before resuming VAD detection
conn.asr_audio.clear() conn.asr_audio.clear()
if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done(): if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) conn.vad_resume_task = asyncio.create_task(
resume_vad_detection(conn))
return return
if have_voice: if have_voice:
if conn.client_is_speaking: if conn.client_is_speaking:
await handleAbortMessage(conn) await handleAbortMessage(conn)
# 设备长时间空闲检测,用于say goodbye # Device long-term idle detection, used for say goodbye
await no_voice_close_connect(conn, have_voice) await no_voice_close_connect(conn, have_voice)
# 接收音频 # Receive audio
await conn.asr.receive_audio(conn, audio, have_voice) await conn.asr.receive_audio(conn, audio, have_voice)
async def resume_vad_detection(conn): async def resume_vad_detection(conn):
# 等待2秒后恢复VAD检测 # Wait 2 seconds before resuming VAD detection
await asyncio.sleep(1) await asyncio.sleep(1)
conn.just_woken_up = False conn.just_woken_up = False
async def startToChat(conn, text): async def startToChat(conn, text):
# Check if input is in JSON format (containing speaker information)
speaker_name = None
actual_text = text
try:
# Try to parse JSON format input
if text.strip().startswith('{') and text.strip().endswith('}'):
data = json.loads(text)
if 'speaker' in data and 'content' in data:
speaker_name = data['speaker']
actual_text = data['content']
conn.logger.bind(tag=TAG).info(
f"Parsed speaker information: {speaker_name}")
# Use JSON format text directly, do not parse
actual_text = text
except (json.JSONDecodeError, KeyError):
# If parsing fails, continue using original text
pass
# Save speaker information to connection object
if speaker_name:
conn.current_speaker = speaker_name
else:
conn.current_speaker = None
if conn.need_bind: if conn.need_bind:
await check_bind_device(conn) await check_bind_device(conn)
return return
# 如果当日的输出字数大于限定的字数 # If the daily output word count exceeds the limit
if conn.max_output_size > 0: if conn.max_output_size > 0:
if check_device_output_limit( if check_device_output_limit(
conn.headers.get("device-id"), conn.max_output_size conn.headers.get("device-id"), conn.max_output_size
@ -52,23 +80,23 @@ async def startToChat(conn, text):
if conn.client_is_speaking: if conn.client_is_speaking:
await handleAbortMessage(conn) await handleAbortMessage(conn)
# 首先进行意图分析 # First perform intent analysis, using actual text content
intent_handled = await handle_user_intent(conn, text) intent_handled = await handle_user_intent(conn, actual_text)
if intent_handled: if intent_handled:
# 如果意图已被处理,不再进行聊天 # If intent has been handled, no longer proceed with chat
return return
# 意图未被处理,继续常规聊天流程 # Intent not handled, continue with regular chat flow, using actual text content
await send_stt_message(conn, text) await send_stt_message(conn, actual_text)
conn.executor.submit(conn.chat, text) conn.executor.submit(conn.chat, actual_text)
async def no_voice_close_connect(conn, have_voice): async def no_voice_close_connect(conn, have_voice):
if have_voice: if have_voice:
conn.last_activity_time = time.time() * 1000 conn.last_activity_time = time.time() * 1000
return return
# 只有在已经初始化过时间戳的情况下才进行超时检查 # Only perform timeout check when timestamp has been initialized
if conn.last_activity_time > 0.0: if conn.last_activity_time > 0.0:
no_voice_time = time.time() * 1000 - conn.last_activity_time no_voice_time = time.time() * 1000 - conn.last_activity_time
close_connection_no_voice_time = int( close_connection_no_voice_time = int(
@ -82,17 +110,18 @@ async def no_voice_close_connect(conn, have_voice):
conn.client_abort = False conn.client_abort = False
end_prompt = conn.config.get("end_prompt", {}) end_prompt = conn.config.get("end_prompt", {})
if end_prompt and end_prompt.get("enable", True) is False: if end_prompt and end_prompt.get("enable", True) is False:
conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语") conn.logger.bind(tag=TAG).info(
"End conversation, no need to send ending prompt")
await conn.close() await conn.close()
return return
prompt = end_prompt.get("prompt") prompt = end_prompt.get("prompt")
if not prompt: if not prompt:
prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!" prompt = "Please use ```time flies so fast``` as the opening, and use emotionally rich, reluctant words to end this conversation!"
await startToChat(conn, prompt) await startToChat(conn, prompt)
async def max_out_size(conn): async def max_out_size(conn):
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!" text = "Sorry, I have some things to deal with now. Let's chat again at this time tomorrow. It's a promise! See you tomorrow, goodbye!"
await send_stt_message(conn, text) await send_stt_message(conn, text)
file_path = "config/assets/max_output_size.wav" file_path = "config/assets/max_output_size.wav"
opus_packets, _ = audio_to_data(file_path) opus_packets, _ = audio_to_data(file_path)
@ -102,34 +131,37 @@ async def max_out_size(conn):
async def check_bind_device(conn): async def check_bind_device(conn):
if conn.bind_code: if conn.bind_code:
# 确保bind_code是6位数字 # Ensure bind_code is a 6-digit number
if len(conn.bind_code) != 6: if len(conn.bind_code) != 6:
conn.logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}") conn.logger.bind(tag=TAG).error(
text = "绑定码格式错误,请检查配置。" f"Invalid binding code format: {conn.bind_code}")
text = "Binding code format error, please check configuration."
await send_stt_message(conn, text) await send_stt_message(conn, text)
return return
text = f"请登录控制面板,输入{conn.bind_code},绑定设备。" text = f"Please log into the control panel and enter {conn.bind_code} to bind the device."
await send_stt_message(conn, text) await send_stt_message(conn, text)
# 播放提示音 # Play notification sound
music_path = "config/assets/bind_code.wav" music_path = "config/assets/bind_code.wav"
opus_packets, _ = audio_to_data(music_path) opus_packets, _ = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text)) conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# 逐个播放数字 # Play digits one by one
for i in range(6): # 确保只播放6位数字 for i in range(6): # Ensure only 6 digits are played
try: try:
digit = conn.bind_code[i] digit = conn.bind_code[i]
num_path = f"config/assets/bind_code/{digit}.wav" num_path = f"config/assets/bind_code/{digit}.wav"
num_packets, _ = audio_to_data(num_path) num_packets, _ = audio_to_data(num_path)
conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None)) conn.tts.tts_audio_queue.put(
(SentenceType.MIDDLE, num_packets, None))
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}") conn.logger.bind(tag=TAG).error(
f"Failed to play digit audio: {e}")
continue continue
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None)) conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
else: else:
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。" text = f"Version information for this device was not found. Please configure the OTA address correctly and then recompile the firmware."
await send_stt_message(conn, text) await send_stt_message(conn, text)
music_path = "config/assets/bind_not_found.wav" music_path = "config/assets/bind_not_found.wav"
opus_packets, _ = audio_to_data(music_path) opus_packets, _ = audio_to_data(music_path)

View file

@ -1,12 +1,12 @@
""" """
TTS上报功能已集成到ConnectionHandler类中。 TTS reporting functionality has been integrated into the ConnectionHandler class.
上报功能包括: Reporting functionality includes:
1. 每个连接对象拥有自己的上报队列和处理线程 1. Each connection object has its own reporting queue and processing thread
2. 上报线程的生命周期与连接对象绑定 2. The reporting thread's lifecycle is bound to the connection object
3. 使用ConnectionHandler.enqueue_tts_report方法进行上报 3. Use ConnectionHandler.enqueue_tts_report method for reporting
具体实现请参考core/connection.py中的相关代码。 For specific implementation, please refer to the relevant code in core/connection.py.
""" """
import time import time
@ -19,21 +19,21 @@ TAG = __name__
def report(conn, type, text, opus_data, report_time): def report(conn, type, text, opus_data, report_time):
"""执行聊天记录上报操作 """Execute chat history reporting operation
Args: Args:
conn: 连接对象 conn: Connection object
type: 上报类型,1为用户,2为智能体 type: Report type, 1 for user, 2 for agent
text: 合成文本 text: Synthesized text
opus_data: opus音频数据 opus_data: Opus audio data
report_time: 上报时间 report_time: Report time
""" """
try: try:
if opus_data: if opus_data:
audio_data = opus_to_wav(conn, opus_data) audio_data = opus_to_wav(conn, opus_data)
else: else:
audio_data = None audio_data = None
# 执行上报 # Execute reporting
manage_report( manage_report(
mac_address=conn.device_id, mac_address=conn.device_id,
session_id=conn.session_id, session_id=conn.session_id,
@ -43,20 +43,20 @@ def report(conn, type, text, opus_data, report_time):
report_time=report_time, report_time=report_time,
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}") conn.logger.bind(tag=TAG).error(f"Chat history reporting failed: {e}")
def opus_to_wav(conn, opus_data): def opus_to_wav(conn, opus_data):
"""将Opus数据转换为WAV格式的字节流 """Convert Opus data to WAV format byte stream
Args: Args:
output_dir: 输出目录(保留参数以保持接口兼容) output_dir: Output directory (parameter retained for interface compatibility)
opus_data: opus音频数据 opus_data: Opus audio data
Returns: Returns:
bytes: WAV格式的音频数据 bytes: WAV format audio data
""" """
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 decoder = opuslib_next.Decoder(16000, 1) # 16kHz, mono
pcm_data = [] pcm_data = []
for opus_packet in opus_data: for opus_packet in opus_data:
@ -64,16 +64,16 @@ def opus_to_wav(conn, opus_data):
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
pcm_data.append(pcm_frame) pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e: except opuslib_next.OpusError as e:
conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True) conn.logger.bind(tag=TAG).error(f"Opus decoding error: {e}", exc_info=True)
if not pcm_data: if not pcm_data:
raise ValueError("没有有效的PCM数据") raise ValueError("No valid PCM data")
# 创建WAV文件头 # Create WAV file header
pcm_data_bytes = b"".join(pcm_data) pcm_data_bytes = b"".join(pcm_data)
num_samples = len(pcm_data_bytes) // 2 # 16-bit samples num_samples = len(pcm_data_bytes) // 2 # 16-bit samples
# WAV文件头 # WAV file header
wav_header = bytearray() wav_header = bytearray()
wav_header.extend(b"RIFF") # ChunkID wav_header.extend(b"RIFF") # ChunkID
wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize
@ -89,7 +89,7 @@ def opus_to_wav(conn, opus_data):
wav_header.extend(b"data") # Subchunk2ID wav_header.extend(b"data") # Subchunk2ID
wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size
# 返回完整的WAV数据 # Return complete WAV data
return bytes(wav_header) + pcm_data_bytes return bytes(wav_header) + pcm_data_bytes
@ -98,27 +98,27 @@ def enqueue_tts_report(conn, text, opus_data):
return return
if conn.chat_history_conf == 0: if conn.chat_history_conf == 0:
return return
"""将TTS数据加入上报队列 """Add TTS data to reporting queue
Args: Args:
conn: 连接对象 conn: Connection object
text: 合成文本 text: Synthesized text
opus_data: opus音频数据 opus_data: Opus audio data
""" """
try: try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径 # Use connection object's queue, pass text and binary data instead of file path
if conn.chat_history_conf == 2: if conn.chat_history_conf == 2:
conn.report_queue.put((2, text, opus_data, int(time.time()))) conn.report_queue.put((2, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " f"TTS data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
) )
else: else:
conn.report_queue.put((2, text, None, int(time.time()))) conn.report_queue.put((2, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频" f"TTS data added to reporting queue: {conn.device_id}, no audio reporting"
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}") conn.logger.bind(tag=TAG).error(f"Failed to add TTS to reporting queue: {text}, {e}")
def enqueue_asr_report(conn, text, opus_data): def enqueue_asr_report(conn, text, opus_data):
@ -126,24 +126,24 @@ def enqueue_asr_report(conn, text, opus_data):
return return
if conn.chat_history_conf == 0: if conn.chat_history_conf == 0:
return return
"""将ASR数据加入上报队列 """Add ASR data to reporting queue
Args: Args:
conn: 连接对象 conn: Connection object
text: 合成文本 text: Synthesized text
opus_data: opus音频数据 opus_data: Opus audio data
""" """
try: try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径 # Use connection object's queue, pass text and binary data instead of file path
if conn.chat_history_conf == 2: if conn.chat_history_conf == 2:
conn.report_queue.put((1, text, opus_data, int(time.time()))) conn.report_queue.put((1, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} " f"ASR data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
) )
else: else:
conn.report_queue.put((1, text, None, int(time.time()))) conn.report_queue.put((1, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频" f"ASR data added to reporting queue: {conn.device_id}, no audio reporting"
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}") conn.logger.bind(tag=TAG).debug(f"Failed to add ASR to reporting queue: {text}, {e}")

View file

@ -2,55 +2,19 @@ import json
import asyncio import asyncio
import time import time
from core.providers.tts.dto.dto import SentenceType from core.providers.tts.dto.dto import SentenceType
from core.utils.util import get_string_no_punctuation_or_emoji, analyze_emotion from core.utils import textUtils
from loguru import logger
TAG = __name__ TAG = __name__
emoji_map = {
"neutral": "😶",
"happy": "🙂",
"laughing": "😆",
"funny": "😂",
"sad": "😔",
"angry": "😠",
"crying": "😭",
"loving": "😍",
"embarrassed": "😳",
"surprised": "😲",
"shocked": "😱",
"thinking": "🤔",
"winking": "😉",
"cool": "😎",
"relaxed": "😌",
"delicious": "🤤",
"kissy": "😘",
"confident": "😏",
"sleepy": "😴",
"silly": "😜",
"confused": "🙄",
}
async def sendAudioMessage(conn, sentenceType, audios, text): async def sendAudioMessage(conn, sentenceType, audios, text):
# 发送句子开始消息 # Send sentence start message
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}") conn.logger.bind(tag=TAG).info(
if text is not None: f"Send audio message: {sentenceType}, {text}")
emotion = analyze_emotion(text)
emoji = emoji_map.get(emotion, "🙂") # 默认使用笑脸
await conn.websocket.send(
json.dumps(
{
"type": "llm",
"text": emoji,
"emotion": emotion,
"session_id": conn.session_id,
}
)
)
pre_buffer = False pre_buffer = False
if conn.tts.tts_audio_first_sentence and text is not None: if conn.tts.tts_audio_first_sentence:
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}") conn.logger.bind(tag=TAG).info(f"Send first audio segment: {text}")
conn.tts.tts_audio_first_sentence = False conn.tts.tts_audio_first_sentence = False
pre_buffer = True pre_buffer = True
@ -58,9 +22,7 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await sendAudio(conn, audios, pre_buffer) await sendAudio(conn, audios, pre_buffer)
await send_tts_message(conn, "sentence_end", text) # Send end message (if it's the last text)
# 发送结束消息(如果是最后一个文本)
if conn.llm_finish_task and sentenceType == SentenceType.LAST: if conn.llm_finish_task and sentenceType == SentenceType.LAST:
await send_tts_message(conn, "stop", None) await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False conn.client_is_speaking = False
@ -68,17 +30,17 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await conn.close() await conn.close()
# 播放音频 # Play audio
async def sendAudio(conn, audios, pre_buffer=True): async def sendAudio(conn, audios, pre_buffer=True):
if audios is None or len(audios) == 0: if audios is None or len(audios) == 0:
return return
# 流控参数优化 # Flow control parameter optimization
frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码 # Frame duration (milliseconds), matching Opus encoding
frame_duration = 60
start_time = time.perf_counter() start_time = time.perf_counter()
play_position = 0 play_position = 0
last_reset_time = time.perf_counter() # 记录最后的重置时间
# 仅当第一句话时执行预缓冲 # Execute pre-buffering only for the first sentence
if pre_buffer: if pre_buffer:
pre_buffer_frames = min(3, len(audios)) pre_buffer_frames = min(3, len(audios))
for i in range(pre_buffer_frames): for i in range(pre_buffer_frames):
@ -87,15 +49,15 @@ async def sendAudio(conn, audios, pre_buffer=True):
else: else:
remaining_audios = audios remaining_audios = audios
# 播放剩余音频帧 # Play remaining audio frames
for opus_packet in remaining_audios: for opus_packet in remaining_audios:
if conn.client_abort: if conn.client_abort:
break break
# 重置没有声音的状态 # Reset no-voice state
conn.last_activity_time = time.time() * 1000 conn.last_activity_time = time.time() * 1000
# 计算预期发送时间 # Calculate expected send time
expected_time = start_time + (play_position / 1000) expected_time = start_time + (play_position / 1000)
current_time = time.perf_counter() current_time = time.perf_counter()
delay = expected_time - current_time delay = expected_time - current_time
@ -108,14 +70,14 @@ async def sendAudio(conn, audios, pre_buffer=True):
async def send_tts_message(conn, state, text=None): async def send_tts_message(conn, state, text=None):
"""发送 TTS 状态消息""" """Send TTS status message"""
message = {"type": "tts", "state": state, "session_id": conn.session_id} message = {"type": "tts", "state": state, "session_id": conn.session_id}
if text is not None: if text is not None:
message["text"] = text message["text"] = textUtils.check_emoji(text)
# TTS播放结束 # TTS playback ended
if state == "stop": if state == "stop":
# 播放提示音 # Play notification sound
tts_notify = conn.config.get("enable_stop_tts_notify", False) tts_notify = conn.config.get("enable_stop_tts_notify", False)
if tts_notify: if tts_notify:
stop_tts_notify_voice = conn.config.get( stop_tts_notify_voice = conn.config.get(
@ -123,10 +85,10 @@ async def send_tts_message(conn, state, text=None):
) )
audios, _ = conn.tts.audio_to_opus_data(stop_tts_notify_voice) audios, _ = conn.tts.audio_to_opus_data(stop_tts_notify_voice)
await sendAudio(conn, audios) await sendAudio(conn, audios)
# 清除服务端讲话状态 # Clear server speaking status
conn.clearSpeakStatus() conn.clearSpeakStatus()
# 发送消息到客户端 # Send message to client
await conn.websocket.send(json.dumps(message)) await conn.websocket.send(json.dumps(message))
@ -136,10 +98,27 @@ async def send_stt_message(conn, text):
await send_tts_message(conn, "start") await send_tts_message(conn, "start")
return return
"""发送 STT 状态消息""" """Send STT status message"""
stt_text = get_string_no_punctuation_or_emoji(text)
# Parse JSON format, extract actual user speech content
display_text = text
try:
# Try to parse JSON format
if text.strip().startswith('{') and text.strip().endswith('}'):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
# If it's JSON format containing speaker information, only display the content part
display_text = parsed_data["content"]
# Save speaker information to conn object
if "speaker" in parsed_data:
conn.current_speaker = parsed_data["speaker"]
except (json.JSONDecodeError, TypeError):
# If it's not JSON format, use original text directly
display_text = text
stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
await conn.websocket.send( await conn.websocket.send(
json.dumps({"type": "stt", "text": stt_text, "session_id": conn.session_id}) json.dumps({"type": "stt", "text": stt_text,
"session_id": conn.session_id})
) )
conn.client_is_speaking = True conn.client_is_speaking = True
await send_tts_message(conn, "start") await send_tts_message(conn, "start")

View file

@ -1,4 +1,5 @@
import json import json
import time
from core.handle.abortHandle import handleAbortMessage from core.handle.abortHandle import handleAbortMessage
from core.handle.helloHandle import handleHelloMessage from core.handle.helloHandle import handleHelloMessage
from core.providers.tools.device_mcp import handle_mcp_message from core.providers.tools.device_mcp import handle_mcp_message
@ -13,25 +14,28 @@ TAG = __name__
async def handleTextMessage(conn, message): async def handleTextMessage(conn, message):
"""处理文本消息""" """Handle text messages"""
try: try:
msg_json = json.loads(message) msg_json = json.loads(message)
if isinstance(msg_json, int): if isinstance(msg_json, int):
conn.logger.bind(tag=TAG).info(f"收到文本消息:{message}") conn.logger.bind(tag=TAG).info(f"Received text message: {message}")
await conn.websocket.send(message) await conn.websocket.send(message)
return return
if msg_json["type"] == "hello": if msg_json["type"] == "hello":
conn.logger.bind(tag=TAG).info(f"收到hello消息:{message}") conn.logger.bind(tag=TAG).info(
f"Received hello message: {message}")
await handleHelloMessage(conn, msg_json) await handleHelloMessage(conn, msg_json)
elif msg_json["type"] == "abort": elif msg_json["type"] == "abort":
conn.logger.bind(tag=TAG).info(f"收到abort消息:{message}") conn.logger.bind(tag=TAG).info(
f"Received abort message: {message}")
await handleAbortMessage(conn) await handleAbortMessage(conn)
elif msg_json["type"] == "listen": elif msg_json["type"] == "listen":
conn.logger.bind(tag=TAG).info(f"收到listen消息:{message}") conn.logger.bind(tag=TAG).info(
f"Received listen message: {message}")
if "mode" in msg_json: if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"] conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug( conn.logger.bind(tag=TAG).debug(
f"客户端拾音模式:{conn.client_listen_mode}" f"Client audio capture mode: {conn.client_listen_mode}"
) )
if msg_json["state"] == "start": if msg_json["state"] == "start":
conn.client_have_voice = True conn.client_have_voice = True
@ -45,77 +49,82 @@ async def handleTextMessage(conn, message):
conn.client_have_voice = False conn.client_have_voice = False
conn.asr_audio.clear() conn.asr_audio.clear()
if "text" in msg_json: if "text" in msg_json:
original_text = msg_json["text"] # 保留原始文本 conn.last_activity_time = time.time() * 1000
original_text = msg_json["text"] # Preserve original text
filtered_len, filtered_text = remove_punctuation_and_length( filtered_len, filtered_text = remove_punctuation_and_length(
original_text original_text
) )
# 识别是否是唤醒词 # Identify if it's a wake-up word
is_wakeup_words = filtered_text in conn.config.get("wakeup_words") is_wakeup_words = filtered_text in conn.config.get(
# 是否开启唤醒词回复 "wakeup_words")
# Whether wake-up word reply is enabled
enable_greeting = conn.config.get("enable_greeting", True) enable_greeting = conn.config.get("enable_greeting", True)
if is_wakeup_words and not enable_greeting: if is_wakeup_words and not enable_greeting:
# 如果是唤醒词,且关闭了唤醒词回复,就不用回答 # If it's a wake-up word and wake-up word reply is disabled, no need to respond
await send_stt_message(conn, original_text) await send_stt_message(conn, original_text)
await send_tts_message(conn, "stop", None) await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False conn.client_is_speaking = False
elif is_wakeup_words: elif is_wakeup_words:
conn.just_woken_up = True conn.just_woken_up = True
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据) # Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, "嘿,你好呀", []) enqueue_asr_report(conn, "Hey, hello there", [])
await startToChat(conn, "嘿,你好呀") await startToChat(conn, "Hey, hello there")
else: else:
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据) # Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, original_text, []) enqueue_asr_report(conn, original_text, [])
# 否则需要LLM对文字内容进行答复 # Otherwise, need LLM to respond to text content
await startToChat(conn, original_text) await startToChat(conn, original_text)
elif msg_json["type"] == "iot": elif msg_json["type"] == "iot":
conn.logger.bind(tag=TAG).info(f"收到iot消息:{message}") conn.logger.bind(tag=TAG).info(f"Received iot message: {message}")
if "descriptors" in msg_json: if "descriptors" in msg_json:
asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"])) asyncio.create_task(handleIotDescriptors(
conn, msg_json["descriptors"]))
if "states" in msg_json: if "states" in msg_json:
asyncio.create_task(handleIotStatus(conn, msg_json["states"])) asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
elif msg_json["type"] == "mcp": elif msg_json["type"] == "mcp":
conn.logger.bind(tag=TAG).info(f"收到mcp消息:{message[:100]}") conn.logger.bind(tag=TAG).info(
f"Received mcp message: {message[:100]}")
if "payload" in msg_json: if "payload" in msg_json:
asyncio.create_task( asyncio.create_task(
handle_mcp_message(conn, conn.mcp_client, msg_json["payload"]) handle_mcp_message(conn, conn.mcp_client,
msg_json["payload"])
) )
elif msg_json["type"] == "server": elif msg_json["type"] == "server":
# 记录日志时过滤敏感信息 # Filter sensitive information when logging
conn.logger.bind(tag=TAG).info( conn.logger.bind(tag=TAG).info(
f"收到服务器消息:{filter_sensitive_info(msg_json)}" f"Received server message: {filter_sensitive_info(msg_json)}"
) )
# 如果配置是从API读取的,则需要验证secret # If configuration is read from API, need to verify secret
if not conn.read_config_from_api: if not conn.read_config_from_api:
return return
# 获取post请求的secret # Get secret from post request
post_secret = msg_json.get("content", {}).get("secret", "") post_secret = msg_json.get("content", {}).get("secret", "")
secret = conn.config["manager-api"].get("secret", "") secret = conn.config["manager-api"].get("secret", "")
# 如果secret不匹配,则返回 # If secret doesn't match, return
if post_secret != secret: if post_secret != secret:
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": "服务器密钥验证失败", "message": "Server secret verification failed",
} }
) )
) )
return return
# 动态更新配置 # Dynamically update configuration
if msg_json["action"] == "update_config": if msg_json["action"] == "update_config":
try: try:
# 更新WebSocketServer的配置 # Update WebSocketServer configuration
if not conn.server: if not conn.server:
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": "无法获取服务器实例", "message": "Cannot get server instance",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
@ -128,40 +137,42 @@ async def handleTextMessage(conn, message):
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": "更新服务器配置失败", "message": "Failed to update server configuration",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
) )
return return
# 发送成功响应 # Send success response
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "success", "status": "success",
"message": "配置更新成功", "message": "Configuration updated successfully",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
) )
except Exception as e: except Exception as e:
conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}") conn.logger.bind(tag=TAG).error(
f"Failed to update configuration: {str(e)}")
await conn.websocket.send( await conn.websocket.send(
json.dumps( json.dumps(
{ {
"type": "server", "type": "server",
"status": "error", "status": "error",
"message": f"更新配置失败: {str(e)}", "message": f"Failed to update configuration: {str(e)}",
"content": {"action": "update_config"}, "content": {"action": "update_config"},
} }
) )
) )
# 重启服务器 # Restart server
elif msg_json["action"] == "restart": elif msg_json["action"] == "restart":
await conn.handle_restart(msg_json) await conn.handle_restart(msg_json)
else: else:
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}") conn.logger.bind(tag=TAG).error(
f"Received unknown type message: {message}")
except json.JSONDecodeError: except json.JSONDecodeError:
await conn.websocket.send(message) await conn.websocket.send(message)

View file

@ -15,19 +15,18 @@ class SimpleHttpServer:
self.vision_handler = VisionHandler(config) self.vision_handler = VisionHandler(config)
def _get_websocket_url(self, local_ip: str, port: int) -> str: def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址 """Get websocket address
Args: Args:
local_ip: 本地IP地址 local_ip: Local IP address
port: 端口号 port: Port number
Returns: Returns:
str: websocket地址 str: websocket address
""" """
server_config = self.config["server"] server_config = self.config["server"]
websocket_config = server_config.get("websocket") websocket_config = server_config.get("websocket")
if websocket_config and "you" not in websocket_config:
if websocket_config and "你" not in websocket_config:
return websocket_config return websocket_config
else: else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/" return f"ws://{local_ip}:{port}/xiaozhi/v1/"
@ -39,43 +38,52 @@ class SimpleHttpServer:
if port: if port:
try: try:
self.logger.bind(tag=TAG).info(f"Starting HTTP server on {host}:{port}") self.logger.bind(tag=TAG).info(
f"Starting HTTP server on {host}:{port}")
app = web.Application() app = web.Application()
read_config_from_api = server_config.get("read_config_from_api", False) read_config_from_api = server_config.get(
self.logger.bind(tag=TAG).info(f"read_config_from_api: {read_config_from_api}") "read_config_from_api", False)
self.logger.bind(tag=TAG).info(
f"read_config_from_api: {read_config_from_api}")
if not read_config_from_api: if not read_config_from_api:
# 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口 # If smart control panel is not enabled, just running single module, need to add simple OTA interface for delivering websocket interface
self.logger.bind(tag=TAG).info("Adding OTA routes") self.logger.bind(tag=TAG).info("Adding OTA routes")
app.add_routes( app.add_routes([
[ web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
web.get("/xiaozhi/ota/", self.ota_handler.handle_get), web.post("/xiaozhi/ota/",
web.post("/xiaozhi/ota/", self.ota_handler.handle_post), self.ota_handler.handle_post),
web.options("/xiaozhi/ota/", self.ota_handler.handle_post), web.options("/xiaozhi/ota/",
] self.ota_handler.handle_post),
) ])
# 添加路由
self.logger.bind(tag=TAG).info("Adding vision routes")
app.add_routes(
[
web.get("/mcp/vision/explain", self.vision_handler.handle_get),
web.post("/mcp/vision/explain", self.vision_handler.handle_post),
web.options("/mcp/vision/explain", self.vision_handler.handle_post),
]
)
# 运行服务 # Add routes
self.logger.bind(tag=TAG).info("Adding vision routes")
app.add_routes([
web.get("/mcp/vision/explain",
self.vision_handler.handle_get),
web.post("/mcp/vision/explain",
self.vision_handler.handle_post),
web.options("/mcp/vision/explain",
self.vision_handler.handle_post),
])
# Run service
self.logger.bind(tag=TAG).info("Setting up HTTP server runner") self.logger.bind(tag=TAG).info("Setting up HTTP server runner")
runner = web.AppRunner(app) runner = web.AppRunner(app)
await runner.setup() await runner.setup()
site = web.TCPSite(runner, host, port) site = web.TCPSite(runner, host, port)
await site.start() await site.start()
self.logger.bind(tag=TAG).info(f"HTTP server started successfully on {host}:{port}")
# 保持服务运行 self.logger.bind(tag=TAG).info(
f"HTTP server started successfully on {host}:{port}")
# Keep service running
while True: while True:
await asyncio.sleep(3600) # 每隔 1 小时检查一次 await asyncio.sleep(3600) # Check every hour
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to start HTTP server: {e}") self.logger.bind(tag=TAG).error(
f"Failed to start HTTP server: {e}")
raise raise

View file

@ -1,15 +1,16 @@
import http.client
import json import json
import asyncio import time
from typing import Optional, Tuple, List
import os
import uuid import uuid
import hmac import hmac
import hashlib
import base64 import base64
import hashlib
import asyncio
import requests import requests
import websockets
import opuslib_next
import random
from typing import Optional, Tuple, List
from urllib import parse from urllib import parse
import time
from datetime import datetime from datetime import datetime
from config.logger import setup_logging from config.logger import setup_logging
from core.providers.asr.base import ASRProviderBase from core.providers.asr.base import ASRProviderBase
@ -18,7 +19,6 @@ from core.providers.asr.dto.dto import InterfaceType
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class AccessToken: class AccessToken:
@staticmethod @staticmethod
def _encode_text(text): def _encode_text(text):
@ -45,204 +45,301 @@ class AccessToken:
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28", "Version": "2019-02-28",
} }
# 构造规范化的请求字符串
query_string = AccessToken._encode_dict(parameters) query_string = AccessToken._encode_dict(parameters)
# print('规范化的请求字符串: %s' % query_string)
# 构造待签名字符串
string_to_sign = ( string_to_sign = (
"GET" "GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string)
+ "&"
+ AccessToken._encode_text("/")
+ "&"
+ AccessToken._encode_text(query_string)
) )
# print('待签名的字符串: %s' % string_to_sign)
# 计算签名
secreted_string = hmac.new( secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"), bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"), bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1, hashlib.sha1,
).digest() ).digest()
signature = base64.b64encode(secreted_string) signature = base64.b64encode(secreted_string)
# print('签名: %s' % signature)
# 进行URL编码
signature = AccessToken._encode_text(signature) signature = AccessToken._encode_text(signature)
# print('URL编码后的签名: %s' % signature)
# 调用服务 full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string)
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature,
query_string,
)
# print('url: %s' % full_url)
# 提交HTTP GET请求
response = requests.get(full_url) response = requests.get(full_url)
if response.ok: if response.ok:
root_obj = response.json() root_obj = response.json()
key = "Token" if "Token" in root_obj:
if key in root_obj: return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"]
token = root_obj[key]["Id"]
expire_time = root_obj[key]["ExpireTime"]
return token, expire_time
# print(response.text)
return None, None return None, None
class ASRProvider(ASRProviderBase): class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool): def __init__(self, config, delete_audio_file):
super().__init__() super().__init__()
self.interface_type = InterfaceType.NON_STREAM self.interface_type = InterfaceType.STREAM
"""阿里云ASR初始化""" self.config = config
# 新增空值判断逻辑 self.text = ""
self.decoder = opuslib_next.Decoder(16000, 1)
self.asr_ws = None
self.forward_task = None
self.is_processing = False
self.server_ready = False # Server ready status
# Basic configuration
self.access_key_id = config.get("access_key_id") self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret") self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.token = config.get("token")
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
self.app_key = config.get("appkey") # If configured as internal address (containing -internal.aliyuncs.com), use ws protocol, default is wss protocol
self.host = "nls-gateway-cn-shanghai.aliyuncs.com" if "-internal." in self.host:
self.base_url = f"https://{self.host}/stream/v1/asr" self.ws_url = f"ws://{self.host}/ws/v1"
self.sample_rate = 16000 else:
self.format = "wav" # Default use wss protocol
self.ws_url = f"wss://{self.host}/ws/v1"
self.max_sentence_silence = config.get("max_sentence_silence")
self.output_dir = config.get("output_dir", "./audio_output") self.output_dir = config.get("output_dir", "./audio_output")
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.expire_time = None
# Token management
if self.access_key_id and self.access_key_secret: if self.access_key_id and self.access_key_secret:
# 使用密钥对生成临时token
self._refresh_token() self._refresh_token()
else: elif not self.token:
# 直接使用预生成的长期token raise ValueError("Must provide access_key_id+access_key_secret or directly provide token")
self.token = config.get("token")
self.expire_time = None
# 确保输出目录存在
os.makedirs(self.output_dir, exist_ok=True)
def _refresh_token(self): def _refresh_token(self):
"""刷新Token并记录过期时间""" """Refresh Token"""
if self.access_key_id and self.access_key_secret: self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
self.token, expire_time_str = AccessToken.create_token( if not self.token:
self.access_key_id, self.access_key_secret raise ValueError("Unable to get valid access Token")
)
if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间")
try: try:
# 统一转换为字符串处理 expire_str = str(expire_time_str).strip()
expire_str = str(expire_time_str).strip() if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
if expire_str.isdigit(): else:
expire_time = datetime.fromtimestamp(int(expire_str)) expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
else: self.expire_time = expire_time.timestamp() - 60
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") except:
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
else:
self.expire_time = None self.expire_time = None
if not self.token:
raise ValueError("无法获取有效的访问Token")
def _is_token_expired(self): def _is_token_expired(self):
"""检查Token是否过期""" """Check if Token has expired"""
if not self.expire_time: return self.expire_time and time.time() > self.expire_time
return False # 长期Token不过期
# 新增调试日志
# current_time = time.time()
# remaining = self.expire_time - current_time
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
# f"剩余 {remaining:.2f}秒")
return time.time() > self.expire_time
def _construct_request_url(self) -> str: async def open_audio_channels(self, conn):
"""构造请求URL,包含参数""" await super().open_audio_channels(conn)
request = f"{self.base_url}?appkey={self.app_key}"
request += f"&format={self.format}"
request += f"&sample_rate={self.sample_rate}"
request += "&enable_punctuation_prediction=true"
request += "&enable_inverse_text_normalization=true"
request += "&enable_voice_detection=false"
return request
async def _send_request(self, pcm_data: bytes) -> Optional[str]: async def receive_audio(self, conn, audio, audio_have_voice):
"""发送请求到阿里云ASR服务""" # Initialize audio cache
try: if not hasattr(conn, 'asr_audio_for_voiceprint'):
# 设置HTTP头 conn.asr_audio_for_voiceprint = []
headers = {
"X-NLS-Token": self.token,
"Content-type": "application/octet-stream",
"Content-Length": str(len(pcm_data)),
}
# 创建连接并发送请求 # Store audio data
conn = http.client.HTTPSConnection(self.host) if audio:
request_url = self._construct_request_url() conn.asr_audio_for_voiceprint.append(audio)
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
loop = asyncio.get_event_loop() # Only establish connection when there is voice and no connection exists
await loop.run_in_executor( if audio_have_voice and not self.is_processing:
None,
lambda: conn.request(
method="POST", url=request_url, body=pcm_data, headers=headers
),
)
# 获取响应
response = await loop.run_in_executor(None, conn.getresponse)
body = await loop.run_in_executor(None, response.read)
conn.close()
# 解析响应
try: try:
body_json = json.loads(body) await self._start_recognition(conn)
status = body_json.get("status") except Exception as e:
logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}")
await self._cleanup(conn)
return
if status == 20000000: if self.asr_ws and self.is_processing and self.server_ready:
result = body_json.get("result", "") try:
logger.bind(tag=TAG).debug(f"ASR结果: {result}") pcm_frame = self.decoder.decode(audio, 960)
return result await self.asr_ws.send(pcm_frame)
else: except Exception as e:
logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}") logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
return None await self._cleanup(conn)
except ValueError: async def _start_recognition(self, conn):
logger.bind(tag=TAG).error("响应不是JSON格式") """Start recognition session"""
return None
except Exception as e:
logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True)
return None
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
if self._is_token_expired(): if self._is_token_expired():
logger.warning("Token已过期,正在自动刷新...")
self._refresh_token() self._refresh_token()
file_path = None # Establish connection
headers = {"X-NLS-Token": self.token}
self.asr_ws = await websockets.connect(
self.ws_url,
additional_headers=headers,
max_size=1000000000,
ping_interval=None,
ping_timeout=None,
close_timeout=5,
)
self.is_processing = True
self.server_ready = False # Reset server ready status
self.forward_task = asyncio.create_task(self._forward_results(conn))
# Send start request
start_request = {
"header": {
"namespace": "SpeechTranscriber",
"name": "StartTranscription",
"status": 20000000,
"message_id": ''.join(random.choices('0123456789abcdef', k=32)),
"task_id": ''.join(random.choices('0123456789abcdef', k=32)),
"status_text": "Gateway:SUCCESS:Success.",
"appkey": self.appkey
},
"payload": {
"format": "pcm",
"sample_rate": 16000,
"enable_intermediate_result": True,
"enable_punctuation_prediction": True,
"enable_inverse_text_normalization": True,
"max_sentence_silence": self.max_sentence_silence,
"enable_voice_detection": False,
}
}
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
logger.bind(tag=TAG).info("Start request sent, waiting for server ready...")
async def _forward_results(self, conn):
"""Forward recognition results"""
try: try:
# 解码Opus为PCM while self.asr_ws and not conn.stop_event.is_set():
if audio_format == "pcm": try:
pcm_data = opus_data response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
else: result = json.loads(response)
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件 header = result.get("header", {})
if self.delete_audio_file: payload = result.get("payload", {})
pass message_name = header.get("name", "")
else: status = header.get("status", 0)
file_path = self.save_audio_to_file(pcm_data, session_id)
# 发送请求并获取文本 if status != 20000000:
text = await self._send_request(combined_pcm_data) if status in [40000004, 40010004]: # Connection timeout or client disconnect
logger.bind(tag=TAG).warning(f"Connection issue, status code: {status}")
break
elif status in [40270002, 40270003]: # Audio issue
logger.bind(tag=TAG).warning(f"Audio processing issue, status code: {status}")
continue
else:
logger.bind(tag=TAG).error(f"Recognition error, status code: {status}, message: {header.get('status_text', '')}")
continue
if text: # Receiving TranscriptionStarted means server is ready to receive audio data
return text, file_path if message_name == "TranscriptionStarted":
self.server_ready = True
logger.bind(tag=TAG).info("Server ready, starting to send cached audio...")
# Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}")
break
continue
return "", file_path if message_name == "TranscriptionResultChanged":
# Intermediate result
text = payload.get("result", "")
if text:
self.text = text
elif message_name == "SentenceEnd":
# Final result
text = payload.get("result", "")
if text:
self.text = text
conn.reset_vad_states()
# Pass cached audio data
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
await self.handle_voice_stop(conn, audio_data)
# Clear cache
conn.asr_audio_for_voiceprint = []
break
elif message_name == "TranscriptionCompleted":
# Recognition completed
self.is_processing = False
break
except asyncio.TimeoutError:
continue
except websockets.exceptions.ConnectionClosed:
break
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to process result: {str(e)}")
break
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
return "", file_path finally:
await self._cleanup(conn)
async def _cleanup(self, conn):
"""Clean up resources"""
logger.bind(tag=TAG).info(f"Starting ASR session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}")
# Clear connection audio cache
if conn and hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# Determine if stop request needs to be sent
should_stop = self.is_processing or self.server_ready
# Send stop recognition request
if self.asr_ws and should_stop:
try:
stop_msg = {
"header": {
"namespace": "SpeechTranscriber",
"name": "StopTranscription",
"status": 20000000,
"message_id": ''.join(random.choices('0123456789abcdef', k=32)),
"status_text": "Client:Stop",
"appkey": self.appkey
}
}
logger.bind(tag=TAG).info("Sending ASR termination request")
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
await asyncio.sleep(0.1)
logger.bind(tag=TAG).info("ASR termination request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to send ASR termination request: {e}")
# Status reset (after termination request is sent)
self.is_processing = False
self.server_ready = False
logger.bind(tag=TAG).info("ASR status reset")
# Clean up task
if self.forward_task and not self.forward_task.done():
self.forward_task.cancel()
try:
await asyncio.wait_for(self.forward_task, timeout=1.0)
except Exception as e:
logger.bind(tag=TAG).debug(f"forward_task cancel exception: {e}")
finally:
self.forward_task = None
# Close connection
if self.asr_ws:
try:
logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
logger.bind(tag=TAG).info("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
"""Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
"""Close resources"""
await self._cleanup()

View file

@ -0,0 +1,364 @@
import json
import time
import uuid
import hmac
import base64
import hashlib
import asyncio
import requests
import websockets
import opuslib_next
import random
from typing import Optional, Tuple, List
from urllib import parse
from datetime import datetime
from config.logger import setup_logging
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class AccessToken:
@staticmethod
def _encode_text(text):
encoded_text = parse.quote_plus(text)
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
@staticmethod
def _encode_dict(dic):
keys = dic.keys()
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
encoded_text = parse.urlencode(dic_sorted)
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
@staticmethod
def create_token(access_key_id, access_key_secret):
parameters = {
"AccessKeyId": access_key_id,
"Action": "CreateToken",
"Format": "JSON",
"RegionId": "cn-shanghai",
"SignatureMethod": "HMAC-SHA1",
"SignatureNonce": str(uuid.uuid1()),
"SignatureVersion": "1.0",
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28",
}
query_string = AccessToken._encode_dict(parameters)
string_to_sign = (
"GET" + "&" +
AccessToken._encode_text("/") + "&" +
AccessToken._encode_text(query_string)
)
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1,
).digest()
signature = base64.b64encode(secreted_string)
signature = AccessToken._encode_text(signature)
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature, query_string)
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
if "Token" in root_obj:
return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"]
return None, None
class ASRProvider(ASRProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__()
self.interface_type = InterfaceType.STREAM
self.config = config
self.text = ""
self.decoder = opuslib_next.Decoder(16000, 1)
self.asr_ws = None
self.forward_task = None
self.is_processing = False
self.server_ready = False # Server ready status
# Basic configuration
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.token = config.get("token")
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
# If configured with internal address (contains -internal.aliyuncs.com), use ws protocol, default is wss protocol
if "-internal." in self.host:
self.ws_url = f"ws://{self.host}/ws/v1"
else:
# Default to wss protocol
self.ws_url = f"wss://{self.host}/ws/v1"
self.max_sentence_silence = config.get("max_sentence_silence")
self.output_dir = config.get("output_dir", "./audio_output")
self.delete_audio_file = delete_audio_file
self.expire_time = None
# Token management
if self.access_key_id and self.access_key_secret:
self._refresh_token()
elif not self.token:
raise ValueError(
"Must provide access_key_id+access_key_secret or provide token directly")
def _refresh_token(self):
"""Refresh Token"""
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret)
if not self.token:
raise ValueError("Unable to obtain valid access Token")
try:
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
else:
expire_time = datetime.strptime(
expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except:
self.expire_time = None
def _is_token_expired(self):
"""Check if Token is expired"""
return self.expire_time and time.time() > self.expire_time
async def open_audio_channels(self, conn):
await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice):
# Initialize audio cache
if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# Store audio data
if audio:
conn.asr_audio_for_voiceprint.append(audio)
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
# Only establish connection when there is voice and no existing connection
if audio_have_voice and not self.is_processing:
try:
await self._start_recognition(conn)
except Exception as e:
logger.bind(tag=TAG).error(
f"Failed to start recognition: {str(e)}")
await self._cleanup(conn)
return
if self.asr_ws and self.is_processing and self.server_ready:
try:
pcm_frame = self.decoder.decode(audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup(conn)
async def _start_recognition(self, conn):
"""Start recognition session"""
if self._is_token_expired():
self._refresh_token()
# Establish connection
headers = {"X-NLS-Token": self.token}
self.asr_ws = await websockets.connect(
self.ws_url,
additional_headers=headers,
max_size=1000000000,
ping_interval=None,
ping_timeout=None,
close_timeout=5,
)
self.is_processing = True
self.server_ready = False # Reset server ready status
self.forward_task = asyncio.create_task(self._forward_results(conn))
# Send start request
start_request = {
"header": {
"namespace": "SpeechTranscriber",
"name": "StartTranscription",
"status": 20000000,
"message_id": ''.join(random.choices('0123456789abcdef', k=32)),
"task_id": ''.join(random.choices('0123456789abcdef', k=32)),
"status_text": "Gateway:SUCCESS:Success.",
"appkey": self.appkey
},
"payload": {
"format": "pcm",
"sample_rate": 16000,
"enable_intermediate_result": True,
"enable_punctuation_prediction": True,
"enable_inverse_text_normalization": True,
"max_sentence_silence": self.max_sentence_silence,
"enable_voice_detection": False,
}
}
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
logger.bind(tag=TAG).info(
"Start request sent, waiting for server to be ready...")
async def _forward_results(self, conn):
"""Forward recognition results"""
try:
while self.asr_ws and not conn.stop_event.is_set():
try:
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
result = json.loads(response)
header = result.get("header", {})
payload = result.get("payload", {})
message_name = header.get("name", "")
status = header.get("status", 0)
if status != 20000000:
# Connection timeout or client disconnect
if status in [40000004, 40010004]:
logger.bind(tag=TAG).warning(
f"Connection issue, status code: {status}")
break
elif status in [40270002, 40270003]: # Audio issues
logger.bind(tag=TAG).warning(
f"Audio processing issue, status code: {status}")
continue
else:
logger.bind(tag=TAG).error(
f"Recognition error, status code: {status}, message: {header.get('status_text', '')}")
continue
# TranscriptionStarted indicates server is ready to receive audio data
if message_name == "TranscriptionStarted":
self.server_ready = True
logger.bind(tag=TAG).info(
"Server is ready, starting to send cached audio...")
# Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(
cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(
f"Failed to send cached audio: {e}")
break
continue
if message_name == "TranscriptionResultChanged":
# Intermediate result
text = payload.get("result", "")
if text:
self.text = text
elif message_name == "SentenceEnd":
# Final result
text = payload.get("result", "")
if text:
self.text = text
conn.reset_vad_states()
# Pass cached audio data
audio_data = getattr(
conn, 'asr_audio_for_voiceprint', [])
await self.handle_voice_stop(conn, audio_data)
# Clear cache
conn.asr_audio_for_voiceprint = []
break
elif message_name == "TranscriptionCompleted":
# Recognition completed
self.is_processing = False
break
except asyncio.TimeoutError:
continue
except websockets.exceptions.ConnectionClosed:
break
except Exception as e:
logger.bind(tag=TAG).error(
f"Failed to process result: {str(e)}")
break
except Exception as e:
logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally:
await self._cleanup(conn)
async def _cleanup(self, conn):
"""Clean up resources"""
logger.bind(tag=TAG).info(
f"Starting ASR session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}")
# Clean up connection's audio cache
if conn and hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# Determine if stop request needs to be sent
should_stop = self.is_processing or self.server_ready
# Send stop recognition request
if self.asr_ws and should_stop:
try:
stop_msg = {
"header": {
"namespace": "SpeechTranscriber",
"name": "StopTranscription",
"status": 20000000,
"message_id": ''.join(random.choices('0123456789abcdef', k=32)),
"status_text": "Client:Stop",
"appkey": self.appkey
}
}
logger.bind(tag=TAG).info("Sending ASR termination request")
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
await asyncio.sleep(0.1)
logger.bind(tag=TAG).info("ASR termination request sent")
except Exception as e:
logger.bind(tag=TAG).error(
f"ASR termination request failed to send: {e}")
# Status reset (after termination request is sent)
self.is_processing = False
self.server_ready = False
logger.bind(tag=TAG).info("ASR status has been reset")
# Clean up tasks
if self.forward_task and not self.forward_task.done():
self.forward_task.cancel()
try:
await asyncio.wait_for(self.forward_task, timeout=1.0)
except Exception as e:
logger.bind(tag=TAG).debug(
f"forward_task cancellation exception: {e}")
finally:
self.forward_task = None
# Close connection
if self.asr_ws:
try:
logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
logger.bind(tag=TAG).error(
f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
logger.bind(tag=TAG).info("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
"""Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
"""Close resources"""
await self._cleanup()

View file

@ -9,7 +9,6 @@ from core.providers.asr.dto.dto import InterfaceType
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class ASRProvider(ASRProviderBase): class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool = True): def __init__(self, config: dict, delete_audio_file: bool = True):
super().__init__() super().__init__()
@ -17,48 +16,48 @@ class ASRProvider(ASRProviderBase):
self.app_id = config.get("app_id") self.app_id = config.get("app_id")
self.api_key = config.get("api_key") self.api_key = config.get("api_key")
self.secret_key = config.get("secret_key") self.secret_key = config.get("secret_key")
dev_pid = config.get("dev_pid", "1537") dev_pid = config.get("dev_pid", "1537")
self.dev_pid = int(dev_pid) if dev_pid else 1537 self.dev_pid = int(dev_pid) if dev_pid else 1537
self.output_dir = config.get("output_dir") self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key) self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key)
# 确保输出目录存在 # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True) os.makedirs(self.output_dir, exist_ok=True)
async def speech_to_text( async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus" self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本""" """Convert speech data to text"""
if not opus_data: if not opus_data:
logger.bind(tag=TAG).warning("音频数据为空!") logger.bind(tag=TAG).warning("Audio data is empty!")
return None, None return None, None
file_path = None file_path = None
try: try:
# 检查配置是否已设置 # Check if configuration is set
if not self.app_id or not self.api_key or not self.secret_key: if not self.app_id or not self.api_key or not self.secret_key:
logger.bind(tag=TAG).error("百度语音识别配置未设置,无法进行识别") logger.bind(tag=TAG).error("Baidu speech recognition configuration not set, cannot perform recognition")
return None, file_path return None, file_path
# 将Opus音频数据解码为PCM # Decode Opus audio data to PCM
if audio_format == "pcm": if audio_format == "pcm":
pcm_data = opus_data pcm_data = opus_data
else: else:
pcm_data = self.decode_opus(opus_data) pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data) combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件 # Determine whether to save as WAV file
if self.delete_audio_file: if self.delete_audio_file:
pass pass
else: else:
self.save_audio_to_file(pcm_data, session_id) self.save_audio_to_file(pcm_data, session_id)
start_time = time.time() start_time = time.time()
# 识别本地文件
# Recognize local file
result = self.client.asr( result = self.client.asr(
combined_pcm_data, combined_pcm_data,
"pcm", "pcm",
@ -70,16 +69,17 @@ class ASRProvider(ASRProviderBase):
if result and result["err_no"] == 0: if result and result["err_no"] == 0:
logger.bind(tag=TAG).debug( logger.bind(tag=TAG).debug(
f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}" f"Baidu speech recognition time: {time.time() - start_time:.3f}s | Result: {result}"
) )
result = result["result"][0] result = result["result"][0]
return result, file_path return result, file_path
else: else:
raise Exception( raise Exception(
f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}" f"Baidu speech recognition failed, error code: {result['err_no']}, error message: {result['err_msg']}"
) )
return None, file_path
return None, file_path
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) logger.bind(tag=TAG).error(f"Error occurred while processing audio! {e}", exc_info=True)
return None, file_path return None, file_path

View file

@ -1,15 +1,18 @@
import os import os
import wave import wave
import copy
import uuid import uuid
import queue import queue
import asyncio import asyncio
import traceback import traceback
import threading import threading
import opuslib_next import opuslib_next
import json
import io
import time
import concurrent.futures
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from config.logger import setup_logging from config.logger import setup_logging
from typing import Optional, Tuple, List from typing import Optional, Tuple, List, Dict, Any
from core.handle.receiveAudioHandle import startToChat from core.handle.receiveAudioHandle import startToChat
from core.handle.reportHandle import enqueue_asr_report from core.handle.reportHandle import enqueue_asr_report
from core.utils.util import remove_punctuation_and_length from core.utils.util import remove_punctuation_and_length
@ -23,17 +26,14 @@ class ASRProviderBase(ABC):
def __init__(self): def __init__(self):
pass pass
# 打开音频通道 # Open audio channels
# 这里默认是非流式的处理方式
# 流式处理方式请在子类中重写
async def open_audio_channels(self, conn): async def open_audio_channels(self, conn):
# tts 消化线程
conn.asr_priority_thread = threading.Thread( conn.asr_priority_thread = threading.Thread(
target=self.asr_text_priority_thread, args=(conn,), daemon=True target=self.asr_text_priority_thread, args=(conn,), daemon=True
) )
conn.asr_priority_thread.start() conn.asr_priority_thread.start()
# 有序处理ASR音频 # Process ASR audio in order
def asr_text_priority_thread(self, conn): def asr_text_priority_thread(self, conn):
while not conn.stop_event.is_set(): while not conn.stop_event.is_set():
try: try:
@ -47,52 +47,191 @@ class ASRProviderBase(ABC):
continue continue
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error( logger.bind(tag=TAG).error(
f"处理ASR文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}" f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
) )
continue continue
# 接收音频 # Receive audio
# 这里默认是非流式的处理方式
# 流式处理方式请在子类中重写
async def receive_audio(self, conn, audio, audio_have_voice): async def receive_audio(self, conn, audio, audio_have_voice):
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime": if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
have_voice = audio_have_voice have_voice = audio_have_voice
else: else:
have_voice = conn.client_have_voice have_voice = conn.client_have_voice
# 如果本次没有声音,本段也没声音,就把声音丢弃了
conn.asr_audio.append(audio) conn.asr_audio.append(audio)
if have_voice == False and conn.client_have_voice == False: if not have_voice and not conn.client_have_voice:
conn.asr_audio = conn.asr_audio[-10:] conn.asr_audio = conn.asr_audio[-10:]
return return
# 如果本段有声音,且已经停止了
if conn.client_voice_stop: if conn.client_voice_stop:
asr_audio_task = copy.deepcopy(conn.asr_audio) asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear() conn.asr_audio.clear()
# 音频太短了,无法识别
conn.reset_vad_states() conn.reset_vad_states()
if len(asr_audio_task) > 15: if len(asr_audio_task) > 15:
await self.handle_voice_stop(conn, asr_audio_task) await self.handle_voice_stop(conn, asr_audio_task)
# 处理语音停止 # Handle voice stop
async def handle_voice_stop(self, conn, asr_audio_task): async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
raw_text, _ = await self.speech_to_text( """Parallel processing of ASR and voiceprint recognition"""
asr_audio_task, conn.session_id, conn.audio_format try:
) # 确保ASR模块返回原始文本 total_start_time = time.monotonic()
conn.logger.bind(tag=TAG).info(f"识别文本: {raw_text}")
text_len, _ = remove_punctuation_and_length(raw_text) # Prepare audio data
self.stop_ws_connection() if conn.audio_format == "pcm":
if text_len > 0: pcm_data = asr_audio_task
# 使用自定义模块进行上报 else:
await startToChat(conn, raw_text) pcm_data = self.decode_opus(asr_audio_task)
enqueue_asr_report(conn, raw_text, asr_audio_task)
combined_pcm_data = b"".join(pcm_data)
# Pre-prepare WAV data
wav_data = None
# Use connection's voiceprint provider
if conn.voiceprint_provider and combined_pcm_data:
wav_data = self._pcm_to_wav(combined_pcm_data)
# Define ASR task
def run_asr():
start_time = time.monotonic()
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
self.speech_to_text(
asr_audio_task, conn.session_id, conn.audio_format)
)
end_time = time.monotonic()
logger.bind(tag=TAG).info(
f"ASR time: {end_time - start_time:.3f}s")
return result
finally:
loop.close()
except Exception as e:
end_time = time.monotonic()
logger.bind(tag=TAG).error(f"ASR failed: {e}")
return ("", None)
# Define voiceprint recognition task
def run_voiceprint():
if not wav_data:
return None
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
# Use connection's voiceprint provider
result = loop.run_until_complete(
conn.voiceprint_provider.identify_speaker(
wav_data, conn.session_id)
)
return result
finally:
loop.close()
except Exception as e:
logger.bind(tag=TAG).error(
f"Voiceprint recognition failed: {e}")
return None
# Run in parallel using thread pool executor
parallel_start_time = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
asr_future = thread_executor.submit(run_asr)
if conn.voiceprint_provider and wav_data:
voiceprint_future = thread_executor.submit(run_voiceprint)
# Wait for both threads to complete
asr_result = asr_future.result(timeout=15)
voiceprint_result = voiceprint_future.result(timeout=15)
results = {"asr": asr_result,
"voiceprint": voiceprint_result}
else:
asr_result = asr_future.result(timeout=15)
results = {"asr": asr_result, "voiceprint": None}
# Process results
raw_text, file_path = results.get("asr", ("", None))
speaker_name = results.get("voiceprint", None)
# Log recognition results
if raw_text:
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")
if speaker_name:
logger.bind(tag=TAG).info(
f"Identified speaker: {speaker_name}")
# Performance monitoring
total_time = time.monotonic() - total_start_time
logger.bind(tag=TAG).info(
f"Total processing time: {total_time:.3f}s")
# Check text length
text_len, _ = remove_punctuation_and_length(raw_text)
self.stop_ws_connection()
if text_len > 0:
# Build JSON string with speaker information
enhanced_text = self._build_enhanced_text(
raw_text, speaker_name)
# Use custom module for reporting
await startToChat(conn, enhanced_text)
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
logger.bind(tag=TAG).debug(
f"Exception details: {traceback.format_exc()}")
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
"""Build text with speaker information"""
if speaker_name and speaker_name.strip():
return json.dumps({
"speaker": speaker_name,
"content": text
}, ensure_ascii=False)
else:
return text
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
"""Convert PCM data to WAV format"""
if len(pcm_data) == 0:
logger.bind(tag=TAG).warning(
"PCM data is empty, cannot convert to WAV")
return b""
# Ensure data length is even (16-bit audio)
if len(pcm_data) % 2 != 0:
pcm_data = pcm_data[:-1]
# Create WAV file header
wav_buffer = io.BytesIO()
try:
with wave.open(wav_buffer, 'wb') as wav_file:
wav_file.setnchannels(1) # Mono
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
wav_buffer.seek(0)
wav_data = wav_buffer.read()
return wav_data
except Exception as e:
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
return b""
def stop_ws_connection(self): def stop_ws_connection(self):
pass pass
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str: def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
"""PCM数据保存为WAV文件""" """Save PCM data as WAV file"""
module_name = __name__.split(".")[-1] module_name = __name__.split(".")[-1]
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav" file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
file_path = os.path.join(self.output_dir, file_name) file_path = os.path.join(self.output_dir, file_name)
@ -109,31 +248,36 @@ class ASRProviderBase(ABC):
async def speech_to_text( async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus" self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本""" """Convert speech data to text"""
pass pass
@staticmethod @staticmethod
def decode_opus(opus_data: List[bytes]) -> bytes: def decode_opus(opus_data: List[bytes]) -> List[bytes]:
"""将Opus音频数据解码为PCM数据""" """Decode Opus audio data to PCM data"""
try: try:
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道 decoder = opuslib_next.Decoder(16000, 1)
pcm_data = [] pcm_data = []
buffer_size = 960 # 每次处理960个采样点 buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
for opus_packet in opus_data: for i, opus_packet in enumerate(opus_data):
try: try:
# 使用较小的缓冲区大小进行处理 if not opus_packet or len(opus_packet) == 0:
continue
pcm_frame = decoder.decode(opus_packet, buffer_size) pcm_frame = decoder.decode(opus_packet, buffer_size)
if pcm_frame: if pcm_frame and len(pcm_frame) > 0:
pcm_data.append(pcm_frame) pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e: except opuslib_next.OpusError as e:
logger.bind(tag=TAG).warning(f"Opus解码错误,跳过当前数据包: {e}") logger.bind(tag=TAG).warning(
continue f"Opus decode error, skipping packet {i}: {e}")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"音频处理错误: {e}", exc_info=True) logger.bind(tag=TAG).error(
continue f"Audio processing error, packet {i}: {e}")
return pcm_data return pcm_data
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}", exc_info=True) logger.bind(tag=TAG).error(
f"Error occurred during audio decoding: {e}")
return [] return []

View file

@ -9,20 +9,16 @@ from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType from core.providers.asr.dto.dto import InterfaceType
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
CLIENT_FULL_REQUEST = 0b0001 CLIENT_FULL_REQUEST = 0b0001
CLIENT_AUDIO_ONLY_REQUEST = 0b0010 CLIENT_AUDIO_ONLY_REQUEST = 0b0010
NO_SEQUENCE = 0b0000 NO_SEQUENCE = 0b0000
NEG_SEQUENCE = 0b0010 NEG_SEQUENCE = 0b0010
SERVER_FULL_RESPONSE = 0b1001 SERVER_FULL_RESPONSE = 0b1001
SERVER_ACK = 0b1011 SERVER_ACK = 0b1011
SERVER_ERROR_RESPONSE = 0b1111 SERVER_ERROR_RESPONSE = 0b1111
NO_SERIALIZATION = 0b0000 NO_SERIALIZATION = 0b0000
JSON = 0b0001 JSON = 0b0001
THRIFT = 0b0011 THRIFT = 0b0011
@ -37,9 +33,9 @@ def parse_response(res):
protocol_version(4 bits), header_size(4 bits), protocol_version(4 bits), header_size(4 bits),
message_type(4 bits), message_type_specific_flags(4 bits) message_type(4 bits), message_type_specific_flags(4 bits)
serialization_method(4 bits) message_compression(4 bits) serialization_method(4 bits) message_compression(4 bits)
reserved (8bits) 保留字段 reserved (8bits) reserved field
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) header_extensions extension header (size equals 8 * 4 * (header_size - 1))
payload 类似与http 请求体 payload similar to http request body
""" """
protocol_version = res[0] >> 4 protocol_version = res[0] >> 4
header_size = res[0] & 0x0F header_size = res[0] & 0x0F
@ -48,11 +44,13 @@ def parse_response(res):
serialization_method = res[2] >> 4 serialization_method = res[2] >> 4
message_compression = res[2] & 0x0F message_compression = res[2] & 0x0F
reserved = res[3] reserved = res[3]
header_extensions = res[4 : header_size * 4] header_extensions = res[4: header_size * 4]
payload = res[header_size * 4 :] payload = res[header_size * 4:]
result = {} result = {}
payload_msg = None payload_msg = None
payload_size = 0 payload_size = 0
if message_type == SERVER_FULL_RESPONSE: if message_type == SERVER_FULL_RESPONSE:
payload_size = int.from_bytes(payload[:4], "big", signed=True) payload_size = int.from_bytes(payload[:4], "big", signed=True)
payload_msg = payload[4:] payload_msg = payload[4:]
@ -67,16 +65,21 @@ def parse_response(res):
result["code"] = code result["code"] = code
payload_size = int.from_bytes(payload[4:8], "big", signed=False) payload_size = int.from_bytes(payload[4:8], "big", signed=False)
payload_msg = payload[8:] payload_msg = payload[8:]
if payload_msg is None: if payload_msg is None:
return result return result
if message_compression == GZIP: if message_compression == GZIP:
payload_msg = gzip.decompress(payload_msg) payload_msg = gzip.decompress(payload_msg)
if serialization_method == JSON: if serialization_method == JSON:
payload_msg = json.loads(str(payload_msg, "utf-8")) payload_msg = json.loads(str(payload_msg, "utf-8"))
elif serialization_method != NO_SERIALIZATION: elif serialization_method != NO_SERIALIZATION:
payload_msg = str(payload_msg, "utf-8") payload_msg = str(payload_msg, "utf-8")
result["payload_msg"] = payload_msg result["payload_msg"] = payload_msg
result["payload_size"] = payload_size result["payload_size"] = payload_size
return result return result
@ -91,13 +94,12 @@ class ASRProvider(ASRProviderBase):
self.correct_table_name = config.get("correct_table_name", "") self.correct_table_name = config.get("correct_table_name", "")
self.output_dir = config.get("output_dir") self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.host = "openspeech.bytedance.com" self.host = "openspeech.bytedance.com"
self.ws_url = f"wss://{self.host}/api/v2/asr" self.ws_url = f"wss://{self.host}/api/v2/asr"
self.success_code = 1000 self.success_code = 1000
self.seg_duration = 15000 self.seg_duration = 15000
# 确保输出目录存在 # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True) os.makedirs(self.output_dir, exist_ok=True)
@staticmethod @staticmethod
@ -107,10 +109,13 @@ class ASRProvider(ASRProviderBase):
"""Generate protocol header.""" """Generate protocol header."""
header = bytearray() header = bytearray()
header_size = 1 header_size = 1
header.append((0b0001 << 4) | header_size) # Protocol version header.append((0b0001 << 4) | header_size) # Protocol version
header.append((message_type << 4) | message_type_specific_flags) header.append((message_type << 4) | message_type_specific_flags)
header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression # JSON serialization & GZIP compression
header.append((0b0001 << 4) | 0b0001)
header.append(0x00) # reserved header.append(0x00) # reserved
return header return header
def _construct_request(self, reqid) -> dict: def _construct_request(self, reqid) -> dict:
@ -146,7 +151,8 @@ class ASRProvider(ASRProviderBase):
) -> Optional[str]: ) -> Optional[str]:
"""Send request to Volcano ASR service.""" """Send request to Volcano ASR service."""
try: try:
auth_header = {"Authorization": "Bearer; {}".format(self.access_token)} auth_header = {
"Authorization": "Bearer; {}".format(self.access_token)}
async with websockets.connect( async with websockets.connect(
self.ws_url, additional_headers=auth_header self.ws_url, additional_headers=auth_header
) as websocket: ) as websocket:
@ -154,6 +160,7 @@ class ASRProvider(ASRProviderBase):
request_params = self._construct_request(str(uuid.uuid4())) request_params = self._construct_request(str(uuid.uuid4()))
payload_bytes = str.encode(json.dumps(request_params)) payload_bytes = str.encode(json.dumps(request_params))
payload_bytes = gzip.compress(payload_bytes) payload_bytes = gzip.compress(payload_bytes)
full_client_request = self._generate_header() full_client_request = self._generate_header()
full_client_request.extend( full_client_request.extend(
(len(payload_bytes)).to_bytes(4, "big") (len(payload_bytes)).to_bytes(4, "big")
@ -165,10 +172,12 @@ class ASRProvider(ASRProviderBase):
await websocket.send(full_client_request) await websocket.send(full_client_request)
res = await websocket.recv() res = await websocket.recv()
result = parse_response(res) result = parse_response(res)
if ( if (
"payload_msg" in result "payload_msg" in result
and result["payload_msg"]["code"] != self.success_code and result["payload_msg"]["code"] != self.success_code
and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误 # Ignore no valid voice error
and result["payload_msg"]["code"] != 1013
): ):
logger.bind(tag=TAG).error(f"ASR error: {result}") logger.bind(tag=TAG).error(f"ASR error: {result}")
return None return None
@ -185,34 +194,37 @@ class ASRProvider(ASRProviderBase):
audio_only_request = self._generate_header( audio_only_request = self._generate_header(
message_type=CLIENT_AUDIO_ONLY_REQUEST message_type=CLIENT_AUDIO_ONLY_REQUEST
) )
payload_bytes = gzip.compress(chunk) payload_bytes = gzip.compress(chunk)
audio_only_request.extend( audio_only_request.extend(
(len(payload_bytes)).to_bytes(4, "big") (len(payload_bytes)).to_bytes(4, "big")
) # payload size(4 bytes) ) # payload size(4 bytes)
audio_only_request.extend(payload_bytes) # payload audio_only_request.extend(payload_bytes) # payload
# Send audio data # Send audio data
await websocket.send(audio_only_request) await websocket.send(audio_only_request)
# Receive response # Receive response
response = await websocket.recv() response = await websocket.recv()
result = parse_response(response) result = parse_response(response)
if ( if (
"payload_msg" in result "payload_msg" in result
and result["payload_msg"]["code"] == self.success_code and result["payload_msg"]["code"] == self.success_code
): ):
if len(result["payload_msg"]["result"]) > 0: if len(result["payload_msg"]["result"]) > 0:
return result["payload_msg"]["result"][0]["text"] return result["payload_msg"]["result"][0]["text"]
return None return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013: elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
# 无有效语音,返回空字符串 # No valid voice, return empty string
return "" return ""
else: else:
logger.bind(tag=TAG).error(f"ASR error: {result}") logger.bind(tag=TAG).error(f"ASR error: {result}")
return None return None
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True) logger.bind(tag=TAG).error(
f"ASR request failed: {e}", exc_info=True)
return None return None
@staticmethod @staticmethod
@ -226,7 +238,7 @@ class ASRProvider(ASRProviderBase):
data_len = len(data) data_len = len(data)
offset = 0 offset = 0
while offset + chunk_size < data_len: while offset + chunk_size < data_len:
yield data[offset : offset + chunk_size], False yield data[offset: offset + chunk_size], False
offset += chunk_size offset += chunk_size
else: else:
yield data[offset:data_len], True yield data[offset:data_len], True
@ -234,38 +246,40 @@ class ASRProvider(ASRProviderBase):
async def speech_to_text( async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus" self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本""" """Convert speech data to text"""
file_path = None file_path = None
try: try:
# 合并所有opus数据包 # Merge all opus data packets
if audio_format == "pcm": if audio_format == "pcm":
pcm_data = opus_data pcm_data = opus_data
else: else:
pcm_data = self.decode_opus(opus_data) pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data) combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件 # Determine whether to save as WAV file
if self.delete_audio_file: if self.delete_audio_file:
pass pass
else: else:
file_path = self.save_audio_to_file(pcm_data, session_id) file_path = self.save_audio_to_file(pcm_data, session_id)
# 直接使用PCM数据 # Use PCM data directly
# 计算分段大小 (单声道, 16bit, 16kHz采样率) # Calculate segment size (mono, 16bit, 16kHz sample rate)
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
segment_size = int(size_per_sec * self.seg_duration / 1000) segment_size = int(size_per_sec * self.seg_duration / 1000)
# 语音识别 # Speech recognition
start_time = time.time() start_time = time.time()
text = await self._send_request(combined_pcm_data, segment_size) text = await self._send_request(combined_pcm_data, segment_size)
if text: if text:
logger.bind(tag=TAG).debug( logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
) )
return text, file_path return text, file_path
return "", file_path return "", file_path
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path return "", file_path

View file

@ -1,351 +1,285 @@
import time
import os
import uuid
import json import json
import gzip import gzip
import uuid
import asyncio
import websockets import websockets
import opuslib_next
from core.providers.asr.base import ASRProviderBase
from config.logger import setup_logging from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType from core.providers.asr.dto.dto import InterfaceType
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
CLIENT_FULL_REQUEST = 0b0001
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
NO_SEQUENCE = 0b0000
NEG_SEQUENCE = 0b0010
SERVER_FULL_RESPONSE = 0b1001
SERVER_ACK = 0b1011
SERVER_ERROR_RESPONSE = 0b1111
NO_SERIALIZATION = 0b0000
JSON = 0b0001
THRIFT = 0b0011
CUSTOM_TYPE = 0b1111
NO_COMPRESSION = 0b0000
GZIP = 0b0001
CUSTOM_COMPRESSION = 0b1111
def parse_response(res):
"""
protocol_version(4 bits), header_size(4 bits),
message_type(4 bits), message_type_specific_flags(4 bits)
serialization_method(4 bits) message_compression(4 bits)
reserved (8bits) reserved field
header_extensions extension header (size equals 8 * 4 * (header_size - 1))
payload similar to http request body
"""
protocol_version = res[0] >> 4
header_size = res[0] & 0x0F
message_type = res[1] >> 4
message_type_specific_flags = res[1] & 0x0F
serialization_method = res[2] >> 4
message_compression = res[2] & 0x0F
reserved = res[3]
header_extensions = res[4: header_size * 4]
payload = res[header_size * 4:]
result = {}
payload_msg = None
payload_size = 0
if message_type == SERVER_FULL_RESPONSE:
payload_size = int.from_bytes(payload[:4], "big", signed=True)
payload_msg = payload[4:]
elif message_type == SERVER_ACK:
seq = int.from_bytes(payload[:4], "big", signed=True)
result["seq"] = seq
if len(payload) >= 8:
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
payload_msg = payload[8:]
elif message_type == SERVER_ERROR_RESPONSE:
code = int.from_bytes(payload[:4], "big", signed=False)
result["code"] = code
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
payload_msg = payload[8:]
if payload_msg is None:
return result
if message_compression == GZIP:
payload_msg = gzip.decompress(payload_msg)
if serialization_method == JSON:
payload_msg = json.loads(str(payload_msg, "utf-8"))
elif serialization_method != NO_SERIALIZATION:
payload_msg = str(payload_msg, "utf-8")
result["payload_msg"] = payload_msg
result["payload_size"] = payload_size
return result
class ASRProvider(ASRProviderBase): class ASRProvider(ASRProviderBase):
def __init__(self, config, delete_audio_file): def __init__(self, config: dict, delete_audio_file: bool):
super().__init__() super().__init__()
self.interface_type = InterfaceType.STREAM self.interface_type = InterfaceType.NON_STREAM
self.config = config self.appid = config.get("appid")
self.text = ""
self.max_retries = 3
self.retry_delay = 2
self.decoder = opuslib_next.Decoder(16000, 1)
self.asr_ws = None
self.forward_task = None
self.is_processing = False # 添加处理状态标志
# 配置参数
self.appid = str(config.get("appid"))
self.cluster = config.get("cluster") self.cluster = config.get("cluster")
self.access_token = config.get("access_token") self.access_token = config.get("access_token")
self.boosting_table_name = config.get("boosting_table_name", "") self.boosting_table_name = config.get("boosting_table_name", "")
self.correct_table_name = config.get("correct_table_name", "") self.correct_table_name = config.get("correct_table_name", "")
self.output_dir = config.get("output_dir", "tmp/") self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.host = "openspeech.bytedance.com"
self.ws_url = f"wss://{self.host}/api/v2/asr"
self.success_code = 1000
self.seg_duration = 15000
# 火山引擎ASR配置 # Ensure output directory exists
self.ws_url = "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel" os.makedirs(self.output_dir, exist_ok=True)
self.uid = config.get("uid", "streaming_asr_service")
self.workflow = config.get(
"workflow", "audio_in,resample,partition,vad,fe,decode,itn,nlu_punctuate"
)
self.result_type = config.get("result_type", "single")
self.format = config.get("format", "pcm")
self.codec = config.get("codec", "pcm")
self.rate = config.get("sample_rate", 16000)
self.language = config.get("language", "zh-CN")
self.bits = config.get("bits", 16)
self.channel = config.get("channel", 1)
self.auth_method = config.get("auth_method", "token")
self.secret = config.get("secret", "access_secret")
async def open_audio_channels(self, conn): @staticmethod
await super().open_audio_channels(conn) def _generate_header(
message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE
) -> bytearray:
"""Generate protocol header."""
header = bytearray()
header_size = 1
async def receive_audio(self, conn, audio, audio_have_voice): header.append((0b0001 << 4) | header_size) # Protocol version
conn.asr_audio.append(audio) header.append((message_type << 4) | message_type_specific_flags)
conn.asr_audio = conn.asr_audio[-10:] # JSON serialization & GZIP compression
header.append((0b0001 << 4) | 0b0001)
header.append(0x00) # reserved
# 如果本次有声音,且之前没有建立连接 return header
if audio_have_voice and self.asr_ws is None and not self.is_processing:
try:
self.is_processing = True
# 建立新的WebSocket连接
headers = self.token_auth() if self.auth_method == "token" else None
logger.bind(tag=TAG).info(f"正在连接ASR服务,headers: {headers}")
self.asr_ws = await websockets.connect( def _construct_request(self, reqid) -> dict:
self.ws_url, """Construct the request payload."""
additional_headers=headers, return {
max_size=1000000000,
ping_interval=None,
ping_timeout=None,
close_timeout=10,
)
# 发送初始化请求
request_params = self.construct_request(str(uuid.uuid4()))
try:
payload_bytes = str.encode(json.dumps(request_params))
payload_bytes = gzip.compress(payload_bytes)
full_client_request = self.generate_header()
full_client_request.extend((len(payload_bytes)).to_bytes(4, "big"))
full_client_request.extend(payload_bytes)
logger.bind(tag=TAG).info(f"发送初始化请求: {request_params}")
await self.asr_ws.send(full_client_request)
# 等待初始化响应
init_res = await self.asr_ws.recv()
result = self.parse_response(init_res)
logger.bind(tag=TAG).info(f"收到初始化响应: {result}")
# 检查初始化响应
if "code" in result and result["code"] != 1000:
error_msg = f"ASR服务初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}"
logger.bind(tag=TAG).error(error_msg)
raise Exception(error_msg)
except Exception as e:
logger.bind(tag=TAG).error(f"发送初始化请求失败: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
raise e
# 启动接收ASR结果的异步任务
self.forward_task = asyncio.create_task(self._forward_asr_results(conn))
# 发送缓存的音频数据
if conn.asr_audio and len(conn.asr_audio) > 0:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
payload = gzip.compress(pcm_frame)
audio_request = bytearray(
self.generate_audio_default_header()
)
audio_request.extend(len(payload).to_bytes(4, "big"))
audio_request.extend(payload)
await self.asr_ws.send(audio_request)
except Exception as e:
logger.bind(tag=TAG).info(
f"发送缓存音频数据时发生错误: {e}"
)
except Exception as e:
logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
self.is_processing = False
return
# 发送当前音频数据
if self.asr_ws and self.is_processing:
try:
pcm_frame = self.decoder.decode(audio, 960)
payload = gzip.compress(pcm_frame)
audio_request = bytearray(self.generate_audio_default_header())
audio_request.extend(len(payload).to_bytes(4, "big"))
audio_request.extend(payload)
await self.asr_ws.send(audio_request)
except Exception as e:
logger.bind(tag=TAG).info(f"发送音频数据时发生错误: {e}")
async def _forward_asr_results(self, conn):
try:
while self.asr_ws and not conn.stop_event.is_set():
try:
response = await self.asr_ws.recv()
result = self.parse_response(response)
logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
if "payload_msg" in result:
payload = result["payload_msg"]
# 检查是否是错误码1013(无有效语音)
if "code" in payload and payload["code"] == 1013:
# 静默处理,不记录错误日志
continue
if "result" in payload:
utterances = payload["result"].get("utterances", [])
# 检查duration和空文本的情况
if (
payload.get("audio_info", {}).get("duration", 0) > 2000
and not utterances
and not payload["result"].get("text")
):
logger.bind(tag=TAG).error(f"识别文本:空")
self.text = ""
conn.reset_vad_states()
await self.handle_voice_stop(conn, None)
break
for utterance in utterances:
if utterance.get("definite", False):
self.text = utterance["text"]
logger.bind(tag=TAG).info(
f"识别到文本: {self.text}"
)
conn.reset_vad_states()
await self.handle_voice_stop(conn, None)
break
elif "error" in payload:
error_msg = payload.get("error", "未知错误")
logger.bind(tag=TAG).error(f"ASR服务返回错误: {error_msg}")
break
except websockets.ConnectionClosed:
logger.bind(tag=TAG).info("ASR服务连接已关闭")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
finally:
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
self.is_processing = False
def stop_ws_connection(self):
if self.asr_ws:
asyncio.create_task(self.asr_ws.close())
self.asr_ws = None
self.is_processing = False
def construct_request(self, reqid):
req = {
"app": { "app": {
"appid": self.appid, "appid": f"{self.appid}",
"cluster": self.cluster, "cluster": self.cluster,
"token": self.access_token, "token": self.access_token,
}, },
"user": {"uid": self.uid}, "user": {
"uid": str(uuid.uuid4()),
},
"request": { "request": {
"reqid": reqid, "reqid": reqid,
"workflow": self.workflow, "show_utterances": False,
"show_utterances": True,
"result_type": self.result_type,
"sequence": 1, "sequence": 1,
"boosting_table_name": self.boosting_table_name, "boosting_table_name": self.boosting_table_name,
"correct_table_name": self.correct_table_name, "correct_table_name": self.correct_table_name,
"end_window_size": 200,
}, },
"audio": { "audio": {
"format": self.format, "format": "raw",
"codec": self.codec, "rate": 16000,
"rate": self.rate, "language": "zh-CN",
"language": self.language, "bits": 16,
"bits": self.bits, "channel": 1,
"channel": self.channel, "codec": "raw",
"sample_rate": self.rate,
}, },
} }
logger.bind(tag=TAG).debug(
f"构造请求参数: {json.dumps(req, ensure_ascii=False)}"
)
return req
def token_auth(self): async def _send_request(
return { self, audio_data: List[bytes], segment_size: int
"X-Api-App-Key": self.appid, ) -> Optional[str]:
"X-Api-Access-Key": self.access_token, """Send request to Volcano ASR service."""
"X-Api-Resource-Id": "volc.bigasr.sauc.duration",
"X-Api-Connect-Id": str(uuid.uuid4()),
}
def generate_header(
self,
version=0x01,
message_type=0x01,
message_type_specific_flags=0x00,
serial_method=0x01,
compression_type=0x01,
reserved_data=0x00,
extension_header: bytes = b"",
):
header = bytearray()
header_size = int(len(extension_header) / 4) + 1
header.append((version << 4) | header_size)
header.append((message_type << 4) | message_type_specific_flags)
header.append((serial_method << 4) | compression_type)
header.append(reserved_data)
header.extend(extension_header)
return header
def generate_audio_default_header(self):
return self.generate_header(
version=0x01,
message_type=0x02,
message_type_specific_flags=0x00,
serial_method=0x01,
compression_type=0x01,
)
def generate_last_audio_default_header(self):
return self.generate_header(
version=0x01,
message_type=0x02,
message_type_specific_flags=0x02,
serial_method=0x01,
compression_type=0x01,
)
def parse_response(self, res: bytes) -> dict:
try: try:
# 检查响应长度 auth_header = {
if len(res) < 4: "Authorization": "Bearer; {}".format(self.access_token)}
logger.bind(tag=TAG).error(f"响应数据长度不足: {len(res)}") async with websockets.connect(
return {"error": "响应数据长度不足"} self.ws_url, additional_headers=auth_header
) as websocket:
# Prepare request data
request_params = self._construct_request(str(uuid.uuid4()))
payload_bytes = str.encode(json.dumps(request_params))
payload_bytes = gzip.compress(payload_bytes)
# 获取消息头 full_client_request = self._generate_header()
header = res[:4] full_client_request.extend(
message_type = header[1] >> 4 (len(payload_bytes)).to_bytes(4, "big")
) # payload size(4 bytes)
full_client_request.extend(payload_bytes) # payload
# 如果是错误响应 # Send header and metadata
if message_type == 0x0F: # SERVER_ERROR_RESPONSE # full_client_request
code = int.from_bytes(res[4:8], "big", signed=False) await websocket.send(full_client_request)
msg_length = int.from_bytes(res[8:12], "big", signed=False) res = await websocket.recv()
error_msg = json.loads(res[12:].decode("utf-8")) result = parse_response(res)
return {
"code": code,
"msg_length": msg_length,
"payload_msg": error_msg,
}
# 获取JSON数据(跳过12字节头部) if (
try: "payload_msg" in result
json_data = res[12:].decode("utf-8") and result["payload_msg"]["code"] != self.success_code
result = json.loads(json_data) # Ignore no valid voice error
logger.bind(tag=TAG).debug(f"成功解析JSON响应: {result}") and result["payload_msg"]["code"] != 1013
return {"payload_msg": result} ):
except (UnicodeDecodeError, json.JSONDecodeError) as e: logger.bind(tag=TAG).error(f"ASR error: {result}")
logger.bind(tag=TAG).error(f"JSON解析失败: {str(e)}") return None
logger.bind(tag=TAG).error(f"原始数据: {res}")
raise for seq, (chunk, last) in enumerate(
self.slice_data(audio_data, segment_size), 1
):
if last:
audio_only_request = self._generate_header(
message_type=CLIENT_AUDIO_ONLY_REQUEST,
message_type_specific_flags=NEG_SEQUENCE,
)
else:
audio_only_request = self._generate_header(
message_type=CLIENT_AUDIO_ONLY_REQUEST
)
payload_bytes = gzip.compress(chunk)
audio_only_request.extend(
(len(payload_bytes)).to_bytes(4, "big")
) # payload size(4 bytes)
audio_only_request.extend(payload_bytes) # payload
# Send audio data
await websocket.send(audio_only_request)
# Receive response
response = await websocket.recv()
result = parse_response(response)
if (
"payload_msg" in result
and result["payload_msg"]["code"] == self.success_code
):
if len(result["payload_msg"]["result"]) > 0:
return result["payload_msg"]["result"][0]["text"]
return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
# No valid voice, return empty string
return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"解析响应失败: {str(e)}") logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(f"原始响应数据: {res.hex()}") f"ASR request failed: {e}", exc_info=True)
raise return None
async def speech_to_text(self, opus_data, session_id, audio_format): @staticmethod
result = self.text def slice_data(data: bytes, chunk_size: int) -> (list, bool):
self.text = "" # 清空text """
return result, None slice data
:param data: wav data
:param chunk_size: the segment size in one request
:return: segment data, last flag
"""
data_len = len(data)
offset = 0
while offset + chunk_size < data_len:
yield data[offset: offset + chunk_size], False
offset += chunk_size
else:
yield data[offset:data_len], True
async def close(self): async def speech_to_text(
"""资源清理方法""" self, opus_data: List[bytes], session_id: str, audio_format="opus"
if self.asr_ws: ) -> Tuple[Optional[str], Optional[str]]:
await self.asr_ws.close() """Convert speech data to text"""
self.asr_ws = None file_path = None
if self.forward_task: try:
self.forward_task.cancel() # Merge all opus data packets
try: if audio_format == "pcm":
await self.forward_task pcm_data = opus_data
except asyncio.CancelledError: else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# Determine whether to save as WAV file
if self.delete_audio_file:
pass pass
self.forward_task = None else:
self.is_processing = False file_path = self.save_audio_to_file(pcm_data, session_id)
# Use PCM data directly
# Calculate segment size (mono, 16bit, 16kHz sample rate)
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
segment_size = int(size_per_sec * self.seg_duration / 1000)
# Speech recognition
start_time = time.time()
text = await self._send_request(combined_pcm_data, segment_size)
if text:
logger.bind(tag=TAG).debug(
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
return "", file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path

View file

@ -3,7 +3,7 @@ from typing import Union, Optional
class InterfaceType(Enum): class InterfaceType(Enum):
# 接口类型 # Interface type
STREAM = "STREAM" # 流式接口 STREAM = "STREAM" # Streaming interface
NON_STREAM = "NON_STREAM" # 非流式接口 NON_STREAM = "NON_STREAM" # Non-streaming interface
LOCAL = "LOCAL" # 本地服务 LOCAL = "LOCAL" # Local service

View file

@ -15,10 +15,11 @@ TAG = __name__
logger = setup_logging() logger = setup_logging()
MAX_RETRIES = 2 MAX_RETRIES = 2
RETRY_DELAY = 1 # 重试延迟(秒) RETRY_DELAY = 1 # Retry delay (seconds)
# Capture standard output
# 捕获标准输出
class CaptureOutput: class CaptureOutput:
def __enter__(self): def __enter__(self):
self._output = io.StringIO() self._output = io.StringIO()
@ -30,7 +31,7 @@ class CaptureOutput:
self.output = self._output.getvalue() self.output = self._output.getvalue()
self._output.close() self._output.close()
# 将捕获到的内容通过 logger 输出 # Output captured content through logger
if self.output: if self.output:
logger.bind(tag=TAG).info(self.output.strip()) logger.bind(tag=TAG).info(self.output.strip())
@ -39,58 +40,60 @@ class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool): def __init__(self, config: dict, delete_audio_file: bool):
super().__init__() super().__init__()
# 内存检测,要求大于2G # Memory detection, require more than 2G
min_mem_bytes = 2 * 1024 * 1024 * 1024 min_mem_bytes = 2 * 1024 * 1024 * 1024
total_mem = psutil.virtual_memory().total total_mem = psutil.virtual_memory().total
if total_mem < min_mem_bytes: if total_mem < min_mem_bytes:
logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR") logger.bind(tag=TAG).error(
f"Insufficient memory (less than 2G), currently only {total_mem / (1024*1024):.2f} MB available, may not be able to start FunASR")
self.interface_type = InterfaceType.LOCAL self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir") self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir") # 修正配置键名 # Correct configuration key name
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
# 确保输出目录存在 # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True) os.makedirs(self.output_dir, exist_ok=True)
with CaptureOutput(): with CaptureOutput():
self.model = AutoModel( self.model = AutoModel(
model=self.model_dir, model=self.model_dir,
vad_kwargs={"max_single_segment_time": 30000}, vad_kwargs={"max_single_segment_time": 30000},
disable_update=True, disable_update=True,
hub="hf", hub="hf",
# device="cuda:0", # 启用GPU加速 # device="cuda:0", # Enable GPU acceleration
) )
async def speech_to_text( async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus" self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
"""语音转文本主处理逻辑""" """Speech to text main processing logic"""
file_path = None file_path = None
retry_count = 0 retry_count = 0
while retry_count < MAX_RETRIES: while retry_count < MAX_RETRIES:
try: try:
# 合并所有opus数据包 # Merge all opus data packets
if audio_format == "pcm": if audio_format == "pcm":
pcm_data = opus_data pcm_data = opus_data
else: else:
pcm_data = self.decode_opus(opus_data) pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data) combined_pcm_data = b"".join(pcm_data)
# 检查磁盘空间 # Check disk space
if not self.delete_audio_file: if not self.delete_audio_file:
free_space = shutil.disk_usage(self.output_dir).free free_space = shutil.disk_usage(self.output_dir).free
if free_space < len(combined_pcm_data) * 2: # 预留2倍空间 if free_space < len(combined_pcm_data) * 2: # Reserve 2x space
raise OSError("磁盘空间不足") raise OSError("Insufficient disk space")
# 判断是否保存为WAV文件 # Determine whether to save as WAV file
if self.delete_audio_file: if self.delete_audio_file:
pass pass
else: else:
file_path = self.save_audio_to_file(pcm_data, session_id) file_path = self.save_audio_to_file(pcm_data, session_id)
# 语音识别 # Speech recognition
start_time = time.time() start_time = time.time()
result = self.model.generate( result = self.model.generate(
input=combined_pcm_data, input=combined_pcm_data,
@ -99,9 +102,11 @@ class ASRProvider(ASRProviderBase):
use_itn=True, use_itn=True,
batch_size_s=60, batch_size_s=60,
) )
text = rich_transcription_postprocess(result[0]["text"]) text = rich_transcription_postprocess(result[0]["text"])
logger.bind(tag=TAG).debug( logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
) )
return text, file_path return text, file_path
@ -110,25 +115,28 @@ class ASRProvider(ASRProviderBase):
retry_count += 1 retry_count += 1
if retry_count >= MAX_RETRIES: if retry_count >= MAX_RETRIES:
logger.bind(tag=TAG).error( logger.bind(tag=TAG).error(
f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True f"Speech recognition failed (retried {retry_count} times): {e}", exc_info=True
) )
return "", file_path return "", file_path
logger.bind(tag=TAG).warning( logger.bind(tag=TAG).warning(
f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}" f"Speech recognition failed, retrying ({retry_count}/{MAX_RETRIES}): {e}"
) )
time.sleep(RETRY_DELAY) time.sleep(RETRY_DELAY)
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path return "", file_path
finally: finally:
# 文件清理逻辑 # File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path): if self.delete_audio_file and file_path and os.path.exists(file_path):
try: try:
os.remove(file_path) os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") logger.bind(tag=TAG).debug(
f"Deleted temporary audio file: {file_path}")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error( logger.bind(tag=TAG).error(
f"文件删除失败: {file_path} | 错误: {e}" f"File deletion failed: {file_path} | Error: {e}"
) )

View file

@ -11,11 +11,11 @@ import re
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class ASRProvider(ASRProviderBase): class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool): def __init__(self, config: dict, delete_audio_file: bool):
""" """
Initialize the ASRProvider with server configuration. Initialize the ASRProvider with server configuration.
:param config: Dictionary containing 'host', 'port', and 'is_ssl'. :param config: Dictionary containing 'host', 'port', and 'is_ssl'.
:param delete_audio_file: Boolean to indicate whether to delete audio files after processing. :param delete_audio_file: Boolean to indicate whether to delete audio files after processing.
""" """
@ -36,6 +36,7 @@ class ASRProvider(ASRProviderBase):
if self.is_ssl if self.is_ssl
else f"ws://{self.host}:{self.port}" else f"ws://{self.host}:{self.port}"
) )
self.ssl_context = ssl.SSLContext() if self.is_ssl else None self.ssl_context = ssl.SSLContext() if self.is_ssl else None
if self.ssl_context: if self.ssl_context:
self.ssl_context.check_hostname = False self.ssl_context.check_hostname = False
@ -52,11 +53,13 @@ class ASRProvider(ASRProviderBase):
response = await asyncio.wait_for(ws.recv(), timeout=5) response = await asyncio.wait_for(ws.recv(), timeout=5)
response_data = json.loads(response) response_data = json.loads(response)
logger.bind(tag=TAG).debug(f"Received response: {response_data}") logger.bind(tag=TAG).debug(f"Received response: {response_data}")
if response_data.get("is_final", True): if response_data.get("is_final", True):
text += response_data.get("text", "") text += response_data.get("text", "")
break break
else: else:
text += response_data.get("text", "") text += response_data.get("text", "")
except asyncio.TimeoutError: except asyncio.TimeoutError:
logger.bind(tag=TAG).error( logger.bind(tag=TAG).error(
"Timeout while waiting for response from WebSocket." "Timeout while waiting for response from WebSocket."
@ -65,28 +68,27 @@ class ASRProvider(ASRProviderBase):
except websockets.exceptions.ConnectionClosed as e: except websockets.exceptions.ConnectionClosed as e:
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}") logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
break break
return text return text
async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple: async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple:
""" """
Internal method to handle WebSocket communication. Internal method to handle WebSocket communication.
Reuses the persistent WebSocket connection if available. Reuses the persistent WebSocket connection if available.
:param pcm_data: PCM audio data to send. :param pcm_data: PCM audio data to send.
:param session_id: Unique session identifier. :param session_id: Unique session identifier.
:return: Tuple containing recognized text and optional timestamp. :return: Tuple containing recognized text and optional timestamp.
""" """
# Send initial configuration message # Send initial configuration message
config_message = json.dumps( config_message = json.dumps({
{ "mode": "offline",
"mode": "offline", "chunk_size": [5, 10, 5],
"chunk_size": [5, 10, 5], "chunk_interval": 10,
"chunk_interval": 10, "wav_name": session_id,
"wav_name": session_id, "is_speaking": True,
"is_speaking": True, "itn": False,
"itn": False, })
}
)
await ws.send(config_message) await ws.send(config_message)
logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}") logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}")
@ -104,6 +106,7 @@ class ASRProvider(ASRProviderBase):
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
""" """
Convert speech data to text using FunASR. Convert speech data to text using FunASR.
:param opus_data: List of Opus-encoded audio data chunks. :param opus_data: List of Opus-encoded audio data chunks.
:param session_id: Unique session identifier. :param session_id: Unique session identifier.
:return: Tuple containing recognized text and optional timestamp. :return: Tuple containing recognized text and optional timestamp.
@ -115,11 +118,12 @@ class ASRProvider(ASRProviderBase):
pcm_data = self.decode_opus(opus_data) pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data) combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件 # Determine whether to save as WAV file
if self.delete_audio_file: if self.delete_audio_file:
pass pass
else: else:
file_path = self.save_audio_to_file(pcm_data, session_id) file_path = self.save_audio_to_file(pcm_data, session_id)
auth_header = {"Authorization": "Bearer; {}".format(self.api_key)} auth_header = {"Authorization": "Bearer; {}".format(self.api_key)}
async with websockets.connect( async with websockets.connect(
self.uri, self.uri,
@ -151,9 +155,11 @@ class ASRProvider(ASRProviderBase):
# Get the result from the receive task # Get the result from the receive task
result = receive_task.result() result = receive_task.result()
match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result) match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result)
if match: if match:
result = match.group(4).strip() result = match.group(4).strip()
return ( return (
result, result,
file_path, file_path,

View file

@ -57,7 +57,6 @@ class ASRProvider(ASRProviderBase):
self, opus_data: List[bytes], session_id: str, audio_format="opus" self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text using Groq Whisper API""" """Convert speech data to text using Groq Whisper API"""
start_time = time.time() start_time = time.time()
try: try:
@ -115,7 +114,8 @@ class ASRProvider(ASRProviderBase):
if self.delete_audio_file and os.path.exists(audio_file_path): if self.delete_audio_file and os.path.exists(audio_file_path):
try: try:
os.remove(audio_file_path) os.remove(audio_file_path)
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}") logger.bind(tag=TAG).debug(
f"Deleted audio file: {audio_file_path}")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).warning( logger.bind(tag=TAG).warning(
f"Failed to delete audio file {audio_file_path}: {e}" f"Failed to delete audio file {audio_file_path}: {e}"

View file

@ -10,6 +10,7 @@ import requests
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class ASRProvider(ASRProviderBase): class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool): def __init__(self, config: dict, delete_audio_file: bool):
self.interface_type = InterfaceType.NON_STREAM self.interface_type = InterfaceType.NON_STREAM
@ -32,7 +33,7 @@ class ASRProvider(ASRProviderBase):
file_path = self.save_audio_to_file(pcm_data, session_id) file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug( logger.bind(tag=TAG).debug(
f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}" f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}"
) )
logger.bind(tag=TAG).info(f"file path: {file_path}") logger.bind(tag=TAG).info(f"file path: {file_path}")
@ -40,13 +41,13 @@ class ASRProvider(ASRProviderBase):
"Authorization": f"Bearer {self.api_key}", "Authorization": f"Bearer {self.api_key}",
} }
# 使用data参数传递模型名称 # Use data parameter to pass model name
data = { data = {
"model": self.model "model": self.model
} }
# Use with statement to ensure file is closed
with open(file_path, "rb") as audio_file: # 使用with语句确保文件关闭 with open(file_path, "rb") as audio_file:
files = { files = {
"file": audio_file "file": audio_file
} }
@ -59,24 +60,26 @@ class ASRProvider(ASRProviderBase):
headers=headers headers=headers
) )
logger.bind(tag=TAG).debug( logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {response.text}" f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {response.text}"
) )
if response.status_code == 200: if response.status_code == 200:
text = response.json().get("text", "") text = response.json().get("text", "")
return text, file_path return text, file_path
else: else:
raise Exception(f"API请求失败: {response.status_code} - {response.text}") raise Exception(
f"API request failed: {response.status_code} - {response.text}")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}") logger.bind(tag=TAG).error(f"Speech recognition failed: {e}")
return "", None return "", None
finally: finally:
# 文件清理逻辑 # File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path): if self.delete_audio_file and file_path and os.path.exists(file_path):
try: try:
os.remove(file_path) os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") logger.bind(tag=TAG).debug(
f"Deleted temporary audio file: {file_path}")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") logger.bind(tag=TAG).error(
f"File deletion failed: {file_path} | Error: {e}")

Some files were not shown because too many files have changed in this diff Show more