mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
added connected device section
This commit is contained in:
parent
8ff30a0215
commit
4cfe44be01
4 changed files with 673 additions and 0 deletions
441
DEVICE_CONNECTIVITY_GUIDE.md
Normal file
441
DEVICE_CONNECTIVITY_GUIDE.md
Normal file
|
|
@ -0,0 +1,441 @@
|
||||||
|
# Xiaozhi ESP32 Device Connectivity Guide
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Device Activation Process](#device-activation-process)
|
||||||
|
- [MQTT Communication](#mqtt-communication)
|
||||||
|
- [UDP Communication](#udp-communication)
|
||||||
|
- [WebSocket Communication](#websocket-communication)
|
||||||
|
- [Network Architecture](#network-architecture)
|
||||||
|
- [Troubleshooting](#troubleshooting)
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The Xiaozhi ESP32 Server supports multiple communication protocols for device connectivity:
|
||||||
|
- **HTTP/HTTPS**: For OTA updates and initial device registration
|
||||||
|
- **MQTT**: For real-time bidirectional communication
|
||||||
|
- **UDP**: For low-latency audio streaming
|
||||||
|
- **WebSocket**: For persistent real-time connections
|
||||||
|
|
||||||
|
## Device Activation Process
|
||||||
|
|
||||||
|
### 1. Initial Connection Flow
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant ESP32 as ESP32 Device
|
||||||
|
participant OTA as OTA Endpoint (8002)
|
||||||
|
participant Redis as Redis Cache
|
||||||
|
participant Web as Web Dashboard
|
||||||
|
participant User as User
|
||||||
|
|
||||||
|
ESP32->>OTA: POST /xiaozhi/ota
|
||||||
|
Note over ESP32,OTA: Headers: device-id (MAC address)
|
||||||
|
Note over ESP32,OTA: Body: firmware info, board type
|
||||||
|
|
||||||
|
OTA->>Redis: Check if device registered
|
||||||
|
alt Device Not Registered
|
||||||
|
OTA->>Redis: Generate 6-digit code
|
||||||
|
Redis-->>OTA: Store activation code
|
||||||
|
OTA-->>ESP32: Return activation code + MQTT credentials
|
||||||
|
ESP32->>ESP32: Display code on screen/log
|
||||||
|
User->>Web: Enter activation code
|
||||||
|
Web->>Redis: Validate code
|
||||||
|
Web->>Web: Register device to user
|
||||||
|
else Device Registered
|
||||||
|
OTA-->>ESP32: Return MQTT credentials + config
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Activation Code Generation
|
||||||
|
|
||||||
|
**Location**: `DeviceServiceImpl.java:buildActivation()`
|
||||||
|
|
||||||
|
The activation process works as follows:
|
||||||
|
|
||||||
|
1. **Device Makes OTA Request**:
|
||||||
|
```http
|
||||||
|
POST http://192.168.1.105:8002/xiaozhi/ota
|
||||||
|
Headers:
|
||||||
|
device-id: AA:BB:CC:DD:EE:FF
|
||||||
|
Body:
|
||||||
|
{
|
||||||
|
"application": {"version": "1.0.0"},
|
||||||
|
"board": {"type": "esp32s3"},
|
||||||
|
"chip_model_name": "ESP32-S3"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Server Generates Activation Code**:
|
||||||
|
```java
|
||||||
|
// 6-digit random code
|
||||||
|
String newCode = RandomUtil.randomNumbers(6);
|
||||||
|
|
||||||
|
// Store in Redis with two keys:
|
||||||
|
// 1. Device data key
|
||||||
|
String dataKey = "ota:device:" + deviceId;
|
||||||
|
redisUtils.set(dataKey, deviceData);
|
||||||
|
|
||||||
|
// 2. Code lookup key (for validation)
|
||||||
|
String codeKey = "ota:activation:code:" + newCode;
|
||||||
|
redisUtils.set(codeKey, deviceId);
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Response to Device**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"activation": {
|
||||||
|
"code": "141966",
|
||||||
|
"message": "http://dashboard.url\n141966",
|
||||||
|
"challenge": "AA:BB:CC:DD:EE:FF"
|
||||||
|
},
|
||||||
|
"mqtt": {
|
||||||
|
"endpoint": "192.168.1.105:1883",
|
||||||
|
"client_id": "GID_test@@@AA_BB_CC_DD_EE_FF@@@uuid",
|
||||||
|
"username": "base64_encoded_user_data",
|
||||||
|
"password": "hmac_sha256_signature",
|
||||||
|
"publish_topic": "device-server",
|
||||||
|
"subscribe_topic": "null"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **User Activation**:
|
||||||
|
- User sees code on device display/logs
|
||||||
|
- Opens web dashboard
|
||||||
|
- Enters 6-digit code
|
||||||
|
- Device is bound to user account
|
||||||
|
|
||||||
|
## MQTT Communication
|
||||||
|
|
||||||
|
### MQTT Configuration
|
||||||
|
|
||||||
|
**Default Settings**:
|
||||||
|
- **Broker**: 192.168.1.105 (configurable)
|
||||||
|
- **Port**: 1883
|
||||||
|
- **Protocol**: MQTT 3.1.1
|
||||||
|
|
||||||
|
### MQTT Credential Generation
|
||||||
|
|
||||||
|
**Location**: `DeviceServiceImpl.java:buildMqttCredentials()`
|
||||||
|
|
||||||
|
The MQTT authentication uses a secure HMAC-SHA256 signature:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// Client ID Format
|
||||||
|
String clientId = "GID_test@@@{mac_address}@@@{uuid}";
|
||||||
|
// Example: GID_test@@@AA_BB_CC_DD_EE_FF@@@550e8400-e29b-41d4-a716-446655440000
|
||||||
|
|
||||||
|
// Username (Base64 encoded JSON)
|
||||||
|
String userData = {"ip": "client_ip_address"};
|
||||||
|
String username = Base64.encode(userData);
|
||||||
|
|
||||||
|
// Password (HMAC-SHA256 signature)
|
||||||
|
String content = clientId + "|" + username;
|
||||||
|
String password = Base64.encode(
|
||||||
|
HMAC_SHA256(content, signature_key)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### MQTT Topics
|
||||||
|
|
||||||
|
- **Device to Server**: `device-server`
|
||||||
|
- **Server to Device**: Device subscribes to personalized topics
|
||||||
|
- **Message Format**: JSON payloads
|
||||||
|
|
||||||
|
### MQTT Message Flow
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph LR
|
||||||
|
A[ESP32 Device] -->|Publish| B[device-server topic]
|
||||||
|
B --> C[MQTT Broker]
|
||||||
|
C --> D[Xiaozhi Server]
|
||||||
|
D -->|Process & Respond| E[Device-specific topic]
|
||||||
|
E --> C
|
||||||
|
C -->|Subscribe| A
|
||||||
|
```
|
||||||
|
|
||||||
|
## UDP Communication
|
||||||
|
|
||||||
|
### UDP Audio Streaming
|
||||||
|
|
||||||
|
**Configuration**:
|
||||||
|
- **Port**: 8884
|
||||||
|
- **Purpose**: Real-time audio streaming
|
||||||
|
- **Protocol**: Custom binary protocol
|
||||||
|
|
||||||
|
### UDP Packet Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
+------------------+------------------+------------------+
|
||||||
|
| Device ID (6B) | Sequence (4B) | Audio Data (nB) |
|
||||||
|
+------------------+------------------+------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
### Audio Parameters
|
||||||
|
```yaml
|
||||||
|
audio_params:
|
||||||
|
format: opus # Audio codec
|
||||||
|
sample_rate: 16000 # Hz
|
||||||
|
channels: 1 # Mono
|
||||||
|
frame_duration: 60 # ms
|
||||||
|
```
|
||||||
|
|
||||||
|
### UDP Flow for Audio
|
||||||
|
|
||||||
|
1. **Device captures audio** from microphone
|
||||||
|
2. **Encodes with Opus** codec
|
||||||
|
3. **Sends UDP packets** to server:8884
|
||||||
|
4. **Server processes** audio (ASR/Speech recognition)
|
||||||
|
5. **Response sent** via MQTT or WebSocket
|
||||||
|
|
||||||
|
## WebSocket Communication
|
||||||
|
|
||||||
|
### WebSocket Endpoint
|
||||||
|
|
||||||
|
**URL Format**: `ws://{server_ip}:{port}/xiaozhi/v1/`
|
||||||
|
|
||||||
|
### Connection Flow
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Client connection example
|
||||||
|
const ws = new WebSocket('ws://192.168.1.105:8000/xiaozhi/v1/');
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
// Send authentication
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
type: 'auth',
|
||||||
|
device_id: 'AA:BB:CC:DD:EE:FF',
|
||||||
|
token: 'device_token'
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
// Handle server messages
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Network Architecture
|
||||||
|
|
||||||
|
### Complete System Architecture
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TB
|
||||||
|
subgraph "ESP32 Devices"
|
||||||
|
D1[Device 1]
|
||||||
|
D2[Device 2]
|
||||||
|
D3[Device N]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "Communication Layer"
|
||||||
|
HTTP[HTTP/8002<br/>OTA & Activation]
|
||||||
|
WS[WebSocket/8000<br/>Real-time Control]
|
||||||
|
MQTT[MQTT/1883<br/>Commands & Status]
|
||||||
|
UDP[UDP/8884<br/>Audio Stream]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "Backend Services"
|
||||||
|
JAVA[Manager API<br/>Port 8002]
|
||||||
|
PY[Xiaozhi Server<br/>Port 8000/8003]
|
||||||
|
REDIS[Redis Cache<br/>Activation Codes]
|
||||||
|
DB[(PostgreSQL<br/>Device Registry)]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph "Frontend"
|
||||||
|
WEB[Web Dashboard<br/>Device Management]
|
||||||
|
MOBILE[Mobile App<br/>Device Control]
|
||||||
|
end
|
||||||
|
|
||||||
|
D1 & D2 & D3 -.->|Initial Setup| HTTP
|
||||||
|
D1 & D2 & D3 -->|Status Updates| MQTT
|
||||||
|
D1 & D2 & D3 -->|Audio Stream| UDP
|
||||||
|
D1 & D2 & D3 <-->|Control| WS
|
||||||
|
|
||||||
|
HTTP --> JAVA
|
||||||
|
WS --> PY
|
||||||
|
MQTT --> PY
|
||||||
|
UDP --> PY
|
||||||
|
|
||||||
|
JAVA <--> REDIS
|
||||||
|
JAVA <--> DB
|
||||||
|
PY <--> REDIS
|
||||||
|
PY <--> DB
|
||||||
|
|
||||||
|
WEB --> JAVA
|
||||||
|
MOBILE --> JAVA
|
||||||
|
```
|
||||||
|
|
||||||
|
### Port Summary
|
||||||
|
|
||||||
|
| Service | Port | Protocol | Purpose |
|
||||||
|
|---------|------|----------|---------|
|
||||||
|
| Manager API | 8002 | HTTP | Device OTA, Activation |
|
||||||
|
| Xiaozhi Server WS | 8000 | WebSocket | Real-time communication |
|
||||||
|
| Xiaozhi Server HTTP | 8003 | HTTP | API endpoints, MCP |
|
||||||
|
| MQTT Broker | 1883 | MQTT | Message broker |
|
||||||
|
| UDP Audio | 8884 | UDP | Audio streaming |
|
||||||
|
| Web Dashboard | 3000 | HTTP | User interface |
|
||||||
|
|
||||||
|
## Configuration Files
|
||||||
|
|
||||||
|
### 1. Server Configuration (`config.yaml`)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
server:
|
||||||
|
ip: 0.0.0.0
|
||||||
|
port: 8000 # WebSocket port
|
||||||
|
http_port: 8003 # HTTP API port
|
||||||
|
mqtt_gateway:
|
||||||
|
enabled: true
|
||||||
|
broker: 192.168.1.105
|
||||||
|
port: 1883
|
||||||
|
udp_port: 8884
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Manager API Configuration
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
manager-api:
|
||||||
|
url: http://192.168.1.105:8002/xiaozhi
|
||||||
|
secret: your-secret-key
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Common Issues and Solutions
|
||||||
|
|
||||||
|
#### 1. Device Not Receiving Activation Code
|
||||||
|
|
||||||
|
**Symptom**: Device connects but no activation code generated
|
||||||
|
|
||||||
|
**Check**:
|
||||||
|
- Verify device is calling correct OTA endpoint (port 8002, not 8003)
|
||||||
|
- Check Redis is running and accessible
|
||||||
|
- Verify device-id header is present in request
|
||||||
|
|
||||||
|
**Solution**:
|
||||||
|
```bash
|
||||||
|
# Check Redis for activation codes
|
||||||
|
redis-cli
|
||||||
|
> KEYS ota:activation:code:*
|
||||||
|
> GET ota:device:AA:BB:CC:DD:EE:FF
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. MQTT Connection Failed
|
||||||
|
|
||||||
|
**Symptom**: Device cannot connect to MQTT broker
|
||||||
|
|
||||||
|
**Check**:
|
||||||
|
- MQTT broker is running on port 1883
|
||||||
|
- Firewall allows MQTT traffic
|
||||||
|
- Credentials are correctly generated
|
||||||
|
|
||||||
|
**Debug**:
|
||||||
|
```bash
|
||||||
|
# Test MQTT connection
|
||||||
|
mosquitto_sub -h 192.168.1.105 -p 1883 -t "device-server" -v
|
||||||
|
|
||||||
|
# Check MQTT logs
|
||||||
|
tail -f /var/log/mosquitto/mosquitto.log
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. UDP Audio Not Working
|
||||||
|
|
||||||
|
**Symptom**: Audio from device not received
|
||||||
|
|
||||||
|
**Check**:
|
||||||
|
- UDP port 8884 is open
|
||||||
|
- Audio format matches configuration (Opus, 16kHz, mono)
|
||||||
|
- Network allows UDP traffic
|
||||||
|
|
||||||
|
**Test**:
|
||||||
|
```python
|
||||||
|
# Simple UDP listener test
|
||||||
|
import socket
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
sock.bind(('0.0.0.0', 8884))
|
||||||
|
while True:
|
||||||
|
data, addr = sock.recvfrom(4096)
|
||||||
|
print(f"Received {len(data)} bytes from {addr}")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. WebSocket Connection Drops
|
||||||
|
|
||||||
|
**Symptom**: WebSocket disconnects frequently
|
||||||
|
|
||||||
|
**Check**:
|
||||||
|
- Keepalive/ping-pong implemented
|
||||||
|
- Proxy/load balancer timeout settings
|
||||||
|
- Network stability
|
||||||
|
|
||||||
|
**Configuration**:
|
||||||
|
```javascript
|
||||||
|
// Client-side keepalive
|
||||||
|
setInterval(() => {
|
||||||
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({type: 'ping'}));
|
||||||
|
}
|
||||||
|
}, 30000); // Every 30 seconds
|
||||||
|
```
|
||||||
|
|
||||||
|
### Debug Logs
|
||||||
|
|
||||||
|
Enable debug logging for different components:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
log:
|
||||||
|
log_level: DEBUG
|
||||||
|
module_levels:
|
||||||
|
OTA: DEBUG
|
||||||
|
MQTT: DEBUG
|
||||||
|
UDP: DEBUG
|
||||||
|
WebSocket: DEBUG
|
||||||
|
```
|
||||||
|
|
||||||
|
### Testing Tools
|
||||||
|
|
||||||
|
1. **Test OTA Endpoint**:
|
||||||
|
```bash
|
||||||
|
curl -X POST http://192.168.1.105:8002/xiaozhi/ota \
|
||||||
|
-H "device-id: AA:BB:CC:DD:EE:FF" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"application":{"version":"1.0.0"}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Test MQTT Publish**:
|
||||||
|
```bash
|
||||||
|
mosquitto_pub -h 192.168.1.105 -p 1883 \
|
||||||
|
-t "device-server" \
|
||||||
|
-m '{"device_id":"AA:BB:CC:DD:EE:FF","message":"test"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Monitor WebSocket**:
|
||||||
|
```javascript
|
||||||
|
// Browser console
|
||||||
|
const ws = new WebSocket('ws://192.168.1.105:8000/xiaozhi/v1/');
|
||||||
|
ws.onmessage = (e) => console.log('Received:', e.data);
|
||||||
|
ws.onerror = (e) => console.error('Error:', e);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security Considerations
|
||||||
|
|
||||||
|
1. **MQTT Authentication**: Uses HMAC-SHA256 signatures
|
||||||
|
2. **Activation Codes**: 6-digit codes with Redis TTL
|
||||||
|
3. **Device IDs**: MAC addresses as unique identifiers
|
||||||
|
4. **Network Security**: Consider using TLS/SSL for production
|
||||||
|
5. **API Keys**: Stored securely in environment variables
|
||||||
|
|
||||||
|
## Performance Optimization
|
||||||
|
|
||||||
|
1. **MQTT QoS**: Use QoS 0 for audio commands, QoS 1 for critical messages
|
||||||
|
2. **UDP Buffer**: Increase system UDP buffer for audio streaming
|
||||||
|
3. **WebSocket**: Implement connection pooling for multiple devices
|
||||||
|
4. **Redis**: Set appropriate TTL for activation codes (default: 5 minutes)
|
||||||
|
|
||||||
|
## Contact & Support
|
||||||
|
|
||||||
|
For issues or questions:
|
||||||
|
- GitHub Issues: [your-repo-url]
|
||||||
|
- Documentation: This guide
|
||||||
|
- Logs: Check `/tmp/xiaozhi-server.log` for detailed debugging
|
||||||
|
|
@ -23,6 +23,9 @@ public class DeviceReportRespDTO {
|
||||||
@Schema(description = "WebSocket配置")
|
@Schema(description = "WebSocket配置")
|
||||||
private Websocket websocket;
|
private Websocket websocket;
|
||||||
|
|
||||||
|
@Schema(description = "MQTT配置")
|
||||||
|
private Mqtt mqtt;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
@Setter
|
@Setter
|
||||||
public static class Firmware {
|
public static class Firmware {
|
||||||
|
|
@ -70,4 +73,26 @@ public class DeviceReportRespDTO {
|
||||||
@Schema(description = "WebSocket服务器地址")
|
@Schema(description = "WebSocket服务器地址")
|
||||||
private String url;
|
private String url;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
public static class Mqtt {
|
||||||
|
@Schema(description = "MQTT服务器端点")
|
||||||
|
private String endpoint;
|
||||||
|
|
||||||
|
@Schema(description = "MQTT客户端ID")
|
||||||
|
private String client_id;
|
||||||
|
|
||||||
|
@Schema(description = "MQTT用户名")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Schema(description = "MQTT密码")
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@Schema(description = "发布主题")
|
||||||
|
private String publish_topic;
|
||||||
|
|
||||||
|
@Schema(description = "订阅主题")
|
||||||
|
private String subscribe_topic;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,16 @@
|
||||||
package xiaozhi.modules.device.service.impl;
|
package xiaozhi.modules.device.service.impl;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.util.Base64;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.TimeZone;
|
import java.util.TimeZone;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import javax.crypto.Mac;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.aop.framework.AopContext;
|
import org.springframework.aop.framework.AopContext;
|
||||||
|
|
@ -176,6 +180,13 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
|
|
||||||
response.setWebsocket(websocket);
|
response.setWebsocket(websocket);
|
||||||
|
|
||||||
|
// Always include MQTT credentials for all devices (both registered and unregistered)
|
||||||
|
DeviceReportRespDTO.Mqtt mqttCredentials = buildMqttCredentials(macAddress);
|
||||||
|
if (mqttCredentials != null) {
|
||||||
|
response.setMqtt(mqttCredentials);
|
||||||
|
log.info("Added MQTT credentials to response for device: {}", macAddress);
|
||||||
|
}
|
||||||
|
|
||||||
if (deviceById != null) {
|
if (deviceById != null) {
|
||||||
// 如果设备存在,则异步更新上次连接时间和版本信息
|
// 如果设备存在,则异步更新上次连接时间和版本信息
|
||||||
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
|
String appVersion = deviceReport.getApplication() != null ? deviceReport.getApplication().getVersion()
|
||||||
|
|
@ -350,6 +361,88 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private DeviceReportRespDTO.Mqtt buildMqttCredentials(String deviceId) {
|
||||||
|
try {
|
||||||
|
DeviceReportRespDTO.Mqtt mqtt = new DeviceReportRespDTO.Mqtt();
|
||||||
|
|
||||||
|
// Get MQTT configuration from system parameters
|
||||||
|
String mqttBroker = sysParamsService.getValue("mqtt.broker", true);
|
||||||
|
String mqttPort = sysParamsService.getValue("mqtt.port", true);
|
||||||
|
String mqttSignatureKey = sysParamsService.getValue("mqtt.signature_key", true);
|
||||||
|
|
||||||
|
// Use defaults if not configured
|
||||||
|
if (StringUtils.isBlank(mqttBroker)) {
|
||||||
|
mqttBroker = "192.168.1.105"; // Default to local IP
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(mqttPort)) {
|
||||||
|
mqttPort = "1883";
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(mqttSignatureKey)) {
|
||||||
|
mqttSignatureKey = "test-signature-key-12345";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert MAC address format (remove colons, use underscores)
|
||||||
|
String macAddress = deviceId.replace(":", "_");
|
||||||
|
|
||||||
|
// Generate UUID for this session
|
||||||
|
String clientUuid = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
// Create client ID in format: GID_test@@@mac_address@@@uuid
|
||||||
|
String groupId = "GID_test";
|
||||||
|
String clientId = groupId + "@@@" + macAddress + "@@@" + clientUuid;
|
||||||
|
|
||||||
|
// Get client IP from request
|
||||||
|
String clientIp = "127.0.0.1";
|
||||||
|
try {
|
||||||
|
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||||
|
if (attributes != null) {
|
||||||
|
HttpServletRequest request = attributes.getRequest();
|
||||||
|
clientIp = request.getRemoteAddr();
|
||||||
|
String forwardedFor = request.getHeader("X-Forwarded-For");
|
||||||
|
if (StringUtils.isNotBlank(forwardedFor)) {
|
||||||
|
clientIp = forwardedFor.split(",")[0].trim();
|
||||||
|
} else {
|
||||||
|
String realIp = request.getHeader("X-Real-IP");
|
||||||
|
if (StringUtils.isNotBlank(realIp)) {
|
||||||
|
clientIp = realIp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to get client IP: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create user data and encode as base64 JSON
|
||||||
|
Map<String, String> userData = new HashMap<>();
|
||||||
|
userData.put("ip", clientIp);
|
||||||
|
String userDataJson = "{\"ip\":\"" + clientIp + "\"}";
|
||||||
|
String username = Base64.getEncoder().encodeToString(userDataJson.getBytes(StandardCharsets.UTF_8));
|
||||||
|
|
||||||
|
// Generate password signature using HMAC-SHA256
|
||||||
|
String content = clientId + "|" + username;
|
||||||
|
Mac mac = Mac.getInstance("HmacSHA256");
|
||||||
|
SecretKeySpec secretKeySpec = new SecretKeySpec(mqttSignatureKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
|
||||||
|
mac.init(secretKeySpec);
|
||||||
|
byte[] signature = mac.doFinal(content.getBytes(StandardCharsets.UTF_8));
|
||||||
|
String password = Base64.getEncoder().encodeToString(signature);
|
||||||
|
|
||||||
|
// Set MQTT credentials
|
||||||
|
mqtt.setEndpoint(mqttBroker + ":" + mqttPort);
|
||||||
|
mqtt.setClient_id(clientId);
|
||||||
|
mqtt.setUsername(username);
|
||||||
|
mqtt.setPassword(password);
|
||||||
|
mqtt.setPublish_topic("device-server");
|
||||||
|
mqtt.setSubscribe_topic("null");
|
||||||
|
|
||||||
|
log.info("Generated MQTT credentials for device {}: clientId={}", deviceId, clientId);
|
||||||
|
|
||||||
|
return mqtt;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to generate MQTT credentials for device {}: {}", deviceId, e.getMessage(), e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private DeviceReportRespDTO.Firmware buildFirmwareInfo(String type, String currentVersion) {
|
private DeviceReportRespDTO.Firmware buildFirmwareInfo(String type, String currentVersion) {
|
||||||
if (StringUtils.isBlank(type)) {
|
if (StringUtils.isBlank(type)) {
|
||||||
return null;
|
return null;
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,45 @@
|
||||||
<div class="main-wrapper">
|
<div class="main-wrapper">
|
||||||
<div class="content-panel">
|
<div class="content-panel">
|
||||||
<div class="content-area">
|
<div class="content-area">
|
||||||
|
<!-- Connected Devices Summary Card -->
|
||||||
|
<el-card class="device-summary-card" shadow="never" style="margin-bottom: 20px;">
|
||||||
|
<div slot="header" class="clearfix">
|
||||||
|
<span style="font-weight: bold;">Connected Devices Overview</span>
|
||||||
|
<el-button style="float: right; padding: 3px 0" type="text" @click="fetchConnectedDevices">
|
||||||
|
<i class="el-icon-refresh"></i> Refresh
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
<div class="device-stats">
|
||||||
|
<el-row :gutter="20">
|
||||||
|
<el-col :span="6">
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ connectedDevices.total || 0 }}</div>
|
||||||
|
<div class="stat-label">Total Devices</div>
|
||||||
|
</div>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="6">
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-value">{{ connectedDevices.activeToday || 0 }}</div>
|
||||||
|
<div class="stat-label">Active Today</div>
|
||||||
|
</div>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="12">
|
||||||
|
<div class="stat-item">
|
||||||
|
<div class="stat-label">Firmware Versions in Use:</div>
|
||||||
|
<div class="version-list">
|
||||||
|
<el-tag v-for="(count, version) in connectedDevices.versionDistribution"
|
||||||
|
:key="version"
|
||||||
|
size="small"
|
||||||
|
style="margin: 2px;">
|
||||||
|
{{ version }} ({{ count }} devices)
|
||||||
|
</el-tag>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
<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="Loading..." element-loading-spinner="el-icon-loading"
|
element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
|
||||||
|
|
@ -136,11 +175,17 @@ export default {
|
||||||
firmwarePath: ""
|
firmwarePath: ""
|
||||||
},
|
},
|
||||||
firmwareTypes: [],
|
firmwareTypes: [],
|
||||||
|
connectedDevices: {
|
||||||
|
total: 0,
|
||||||
|
activeToday: 0,
|
||||||
|
versionDistribution: {}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
this.fetchFirmwareList();
|
this.fetchFirmwareList();
|
||||||
this.getFirmwareTypes();
|
this.getFirmwareTypes();
|
||||||
|
this.fetchConnectedDevices();
|
||||||
},
|
},
|
||||||
|
|
||||||
computed: {
|
computed: {
|
||||||
|
|
@ -401,6 +446,36 @@ export default {
|
||||||
const firmwareType = this.firmwareTypes.find(item => item.key === type)
|
const firmwareType = this.firmwareTypes.find(item => item.key === type)
|
||||||
return firmwareType ? firmwareType.name : type
|
return firmwareType ? firmwareType.name : type
|
||||||
},
|
},
|
||||||
|
fetchConnectedDevices() {
|
||||||
|
// Fetch connected devices statistics
|
||||||
|
// This would call an API endpoint to get device statistics
|
||||||
|
// For now, we'll use the device management API to get device info
|
||||||
|
const currentAgentId = localStorage.getItem('agentId') || this.$route.query.agentId;
|
||||||
|
if (currentAgentId) {
|
||||||
|
Api.device.getAgentBindDevices(currentAgentId, ({data}) => {
|
||||||
|
if (data.code === 0 && data.data) {
|
||||||
|
const devices = data.data;
|
||||||
|
this.connectedDevices.total = devices.length;
|
||||||
|
|
||||||
|
// Count devices active today
|
||||||
|
const today = new Date();
|
||||||
|
today.setHours(0, 0, 0, 0);
|
||||||
|
this.connectedDevices.activeToday = devices.filter(device => {
|
||||||
|
const lastConnected = new Date(device.lastConnectedAt);
|
||||||
|
return lastConnected >= today;
|
||||||
|
}).length;
|
||||||
|
|
||||||
|
// Calculate version distribution
|
||||||
|
const versionMap = {};
|
||||||
|
devices.forEach(device => {
|
||||||
|
const version = device.appVersion || 'Unknown';
|
||||||
|
versionMap[version] = (versionMap[version] || 0) + 1;
|
||||||
|
});
|
||||||
|
this.connectedDevices.versionDistribution = versionMap;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
@ -481,6 +556,45 @@ export default {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.device-summary-card {
|
||||||
|
background: white;
|
||||||
|
border: none;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||||
|
|
||||||
|
::v-deep .el-card__header {
|
||||||
|
background: linear-gradient(135deg, #f5f7fa 0%, #f0f3f8 100%);
|
||||||
|
padding: 12px 20px;
|
||||||
|
border-bottom: 1px solid #e4e7ed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-stats {
|
||||||
|
padding: 10px 0;
|
||||||
|
|
||||||
|
.stat-item {
|
||||||
|
text-align: center;
|
||||||
|
padding: 10px;
|
||||||
|
|
||||||
|
.stat-value {
|
||||||
|
font-size: 28px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #409eff;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-label {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #606266;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.version-list {
|
||||||
|
margin-top: 8px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.params-card {
|
.params-card {
|
||||||
background: white;
|
background: white;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue