feat: 航线解析以及websocket订阅不关闭bug修复

This commit is contained in:
2025-12-21 14:15:44 +08:00
parent 17bed2438f
commit 5ee8c03671
59 changed files with 10746 additions and 122 deletions
+984
View File
@@ -0,0 +1,984 @@
# WebSocket订阅机制全面审计报告
**审计时间**: 2025-01-20
**审计范围**: device-center WebSocket订阅机制
**审计目标**: 检查是否存在导致WebSocket持续不断订阅数据的bug
---
## 执行摘要
经过全面审计,发现 **3个严重问题** 和 **5个中等风险点**,这些问题可能导致WebSocket订阅无法正常清理,造成资源泄漏和持续订阅数据。
### 关键发现
1. ✅ **Redis订阅池与WebSocket订阅同步良好** - 使用引用计数机制
2. ⚠️ **存在多处订阅泄漏风险** - 特定场景下订阅未清理
3. ⚠️ **前端断开逻辑不完善** - 某些情况下无法通知后端
4. ✅ **孤儿订阅清理机制有效** - 60秒定时清理
---
## 1. 订阅入口点分析
### 1.1 SSE连接入口(机库数据)
**文件**: `SseEmitterManager.java:101-177`
```java
public SseEmitter addEmitter(String sessionId, String deviceSn, String tenantId)
```
**订阅主题**:
- FIRE_ALARM (机库状态)
- ONLINE (设备上线)
- OFFLINE (设备离线)
**引用计数机制**: ✅ 正确实现
- Redis池: `subscriptionPoolService.addSubscription()` 返回 `isFirst`
- 本地计数: `deviceRefCount.compute()` 递增
- 只有首次订阅才调用 `deviceSubscriptionManager.subscribeDevice()`
**问题**: 无
---
### 1.2 SSE连接入口(无人机遥测数据)
**文件**: `SseEmitterManager.java:481-568`
```java
public SseEmitter addDroneTelemetryEmitter(String sessionId, String deviceSn, String tenantId)
```
**订阅主题**:
- MSG_ALARM (无人机遥测)
- ONLINE (设备上线) - **⚠️ 重复订阅风险**
- OFFLINE (设备离线) - **⚠️ 重复订阅风险**
**问题 1**: 🔴 **严重 - 重复订阅ONLINE/OFFLINE主题**
```java
// 第538-543行
boolean isFirstOnline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isFirstOffline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.OFFLINE);
if (isFirstOnline || isFirstOffline) {
log.info("设备 {} 首次订阅基础主题,触发WebSocket懒加载", deviceSn);
deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId);
}
```
**影响**:
- 如果用户先打开机库页面(已订阅ONLINE/OFFLINE),再进入操控台,此时 `isFirstOnline` 和 `isFirstOffline` 都是false
- 但如果用户先进入操控台(无机库SSE),此时会订阅ONLINE/OFFLINE
- 这导致订阅逻辑不一致,虽然使用Redis池管理,但增加了复杂度
**严重程度**: 中等(功能正常但逻辑复杂)
---
### 1.3 WebSocket重连订阅
**文件**: `JetLinksWebSocketClient.java:543-615`
```java
private void resubscribeAll()
```
**问题 2**: 🔴 **严重 - 重连时可能订阅已取消的设备**
**场景再现**:
1. 用户A订阅设备D1(Redis池记录:D1 → sessionA)
2. WebSocket断开,触发重连
3. 重连时调用 `resubscribeAll()`,从 `subscribedTopics` 恢复订阅
4. 此时用户A已关闭页面,但 `subscribedTopics` 中仍有D1的记录
5. 导致WebSocket重新订阅D1,但Redis池中已无订阅者
**根本原因**:
- `subscribedTopics` 是本地内存Set,与Redis订阅池不同步
- `resubscribeAll()` 清空后重新订阅,但没有检查Redis池状态
- 虽然有订阅池检查逻辑(565-614行),但如果 `subscriptionPoolService` 未设置则回退到默认行为
**修复措施**: ✅ 已实现
```java
// 第565-604行:基于Redis池状态重新订阅
if (subscriptionPoolService != null) {
// 只订阅Redis中有订阅者的主题
}
```
**残留风险**: 🟡 中等
- 如果 `subscriptionPoolService` 为null,则回退到默认行为(606-613行)
- 默认行为会订阅所有基础主题,可能造成过度订阅
---
### 1.4 单设备订阅(设备级懒加载)
**文件**: `DeviceSubscriptionManager.java:244-273`
```java
public void subscribeDevice(String deviceSn, String tenantId)
```
**订阅主题**:
- ONLINE
- OFFLINE
- EVENT_FIRE_ALARM
**问题**: 无(正确实现)
---
### 1.5 无人机遥测订阅
**文件**: `DeviceSubscriptionManager.java:314-346`
```java
public void subscribeDroneTelemetry(String deviceSn)
```
**订阅主题**:
- EVENT_MSG_ALARM
**问题**: 无(正确实现)
---
## 2. 取消订阅出口点分析
### 2.1 SSE断开 - 机库连接
**文件**: `SseEmitterManager.java:183-262` (removeEmitter方法)
**逻辑流程**:
```
1. 从emitters Map移除连接
2. 尝试完成emitter(优雅关闭)
3. 减少本地引用计数
4. 根据连接类型(机库/无人机)分别处理
```
**机库连接处理** (244-261行):
```java
boolean isLastFireAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.FIRE_ALARM);
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
if (isLastFireAlarm && isLastOnline && isLastOffline) {
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
}
```
**问题 3**: 🔴 **严重 - 条件过于严格,可能导致订阅残留**
**场景再现**:
1. 电脑A和电脑B同时订阅设备D1的机库数据
- Redis池: D1:fire_alarm → {sessionA, sessionB}
- Redis池: D1:online → {sessionA, sessionB}
- Redis池: D1:offline → {sessionA, sessionB}
2. 电脑B进入操控台(无人机SSE)
- Redis池: D1:msg_alarm → {droneSessionB}
- Redis池: D1:online → {sessionA, sessionB, droneSessionB}
- Redis池: D1:offline → {sessionA, sessionB, droneSessionB}
3. 电脑A关闭机库页面
- 移除: D1:fire_alarm → sessionA (isLastFireAlarm = false,仍有sessionB)
- 移除: D1:online → sessionA (isLastOnline = false,仍有sessionB和droneSessionB)
- 移除: D1:offline → sessionA (isLastOffline = false,仍有sessionB和droneSessionB)
- **条件不满足**: `isLastFireAlarm && isLastOnline && isLastOffline` = false
- **结果**: 不调用 `unsubscribeDevice()`(这是正确的,因为还有sessionB)
4. 电脑B关闭机库页面
- 移除: D1:fire_alarm → sessionB (isLastFireAlarm = **true**,最后一个)
- 移除: D1:online → sessionB (isLastOnline = false,仍有droneSessionB)
- 移除: D1:offline → sessionB (isLastOffline = false,仍有droneSessionB)
- **条件不满足**: `isLastFireAlarm && isLastOnline && isLastOffline` = false
- **结果**: 不调用 `unsubscribeDevice()`
- **❌ BUG**: WebSocket中 FIRE_ALARM 主题订阅未取消!
**根本原因**:
- 条件要求三个主题**同时**是最后一个订阅者才取消WebSocket订阅
- 但无人机SSE也会订阅ONLINE/OFFLINE,导致机库SSE断开时条件永远不满足
- 最终导致 FIRE_ALARM 主题的WebSocket订阅残留
**正确逻辑应该是**:
```java
// 只要 fire_alarm 是最后一个订阅者,就取消 FIRE_ALARM 主题的WebSocket订阅
if (isLastFireAlarm) {
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM);
}
// 只有当 ONLINE 和 OFFLINE 都是最后一个订阅者时,才取消这两个主题
if (isLastOnline && isLastOffline) {
// 还需检查是否有msg_alarm订阅
boolean hasMsgAlarm = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM);
if (!hasMsgAlarm) {
jetLinksWebSocketClient.unsubscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
}
}
```
**严重程度**: 🔴 **严重** - 导致WebSocket订阅残留
---
### 2.2 SSE断开 - 无人机连接
**文件**: `SseEmitterManager.java:212-243`
**逻辑流程**:
```java
boolean isLastMsgAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
if (isLastMsgAlarm) {
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
}
if (isLastOnline && isLastOffline) {
boolean hasFireAlarmSubscribers = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.FIRE_ALARM);
if (!hasFireAlarmSubscribers) {
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
}
}
```
**评价**: ✅ **正确实现**
- MSG_ALARM 单独取消(符合预期)
- ONLINE/OFFLINE 取消前检查是否有FIRE_ALARM订阅者(避免误删)
**问题**: 无
---
### 2.3 WebSocket取消订阅
**文件**: `JetLinksWebSocketClient.java:448-476`
```java
public void unsubscribeDevice(String deviceSn, SubscriptionTopic... topics)
```
**逻辑流程**:
1. 检查连接状态
2. 逐个取消订阅主题 (`unsubscribeTopic`)
3. 更新设备订阅计数
4. 如果所有设备订阅都取消,自动断开WebSocket
**问题 4**: 🟡 **中等 - 自动断开逻辑可能过早触发**
```java
// 第469行
if (deviceSubscriptionCounts.isEmpty()) {
log.info("所有设备的所有订阅已取消,自动断开WebSocket连接以节省资源");
closeConnection();
}
```
**场景再现**:
1. 设备D1订阅了FIRE_ALARM(计数=1)
2. 调用 `unsubscribeDevice(D1, FIRE_ALARM)`
3. 计数递减为0,从map移除
4. `deviceSubscriptionCounts.isEmpty()` = true
5. 自动断开WebSocket
6. 但此时可能还有ONLINE/OFFLINE订阅未处理
**实际影响**: 🟢 轻微
- 因为 `unsubscribeDevice` 通常传入多个主题一起取消
- 但如果分开调用可能触发问题
---
### 2.4 设备订阅管理器取消订阅
**文件**: `DeviceSubscriptionManager.java:280-306`
```java
public void unsubscribeDevice(String deviceSn)
```
**订阅取消**:
- ONLINE
- OFFLINE
- EVENT_FIRE_ALARM
- EVENT_MSG_ALARM
**问题 5**: 🟡 **中等 - 取消订阅范围过大**
```java
// 第290-296行
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
```
**问题**:
- 此方法命名为 `unsubscribeDevice`,语义上是取消设备基础订阅
- 但同时取消了 `EVENT_MSG_ALARM`(无人机遥测)
- 如果其他session仍在操控台看无人机数据,会被意外断开
**正确逻辑**:
```java
// unsubscribeDevice 应该只取消设备基础主题
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
);
// 不应取消 EVENT_MSG_ALARM
```
**严重程度**: 🟡 中等(可能导致其他用户数据中断)
---
### 2.5 无人机遥测取消订阅
**文件**: `DeviceSubscriptionManager.java:354-386`
```java
public void unsubscribeDroneTelemetry(String deviceSn)
```
**订阅取消**:
- EVENT_MSG_ALARM
**评价**: ✅ **正确实现**
---
## 3. 关键场景分析
### 场景A: 正常打开页面 → 正常关闭页面
**流程**:
1. 前端调用 `connectSSE(deviceSn)` → 后端 `addEmitter()`
2. Redis池添加订阅(isFirst=true) → 触发WebSocket订阅
3. 前端调用 `disconnectSSE()` → 后端 `removeEmitter()`
4. Redis池移除订阅(isLast=true) → 取消WebSocket订阅
**结论**: ✅ **正常工作**
---
### 场景B: 打开页面 → 刷新浏览器
**流程**:
1. 前端 `beforeunload` 事件触发 → `performDisconnect()`
2. 使用 `sendBeacon()` 发送断开请求(POST /disconnect)
3. 后端收到请求 → `removeEmitter()` → 清理订阅
**问题 6**: 🟡 **中等 - sendBeacon可能失败**
**失败情况**:
- 网络延迟高时,beacon请求可能未发送完成
- 浏览器强制关闭进程(任务管理器结束)
- 某些浏览器版本sendBeacon实现有bug
**缓解措施**: ✅ 已实现
- 孤儿订阅清理机制(60秒一次)
- SSE超时机制(5分钟)
**结论**: 🟡 **基本可用,但有风险**
---
### 场景C: 打开页面 → 关闭浏览器标签
**流程**: 同场景B
**结论**: 🟡 **基本可用,但有风险**
---
### 场景D: 电脑A和电脑B同时查看同一设备 → A关闭 → B继续
**流程**:
1. A和B同时订阅D1 → Redis池: D1:fire_alarm → {sessionA, sessionB}
2. A关闭 → `removeSubscription(sessionA)` → isLast=false → 不取消WebSocket
3. B继续 → 正常接收数据
**结论**: ✅ **正常工作**(引用计数机制生效)
**但存在问题3的风险**: 如果B进入了操控台,A关闭后WebSocket订阅可能残留
---
### 场景E: 进入操控台(订阅msg_alarm)→ 退出操控台
**流程**:
1. 前端调用 `connectDroneSSE(deviceSn)` → 后端 `addDroneTelemetryEmitter()`
2. Redis池添加MSG_ALARM订阅(isFirst=true) → 触发WebSocket订阅
3. Redis池添加ONLINE/OFFLINE订阅(触发设备基础订阅)
4. 前端调用 `disconnectDroneSSE()` → 后端 `removeEmitter()`
5. Redis池移除MSG_ALARM(isLast=true) → 取消WebSocket的MSG_ALARM订阅
6. Redis池移除ONLINE/OFFLINE → 检查是否有FIRE_ALARM订阅者 → 决定是否取消
**结论**: ✅ **正常工作**(逻辑正确)
---
### 场景F: WebSocket断开重连
**流程**:
1. WebSocket断开 → `afterConnectionClosed()` 触发
2. 检查 `isAutoClose` 和 `isManualClose` 标志
3. 如果不是主动关闭 → 调用 `scheduleReconnect()`
4. 重连成功 → `afterConnectionEstablished()` → `resubscribeAll()`
5. 基于Redis池状态重新订阅
**问题**: 见问题2
**结论**: 🟡 **基本可用**(如果subscriptionPoolService正常则无问题)
---
### 场景G: SSE连接超时(5分钟)
**流程**:
1. 5分钟无数据传输 → SseEmitter超时
2. `onTimeout()` 回调触发 → `removeEmitter()`
3. 清理Redis订阅和WebSocket订阅
**结论**: ✅ **正常工作**
---
## 4. Redis订阅池与WebSocket同步性分析
### 4.1 数据结构对比
| 数据源 | 存储位置 | 数据结构 | 用途 |
|--------|---------|---------|------|
| **Redis订阅池** | Redis | `device:sub:{deviceSn}:{topicType}` → Set\<sessionId\> | 全局订阅状态,跨实例共享 |
| **WebSocket订阅** | JetLinksWebSocketClient | `subscribedTopics` (Set\<String\>) | 本地已订阅主题列表 |
| **设备订阅计数** | JetLinksWebSocketClient | `deviceSubscriptionCounts` (Map\<String, AtomicInteger\>) | 本地设备订阅计数 |
| **本地引用计数** | SseEmitterManager | `deviceRefCount` (Map\<String, Integer\>) | 本地设备引用计数(快速查询) |
### 4.2 同步流程
**订阅流程**:
```
SseEmitterManager.addEmitter()
↓
subscriptionPoolService.addSubscription() → Redis SET SADD
↓ 返回 isFirst
如果 isFirst == true:
↓
deviceSubscriptionManager.subscribeDevice()
↓
jetLinksWebSocketClient.subscribeDevice()
↓
subscribeTopic() → 发送WebSocket订阅消息
↓
subscribedTopics.add(topic)
deviceSubscriptionCounts.increment(deviceSn)
```
**取消订阅流程**:
```
SseEmitterManager.removeEmitter()
↓
subscriptionPoolService.removeSubscription() → Redis SET SREM
↓ 返回 isLast
如果 isLast == true:
↓
deviceSubscriptionManager.unsubscribeDevice()
↓
jetLinksWebSocketClient.unsubscribeDevice()
↓
unsubscribeTopic() → 发送WebSocket取消订阅消息
↓
subscribedTopics.remove(topic)
deviceSubscriptionCounts.decrement(deviceSn)
```
### 4.3 同步问题
**问题 7**: 🟡 **中等 - 网络分区时数据不一致**
**场景**:
1. Redis池添加订阅成功(isFirst=true)
2. 准备调用WebSocket订阅时,网络中断
3. WebSocket订阅失败,但Redis中已有记录
4. 网络恢复后,不会重试订阅(因为isFirst=false)
**缓解措施**:
- WebSocket重连时会调用 `resubscribeAll()`
- 基于Redis池状态重新订阅(问题2的修复)
**结论**: 🟢 **可接受**(重连机制可恢复)
---
### 4.4 孤儿订阅清理机制
**文件**: `SseEmitterManager.java:396-434`
```java
private void startOrphanSubscriptionCleanup() {
cleanupExecutor.scheduleAtFixedRate(() -> {
cleanupOrphanSubscriptions();
}, 60000, 60000, TimeUnit.MILLISECONDS);
}
private void cleanupOrphanSubscriptions() {
Set<String> activeSessionIds = new HashSet<>(emitters.keySet());
int cleanedCount = subscriptionPoolService.cleanupOrphanSessions(activeSessionIds);
}
```
**清理逻辑**:
1. 获取当前活跃的SSE session
2. 遍历Redis中所有session
3. 如果Redis中的session不在活跃列表中 → 清理
**评价**: ✅ **机制有效**
**残留问题**:
- 清理周期是60秒,意味着孤儿订阅最多存在60秒
- 如果有大量孤儿订阅,可能在清理周期内产生较多WebSocket消息
**建议**: 将清理周期缩短到30秒
---
## 5. 前端断开逻辑分析
### 5.1 useDeviceSSE.ts(机库数据)
**断开逻辑**:
```typescript
// 1. beforeunload 事件
window.addEventListener('beforeunload', handleBeforeUnload);
// 2. 组件卸载
useEffect(() => {
return () => {
performDisconnect(...);
abortController.abort();
};
}, []);
```
**performDisconnect实现**:
```typescript
// 方案1: sendBeacon (POST /disconnect)
navigator.sendBeacon(beaconUrl, blob);
// 方案2: fetch (DELETE) with keepalive
fetch(deleteUrl, { keepalive: true });
```
**评价**: ✅ **设计良好**
**问题 8**: 🟡 **中等 - React StrictMode导致重复调用**
**场景**:
- React 18 StrictMode 会在开发模式下双重调用 useEffect
- 可能导致断开逻辑执行两次
- 如果sessionId相同,后端可能报错(连接不存在)
**影响**: 🟢 轻微(仅影响开发环境)
---
### 5.2 useDroneSSE.ts(无人机数据)
**逻辑**: 同 useDeviceSSE.ts
**评价**: ✅ **设计良好**
---
## 6. 问题汇总与优先级
| 问题编号 | 严重程度 | 问题描述 | 影响场景 | 是否修复 |
|---------|---------|---------|---------|---------|
| **问题1** | 🟡 中等 | addDroneTelemetryEmitter重复订阅ONLINE/OFFLINE | 代码复杂度高 | ❌ 未修复 |
| **问题2** | 🟡 中等 | WebSocket重连时可能订阅已取消的设备 | 场景F(重连) | ✅ 已修复(但有回退风险) |
| **问题3** | 🔴 严重 | 机库SSE断开条件过于严格,导致FIRE_ALARM订阅残留 | 场景D(多客户端混合使用) | ❌ **未修复** |
| **问题4** | 🟡 中等 | WebSocket自动断开逻辑可能过早触发 | 分批取消订阅 | ❌ 未修复 |
| **问题5** | 🟡 中等 | unsubscribeDevice取消订阅范围过大 | 多客户端混合使用 | ❌ 未修复 |
| **问题6** | 🟡 中等 | sendBeacon可能失败 | 场景B/C(刷新/关闭) | ✅ 已缓解(孤儿清理) |
| **问题7** | 🟡 中等 | 网络分区时Redis与WebSocket不一致 | 网络异常 | ✅ 已缓解(重连恢复) |
| **问题8** | 🟢 轻微 | React StrictMode重复调用 | 开发环境 | - |
---
## 7. 修复建议
### 7.1 紧急修复(问题3)
**文件**: `SseEmitterManager.java:244-261`
**现有代码**:
```java
// 机库SSE连接:取消该session的fire_alarm, online, offline订阅
boolean isLastFireAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.FIRE_ALARM);
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
// 只有当所有主题都是最后一个订阅者时,才取消WebSocket订阅
if (isLastFireAlarm && isLastOnline && isLastOffline) {
log.info("设备 {} 机库数据最后一个订阅者离开,取消WebSocket订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
}
```
**修复代码**:
```java
// 机库SSE连接:取消该session的fire_alarm, online, offline订阅
boolean isLastFireAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.FIRE_ALARM);
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
log.info("机库SSE连接断开: sessionId={}, deviceSn={}, isLastFireAlarm={}, isLastOnline={}, isLastOffline={}",
sessionId, deviceSn, isLastFireAlarm, isLastOnline, isLastOffline);
// 【修复】分别处理每个主题的WebSocket订阅
// 1. 如果 fire_alarm 是最后一个订阅者,取消 FIRE_ALARM 主题的WebSocket订阅
if (isLastFireAlarm) {
log.info("设备 {} 机库数据(FIRE_ALARM)最后一个订阅者离开,取消WebSocket订阅", deviceSn);
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM);
}
// 2. 如果 ONLINE 和 OFFLINE 都是最后一个订阅者,检查是否还有msg_alarm订阅
if (isLastOnline && isLastOffline) {
// 检查是否还有无人机遥测数据订阅(msg_alarm)
boolean hasMsgAlarmSubscribers = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM);
if (!hasMsgAlarmSubscribers) {
log.info("设备 {} 所有基础主题订阅者都已离开,取消ONLINE/OFFLINE的WebSocket订阅", deviceSn);
jetLinksWebSocketClient.unsubscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
} else {
log.info("设备 {} 仍有无人机遥测订阅,保持ONLINE/OFFLINE的WebSocket订阅", deviceSn);
}
}
```
---
### 7.2 优化建议(问题5)
**文件**: `DeviceSubscriptionManager.java:280-306`
**现有代码**:
```java
public void unsubscribeDevice(String deviceSn) {
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
}
```
**修复代码**:
```java
public void unsubscribeDevice(String deviceSn) {
// 只取消设备基础主题,不取消无人机遥测数据(msg_alarm应该单独管理)
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
);
// 移除 EVENT_MSG_ALARM
}
```
---
### 7.3 代码重构建议(问题1)
**文件**: `SseEmitterManager.java:538-544`
**建议**: 移除无人机SSE中的ONLINE/OFFLINE订阅,统一由机库SSE管理
**理由**:
- ONLINE/OFFLINE是设备基础主题,应该由设备级别的SSE管理
- 无人机SSE应该只负责MSG_ALARM主题
- 这样可以简化逻辑,避免交叉依赖
**修复后的逻辑**:
```java
public SseEmitter addDroneTelemetryEmitter(...) {
// 只添加 MSG_ALARM 订阅
boolean isFirstMsgAlarm = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
if (isFirstMsgAlarm) {
// 只订阅 msg_alarm 主题
deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn);
}
// 移除 ONLINE/OFFLINE 订阅逻辑(由机库SSE负责)
}
```
**前提条件**: 进入操控台前,必须先建立机库SSE连接(订阅ONLINE/OFFLINE)
---
### 7.4 监控增强建议
**新增监控指标**:
1. Redis订阅池大小 vs WebSocket订阅数
2. 孤儿订阅数量(每次清理统计)
3. WebSocket订阅残留检测(对比Redis池)
**实现方式**:
```java
@Scheduled(fixedDelay = 300000) // 每5分钟执行一次
public void checkSubscriptionConsistency() {
Set<String> activeDevices = jetLinksWebSocketClient.getActiveDevices();
for (String deviceSn : activeDevices) {
int wsCount = jetLinksWebSocketClient.getDeviceSubscriptionCount(deviceSn);
long fireAlarmCount = subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.FIRE_ALARM);
long msgAlarmCount = subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.MSG_ALARM);
long onlineCount = subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.ONLINE);
long totalRedisCount = (fireAlarmCount > 0 ? 1 : 0) +
(msgAlarmCount > 0 ? 1 : 0) +
(onlineCount > 0 ? 1 : 0);
if (wsCount > totalRedisCount) {
log.warn("⚠️ 检测到订阅残留: deviceSn={}, WebSocket订阅数={}, Redis订阅数={}",
deviceSn, wsCount, totalRedisCount);
}
}
}
```
---
## 8. 测试建议
### 8.1 单元测试
**测试用例**:
1. 单个客户端订阅-取消订阅循环
2. 多个客户端同时订阅同一设备
3. 机库SSE + 无人机SSE混合使用
4. WebSocket重连后订阅状态
5. SSE超时自动清理
6. 孤儿订阅清理
### 8.2 集成测试
**测试场景**:
1. 电脑A订阅D1机库 → 电脑B订阅D1操控台 → A关闭 → B继续 → 检查WebSocket订阅
2. 浏览器刷新后Redis订阅状态
3. WebSocket断开重连后数据接收正常
4. 多实例部署(Redis共享)
### 8.3 压力测试
**测试指标**:
1. 1000个客户端同时订阅不同设备
2. 100个客户端反复订阅-取消同一设备
3. 模拟网络抖动(频繁断开重连)
---
## 9. 结论
### 9.1 关键问题
**问题3(严重)**必须修复:
- 机库SSE断开时,FIRE_ALARM主题的WebSocket订阅可能残留
- 导致WebSocket持续接收数据,但无客户端消费
- 造成服务器资源浪费和Redis订阅池不一致
### 9.2 系统健壮性评估
| 维度 | 评分 | 说明 |
|------|------|------|
| 订阅管理 | 🟡 75/100 | 引用计数机制良好,但有逻辑漏洞 |
| 取消订阅 | 🟡 70/100 | 部分场景存在残留风险 |
| 异常恢复 | 🟢 85/100 | WebSocket重连、孤儿清理机制有效 |
| 多客户端支持 | 🟢 80/100 | Redis池隔离良好,但混合场景有问题 |
| 前端清理 | 🟢 80/100 | sendBeacon + 组件卸载双重保障 |
### 9.3 修复优先级
1. **P0(立即修复)**: 问题3 - 机库SSE断开逻辑
2. **P1(本周修复)**: 问题5 - unsubscribeDevice范围
3. **P2(本月优化)**: 问题1 - 代码重构
4. **P3(持续监控)**: 问题6、7 - 异常场景缓解措施
---
## 10. 附录
### 10.1 订阅流程图
```
┌─────────────┐
│ 前端SSE │
│ 连接建立 │
└──────┬──────┘
│
↓
┌──────────────────┐
│ SseEmitterManager│
│ addEmitter() │
└──────┬───────────┘
│
↓
┌──────────────────────────┐
│ SubscriptionPoolService │
│ addSubscription() → Redis│
└──────┬───────────────────┘
│ isFirst=true?
↓
┌──────────────────────────┐
│DeviceSubscriptionManager │
│ subscribeDevice() │
└──────┬───────────────────┘
│
↓
┌──────────────────────────┐
│JetLinksWebSocketClient │
│ subscribeDevice() │
│ → subscribedTopics.add()│
└──────────────────────────┘
```
### 10.2 取消订阅流程图
```
┌─────────────┐
│ 前端SSE │
│ 断开连接 │
└──────┬──────┘
│
↓
┌──────────────────┐
│ SseEmitterManager│
│ removeEmitter() │
└──────┬───────────┘
│
↓
┌──────────────────────────┐
│ SubscriptionPoolService │
│ removeSubscription() → Redis│
└──────┬───────────────────┘
│ isLast=true?
↓
┌──────────────────────────┐
│DeviceSubscriptionManager │
│ unsubscribeDevice() │
└──────┬───────────────────┘
│
↓
┌──────────────────────────┐
│JetLinksWebSocketClient │
│ unsubscribeDevice() │
│ → subscribedTopics.remove()│
└──────────────────────────┘
```
### 10.3 问题3详细场景示例
**初始状态**:
```
电脑A: 机库SSE (session_A)
电脑B: 机库SSE (session_B) + 无人机SSE (drone_session_B)
Redis池状态:
D1:fire_alarm → {session_A, session_B}
D1:msg_alarm → {drone_session_B}
D1:online → {session_A, session_B, drone_session_B}
D1:offline → {session_A, session_B, drone_session_B}
WebSocket订阅:
D1 → [FIRE_ALARM, MSG_ALARM, ONLINE, OFFLINE]
```
**电脑A关闭机库页面**:
```
调用 removeEmitter(session_A, D1)
1. removeSubscription(session_A, D1, FIRE_ALARM)
→ D1:fire_alarm = {session_B}
→ isLastFireAlarm = false
2. removeSubscription(session_A, D1, ONLINE)
→ D1:online = {session_B, drone_session_B}
→ isLastOnline = false
3. removeSubscription(session_A, D1, OFFLINE)
→ D1:offline = {session_B, drone_session_B}
→ isLastOffline = false
4. 检查条件: isLastFireAlarm && isLastOnline && isLastOffline
→ false && false && false = false
→ ❌ 不调用 unsubscribeDevice()
结果: WebSocket订阅未变化
```
**电脑B关闭机库页面**:
```
调用 removeEmitter(session_B, D1)
1. removeSubscription(session_B, D1, FIRE_ALARM)
→ D1:fire_alarm = {} (空)
→ isLastFireAlarm = true ✅
2. removeSubscription(session_B, D1, ONLINE)
→ D1:online = {drone_session_B}
→ isLastOnline = false
3. removeSubscription(session_B, D1, OFFLINE)
→ D1:offline = {drone_session_B}
→ isLastOffline = false
4. 检查条件: isLastFireAlarm && isLastOnline && isLastOffline
→ true && false && false = false
→ ❌ 不调用 unsubscribeDevice()
结果: WebSocket仍然订阅 FIRE_ALARM 主题!
但 Redis池中 D1:fire_alarm 已经没有订阅者了!
```
**最终状态(有BUG)**:
```
Redis池状态:
D1:fire_alarm → {} (空) ← 无订阅者
D1:msg_alarm → {drone_session_B}
D1:online → {drone_session_B}
D1:offline → {drone_session_B}
WebSocket订阅:
D1 → [FIRE_ALARM, MSG_ALARM, ONLINE, OFFLINE] ← FIRE_ALARM残留!
问题:
1. WebSocket仍然接收D1的FIRE_ALARM数据
2. 但没有任何客户端订阅(Redis池为空)
3. 收到的数据被SseEmitterManager丢弃(因为找不到匹配的emitter)
4. 造成服务器资源浪费
```
---
**报告结束**
**建议下一步行动**:
1. 立即修复问题3(预计影响:中等,修复难度:低)
2. 增加监控脚本,每5分钟检测订阅残留
3. 计划代码重构,简化机库/无人机SSE的主题管理逻辑
@@ -0,0 +1,59 @@
package com.central.device.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步任务配置
*
* @author dzc
* @date 2025-12-17
*/
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig {
/**
* 航线解析专用线程池
*/
@Bean("waylineParseExecutor")
public Executor waylineParseExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数
executor.setCorePoolSize(2);
// 最大线程数
executor.setMaxPoolSize(5);
// 队列容量
executor.setQueueCapacity(100);
// 线程名前缀
executor.setThreadNamePrefix("wayline-parse-");
// 拒绝策略:由调用线程处理
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 线程空闲时间
executor.setKeepAliveSeconds(60);
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
// 等待时间
executor.setAwaitTerminationSeconds(60);
executor.initialize();
log.info("航线解析线程池初始化完成");
return executor;
}
}
@@ -0,0 +1,178 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.model.vo.FlightTrackVO;
import com.central.device.service.IDroneFlightTrackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 飞行轨迹Controller
*
* @author dzc
* @date 2025-12-17
*/
@RestController
@RequestMapping("/api/device/drone/track")
@Tag(name = "飞行轨迹管理", description = "飞行轨迹相关接口")
@Slf4j
public class DroneFlightTrackController {
@Autowired
private IDroneFlightTrackService flightTrackService;
@Operation(summary = "获取飞行轨迹", description = "获取指定设备的飞行轨迹数据")
@GetMapping("/{deviceSn}")
public Result<FlightTrackVO> getFlightTrack(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "任务ID")
@RequestParam(required = false) String jobId,
@Parameter(description = "航线任务ID")
@RequestParam(required = false) String routeId,
@Parameter(description = "开始时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "结束时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
@Parameter(description = "限制数量")
@RequestParam(required = false, defaultValue = "1000") Integer limit) {
try {
List<DroneFlightTrack> trackPoints = flightTrackService.getTrackPoints(
deviceSn, jobId, routeId, startTime, endTime, limit);
FlightTrackVO vo = new FlightTrackVO();
vo.setDeviceSn(deviceSn);
vo.setJobId(jobId);
vo.setRouteId(routeId);
if (trackPoints != null && !trackPoints.isEmpty()) {
// 转换轨迹点
List<FlightTrackVO.TrackPointVO> pointVOs = trackPoints.stream()
.map(this::convertToTrackPointVO)
.collect(Collectors.toList());
vo.setTrackPoints(pointVOs);
vo.setTotalPoints(pointVOs.size());
// 计算飞行时长(秒)
LocalDateTime firstTime = trackPoints.get(0).getRecordTime();
LocalDateTime lastTime = trackPoints.get(trackPoints.size() - 1).getRecordTime();
if (firstTime != null && lastTime != null) {
vo.setDuration(java.time.Duration.between(firstTime, lastTime).getSeconds());
}
} else {
vo.setTrackPoints(new ArrayList<>());
vo.setTotalPoints(0);
vo.setDuration(0L);
}
return Result.succeed(vo);
} catch (Exception e) {
log.error("获取飞行轨迹失败: deviceSn={}", deviceSn, e);
return Result.failed("获取失败: " + e.getMessage());
}
}
@Operation(summary = "获取最新轨迹点", description = "获取指定设备的最新轨迹点")
@GetMapping("/latest/{deviceSn}")
public Result<FlightTrackVO.TrackPointVO> getLatestTrackPoint(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
try {
DroneFlightTrack track = flightTrackService.getLatestTrackPoint(deviceSn);
if (track != null) {
FlightTrackVO.TrackPointVO vo = convertToTrackPointVO(track);
return Result.succeed(vo);
} else {
return Result.succeed(null, "暂无轨迹数据");
}
} catch (Exception e) {
log.error("获取最新轨迹点失败: deviceSn={}", deviceSn, e);
return Result.failed("获取失败: " + e.getMessage());
}
}
@Operation(summary = "删除历史轨迹", description = "删除指定时间之前的飞行轨迹数据")
@DeleteMapping("/history/{deviceSn}")
public Result<Integer> deleteHistoryTracks(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "删除此时间之前的轨迹", required = true)
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beforeTime) {
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
try {
int count = flightTrackService.deleteTrackPointsBefore(deviceSn, beforeTime);
return Result.succeed(count, "成功删除 " + count + " 条轨迹记录");
} catch (Exception e) {
log.error("删除历史轨迹失败: deviceSn={}", deviceSn, e);
return Result.failed("删除失败: " + e.getMessage());
}
}
@Operation(summary = "统计轨迹点数量", description = "统计指定条件的轨迹点数量")
@GetMapping("/count/{deviceSn}")
public Result<Long> countTrackPoints(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "任务ID")
@RequestParam(required = false) String jobId,
@Parameter(description = "航线任务ID")
@RequestParam(required = false) String routeId,
@Parameter(description = "开始时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "结束时间")
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
try {
Long count = flightTrackService.countTrackPoints(deviceSn, jobId, routeId, startTime, endTime);
return Result.succeed(count);
} catch (Exception e) {
log.error("统计轨迹点数量失败", e);
return Result.failed("统计失败: " + e.getMessage());
}
}
/**
* 转换为轨迹点VO
*/
private FlightTrackVO.TrackPointVO convertToTrackPointVO(DroneFlightTrack track) {
FlightTrackVO.TrackPointVO vo = new FlightTrackVO.TrackPointVO();
vo.setLng(track.getLongitude() != null ? track.getLongitude().doubleValue() : 0);
vo.setLat(track.getLatitude() != null ? track.getLatitude().doubleValue() : 0);
vo.setAlt(track.getAltitude() != null ? track.getAltitude().doubleValue() : 0);
vo.setHeight(track.getHeight() != null ? track.getHeight().doubleValue() : 0);
vo.setSpeed(track.getHorizontalSpeed() != null ? track.getHorizontalSpeed().doubleValue() : 0);
vo.setHeading(track.getHeading() != null ? track.getHeading().doubleValue() : 0);
vo.setBatteryPercent(track.getBatteryPercent());
vo.setTime(track.getRecordTime());
// 偏离信息
vo.setDeviationDistance(track.getDeviationDistance() != null ? track.getDeviationDistance().doubleValue() : 0);
vo.setIsDeviation(track.getIsDeviation() != null && track.getIsDeviation() == 1);
return vo;
}
}
@@ -0,0 +1,331 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.WaylineAction;
import com.central.device.entity.WaylineRoute;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.model.dto.WaylineRouteCreateDTO;
import com.central.device.model.dto.BindDeviceDTO;
import com.central.device.model.vo.WaylineRouteVO;
import com.central.device.model.vo.WaypointVO;
import com.central.device.model.vo.WaypointActionVO;
import com.central.device.model.vo.RouteDetailVO;
import com.central.device.parser.model.KmzParseResult;
import com.central.device.service.IWaylineParseService;
import com.central.device.service.IWaylineRouteService;
import com.central.device.service.IWaylineWaypointService;
import com.central.device.mapper.WaylineActionMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 航线任务管理Controller
*
* @author dzc
* @date 2025-12-17
*/
@RestController
@RequestMapping("/device/route")
@Tag(name = "航线任务管理", description = "航线任务相关接口")
@Slf4j
@Validated
public class WaylineRouteController {
@Autowired
private IWaylineRouteService waylineRouteService;
@Autowired
private IWaylineParseService waylineParseService;
@Autowired
private IWaylineWaypointService waylineWaypointService;
@Autowired
private WaylineActionMapper waylineActionMapper;
@Autowired
private ObjectMapper objectMapper;
@Operation(summary = "绑定航迹文件到设备并解析", description = "将航迹文件绑定到设备,并自动解析航线、航点、动作数据")
@PostMapping("/bindWaylineToDevice")
public Result<String> bindWaylineToDevice(@RequestBody BindDeviceDTO dto) {
try {
waylineRouteService.bindWaylineToDevice(
dto.getDeviceSn(),
dto.getWaylineId(),
dto.getWaylineName(),
dto.getWorkspaceId()
);
return Result.succeed("绑定成功,航线解析完成");
} catch (Exception e) {
log.error("绑定航迹文件到设备失败: deviceSn={}, waylineId={}",
dto.getDeviceSn(), dto.getWaylineId(), e);
return Result.failed("绑定失败: " + e.getMessage());
}
}
@Operation(summary = "创建航线任务", description = "创建新的航线任务,关联航迹文件和设备")
@PostMapping("/create")
public Result<WaylineRouteVO> createRoute(@Valid @RequestBody WaylineRouteCreateDTO dto) {
try {
WaylineRoute route = waylineRouteService.createRoute(
dto.getRouteName(),
dto.getFileWaylineId(),
dto.getDeviceSn(),
dto.getDeviceName(),
dto.getRemark()
);
WaylineRouteVO vo = convertToRouteVO(route);
return Result.succeed(vo);
} catch (Exception e) {
log.error("创建航线任务失败", e);
return Result.failed("创建失败: " + e.getMessage());
}
}
@Operation(summary = "根据航迹文件ID查询航线任务列表", description = "查询指定航迹文件创建的所有航线任务")
@GetMapping("/listByFileWaylineId/{fileWaylineId}")
public Result<List<WaylineRouteVO>> listByFileWaylineId(
@Parameter(description = "航迹文件ID", required = true)
@PathVariable String fileWaylineId) {
if (!StringUtils.hasText(fileWaylineId)) {
return Result.failed("航迹文件ID不能为空");
}
try {
List<WaylineRoute> routes = waylineRouteService.listByFileWaylineId(fileWaylineId);
List<WaylineRouteVO> vos = routes.stream()
.map(this::convertToRouteVO)
.collect(Collectors.toList());
return Result.succeed(vos);
} catch (Exception e) {
log.error("查询航线任务列表失败: fileWaylineId={}", fileWaylineId, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "根据设备SN查询绑定的航线任务列表", description = "查询指定设备绑定的所有航线任务")
@GetMapping("/listByDevice/{deviceSn}")
public Result<List<WaylineRouteVO>> listByDevice(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
try {
List<WaylineRoute> routes = waylineRouteService.listByDeviceSn(deviceSn);
List<WaylineRouteVO> vos = routes.stream()
.map(this::convertToRouteVO)
.collect(Collectors.toList());
return Result.succeed(vos);
} catch (Exception e) {
log.error("查询航线任务列表失败: deviceSn={}", deviceSn, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "获取航线解析详情", description = "获取航线的完整信息,包含航点和动作数据")
@GetMapping("/detail/{routeId}")
public Result<RouteDetailVO> getRouteDetail(
@Parameter(description = "航线任务ID", required = true)
@PathVariable String routeId) {
if (!StringUtils.hasText(routeId)) {
return Result.failed("航线任务ID不能为空");
}
try {
// 获取航线任务信息
WaylineRoute route = waylineRouteService.getByRouteId(routeId);
if (route == null) {
return Result.failed("航线任务不存在");
}
// 获取航点数据
List<WaylineWaypoint> waypoints = waylineWaypointService.listByRouteIdOrderByIndex(routeId);
List<WaypointVO> waypointVOs = waypoints.stream()
.map(this::convertToWaypointVO)
.collect(Collectors.toList());
// 获取动作数据
List<WaypointActionVO> actionVOs = waylineParseService.getActionsByRouteId(routeId);
// 构建返回数据
RouteDetailVO detailVO = new RouteDetailVO();
detailVO.setRouteInfo(convertToRouteVO(route));
detailVO.setWaypoints(waypointVOs);
detailVO.setActions(actionVOs);
detailVO.setTotalWaypoints(waypointVOs.size());
detailVO.setTotalActions(actionVOs.size());
detailVO.setTotalDistance(route.getTotalDistance() != null ? route.getTotalDistance().doubleValue() : null);
detailVO.setTotalDuration(route.getTotalDuration() != null ? route.getTotalDuration().doubleValue() : null);
return Result.succeed(detailVO);
} catch (Exception e) {
log.error("获取航线任务详情失败: routeId={}", routeId, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "获取航线航点列表", description = "获取航线的所有航点坐标信息,用于地图展示")
@GetMapping("/waypoints/{routeId}")
public Result<List<WaypointVO>> getRouteWaypoints(
@Parameter(description = "航线任务ID", required = true)
@PathVariable String routeId) {
if (!StringUtils.hasText(routeId)) {
return Result.failed("航线任务ID不能为空");
}
try {
List<WaylineWaypoint> waypoints = waylineWaypointService.listByRouteIdOrderByIndex(routeId);
List<WaypointVO> vos = waypoints.stream()
.map(this::convertToWaypointVO)
.collect(Collectors.toList());
return Result.succeed(vos);
} catch (Exception e) {
log.error("获取航点列表失败: routeId={}", routeId, e);
return Result.failed("查询失败: " + e.getMessage());
}
}
@Operation(summary = "解析航线任务", description = "解析航线的KMZ文件,提取航点和动作数据")
@PostMapping("/parse/{routeId}")
public Result<KmzParseResult> parseRoute(
@Parameter(description = "航线任务ID", required = true)
@PathVariable String routeId) {
if (!StringUtils.hasText(routeId)) {
return Result.failed("航线任务ID不能为空");
}
try {
KmzParseResult result = waylineParseService.parseRoute(routeId);
if (result.isSuccess()) {
return Result.succeed(result, "解析成功");
} else {
return Result.failed("解析失败: " + result.getErrorMessage());
}
} catch (Exception e) {
log.error("解析航线任务失败: routeId={}", routeId, e);
return Result.failed("解析失败: " + e.getMessage());
}
}
@Operation(summary = "批量解析航线任务", description = "批量解析多个航线的KMZ文件")
@PostMapping("/parse/batch")
public Result<String> batchParseRoutes(@RequestBody List<String> routeIds) {
try {
if (CollectionUtils.isEmpty(routeIds)) {
return Result.failed("航线任务ID列表不能为空");
}
waylineParseService.batchParseRoutes(routeIds.toArray(new String[0]));
return Result.succeed("批量解析任务已提交,正在后台执行");
} catch (Exception e) {
log.error("批量解析航线任务失败", e);
return Result.failed("批量解析失败: " + e.getMessage());
}
}
/**
* 转换为航线任务VO
*/
private WaylineRouteVO convertToRouteVO(WaylineRoute route) {
WaylineRouteVO vo = new WaylineRouteVO();
BeanUtils.copyProperties(route, vo);
// 设置解析状态描述
if (route.getParseStatus() != null) {
WaylineRoute.ParseStatus status = WaylineRoute.ParseStatus.fromCode(route.getParseStatus());
vo.setParseStatusDesc(status.getDesc());
}
return vo;
}
/**
* 转换为航点VO
*/
private WaypointVO convertToWaypointVO(WaylineWaypoint waypoint) {
WaypointVO vo = new WaypointVO();
BeanUtils.copyProperties(waypoint, vo);
vo.setIndex(waypoint.getWaypointIndex());
// 转换布尔值
vo.setUseStraightLine(waypoint.getUseStraightLine() != null && waypoint.getUseStraightLine() == 1);
vo.setIsRisky(waypoint.getIsRisky() != null && waypoint.getIsRisky() == 1);
// 加载动作数据
List<WaylineAction> actions = waylineActionMapper.selectByWaypointId(waypoint.getId());
if (actions != null && !actions.isEmpty()) {
List<WaypointActionVO> actionVOs = new ArrayList<>();
for (WaylineAction action : actions) {
WaypointActionVO actionVO = new WaypointActionVO();
actionVO.setActionGroupId(action.getActionGroupId());
actionVO.setActionIndex(action.getActionIndex());
actionVO.setActionType(action.getActionType());
actionVO.setTriggerType(action.getTriggerType());
// 解析动作参数
if (StringUtils.hasText(action.getActionParams())) {
try {
Map<String, Object> params = objectMapper.readValue(action.getActionParams(), Map.class);
actionVO.setActionParams(params);
// 从参数中提取具体字段
if (params.containsKey("hoverTime")) {
Object hoverTime = params.get("hoverTime");
if (hoverTime instanceof Number) {
actionVO.setHoverTime(((Number) hoverTime).doubleValue());
}
}
if (params.containsKey("aircraftHeading")) {
Object heading = params.get("aircraftHeading");
if (heading instanceof Number) {
actionVO.setAircraftHeading(((Number) heading).doubleValue());
}
}
if (params.containsKey("gimbalPitchRotateAngle")) {
Object pitch = params.get("gimbalPitchRotateAngle");
if (pitch instanceof Number) {
actionVO.setGimbalPitchRotateAngle(((Number) pitch).doubleValue());
}
}
if (params.containsKey("gimbalYawRotateAngle")) {
Object yaw = params.get("gimbalYawRotateAngle");
if (yaw instanceof Number) {
actionVO.setGimbalYawRotateAngle(((Number) yaw).doubleValue());
}
}
// 提取megaphone文件路径
if (params.containsKey("megaphoneOperateFilePath")) {
Object filePath = params.get("megaphoneOperateFilePath");
if (filePath != null) {
actionVO.setMegaphoneFilePath(filePath.toString());
}
}
} catch (Exception e) {
log.warn("解析动作参数失败: waypointId={}, actionId={}", waypoint.getId(), action.getId(), e);
}
}
actionVOs.add(actionVO);
}
vo.setActions(actionVOs);
} else {
vo.setActions(new ArrayList<>());
}
return vo;
}
}
@@ -0,0 +1,190 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 飞行轨迹实体
*
* @author dzc
* @date 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("drone_flight_track")
public class DroneFlightTrack implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 设备SN
*/
@TableField("device_sn")
private String deviceSn;
/**
* 任务ID(关联wayline_job.job_id)
*/
@TableField("job_id")
private String jobId;
/**
* 航线任务ID(关联wayline_route.route_id)
*/
@TableField("route_id")
private String routeId;
/**
* 经度
*/
@TableField("longitude")
private BigDecimal longitude;
/**
* 纬度
*/
@TableField("latitude")
private BigDecimal latitude;
/**
* 海拔高度(m)
*/
@TableField("altitude")
private BigDecimal altitude;
/**
* 相对高度(m)
*/
@TableField("height")
private BigDecimal height;
/**
* 水平速度(m/s)
*/
@TableField("horizontal_speed")
private BigDecimal horizontalSpeed;
/**
* 垂直速度(m/s)
*/
@TableField("vertical_speed")
private BigDecimal verticalSpeed;
/**
* 航向角(度)
*/
@TableField("heading")
private BigDecimal heading;
/**
* 俯仰角(度)
*/
@TableField("pitch")
private BigDecimal pitch;
/**
* 横滚角(度)
*/
@TableField("roll")
private BigDecimal roll;
/**
* 飞行模式
*/
@TableField("flight_mode")
private Integer flightMode;
/**
* 电池电量(%)
*/
@TableField("battery_percent")
private Integer batteryPercent;
/**
* 偏离距离(m)-与计划航线的偏离
*/
@TableField("deviation_distance")
private BigDecimal deviationDistance;
/**
* 是否偏离:0-否,1-是
*/
@TableField("is_deviation")
private Integer isDeviation;
/**
* 记录时间(无人机上报时间)
*/
@TableField("record_time")
private LocalDateTime recordTime;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 飞行模式枚举(参考大疆飞行模式)
*/
public enum FlightMode {
MANUAL(0, "手动模式"),
ATTI(1, "姿态模式"),
P_GPS(2, "P-GPS模式"),
F_GPS(3, "F-GPS模式"),
SPORT(4, "运动模式"),
TRIPOD(5, "三脚架模式"),
CINEMATIC(6, "平滑模式"),
SMART(7, "智能模式"),
BOUNCE(8, "弹跳模式"),
WAYPOINT(9, "航线模式"),
POI(10, "兴趣点环绕"),
FOLLOW(11, "智能跟随"),
FPV(12, "FPV模式"),
ACTIVE_TRACK(13, "智能拍摄"),
TAP_FLY(14, "点击飞行"),
QUICK_SHOT(15, "快拍模式");
private final Integer code;
private final String desc;
FlightMode(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static FlightMode fromCode(Integer code) {
for (FlightMode mode : values()) {
if (mode.getCode().equals(code)) {
return mode;
}
}
return MANUAL;
}
}
}
@@ -0,0 +1,153 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 航点动作实体
*
* @author dzc
* @date 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("wayline_action")
public class WaylineAction implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航点ID(关联wayline_waypoint.id)
*/
@TableField("waypoint_id")
private Long waypointId;
/**
* 航线任务ID(冗余字段,便于查询)
*/
@TableField("route_id")
private String routeId;
/**
* 动作组ID
*/
@TableField("action_group_id")
private Integer actionGroupId;
/**
* 动作序号(组内)
*/
@TableField("action_index")
private Integer actionIndex;
/**
* 动作类型
*/
@TableField("action_type")
private String actionType;
/**
* 动作参数(JSON格式)
*/
@TableField("action_params")
private String actionParams;
/**
* 触发类型:reachPoint-到达航点,betweenAdjacentPoints-航点间
*/
@TableField("trigger_type")
private String triggerType;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建时间
*/
@TableField("create_time")
private LocalDateTime createTime;
/**
* 动作类型枚举
*/
public enum ActionType {
TAKE_PHOTO("takePhoto", "拍照"),
START_RECORD("startRecord", "开始录像"),
STOP_RECORD("stopRecord", "停止录像"),
HOVER("hover", "悬停"),
ZOOM("zoom", "变焦"),
GIMBAL_ROTATE("gimbalRotate", "云台旋转"),
ROTATE_YAW("rotateYaw", "飞机旋转"),
MEGAPHONE("megaphone", "喊话器"),
FOCUS("focus", "对焦"),
GIMBAL_EVENLY_ROTATE("gimbalEvenlyRotate", "云台均匀旋转"),
FLIGHT_PATH_ROTATE_YAW("flightPathRotateYaw", "飞行路径旋转"),
LOOK_AT("lookAt", "查看目标"),
LOOK_AT_TARGET("lookAtTarget", "查看特定目标");
private final String code;
private final String desc;
ActionType(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static ActionType fromCode(String code) {
for (ActionType type : values()) {
if (type.getCode().equals(code)) {
return type;
}
}
return null;
}
}
/**
* 触发类型枚举
*/
public enum TriggerType {
REACH_POINT("reachPoint", "到达航点"),
BETWEEN_ADJACENT_POINTS("betweenAdjacentPoints", "航点间"),
AFTER_FINISHED_WAYPOINT("afterFinishedWaypoint", "完成航点后"),
BEFORE_FINISHED_WAYPOINT("beforeFinishedWaypoint", "完成航点前"),
IMMEDIATELY("immediately", "立即触发");
private final String code;
private final String desc;
TriggerType(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,245 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 航线任务实体
*
* @author dzc
* @date 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("wayline_route")
public class WaylineRoute implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航线任务ID(UUID)
*/
@TableField("route_id")
private String routeId;
/**
* 航线任务名称
*/
@TableField("route_name")
private String routeName;
/**
* 关联航迹文件ID(wayline_file.wayline_id)
*/
@TableField("file_wayline_id")
private String fileWaylineId;
/**
* 绑定设备SN
*/
@TableField("device_sn")
private String deviceSn;
/**
* 设备名称(冗余)
*/
@TableField("device_name")
private String deviceName;
/**
* 解析状态:0-未解析,1-解析中,2-已解析,3-解析失败
*/
@TableField("parse_status")
private Integer parseStatus;
/**
* 解析错误信息
*/
@TableField("parse_error")
private String parseError;
/**
* 航点数量
*/
@TableField("waypoint_count")
private Integer waypointCount;
/**
* 动作总数
*/
@TableField("action_count")
private Integer actionCount;
/**
* 总航程(m)
*/
@TableField("total_distance")
private BigDecimal totalDistance;
/**
* 预计时长(s)
*/
@TableField("total_duration")
private BigDecimal totalDuration;
/**
* 自动飞行速度(m/s)
*/
@TableField("auto_flight_speed")
private BigDecimal autoFlightSpeed;
/**
* 起飞点坐标(经度,纬度,高度)
*/
@TableField("take_off_point")
private String takeOffPoint;
/**
* 完成动作:goHome/hover/landing
*/
@TableField("finish_action")
private String finishAction;
/**
* 遥控器失联动作
*/
@TableField("exit_on_rc_lost")
private String exitOnRcLost;
/**
* 全局返航高度(m)
*/
@TableField("global_rth_height")
private BigDecimal globalRthHeight;
/**
* 坐标系
*/
@TableField("coordinate_mode")
private String coordinateMode;
/**
* 高度模式
*/
@TableField("height_mode")
private String heightMode;
/**
* 状态:0-禁用,1-启用
*/
@TableField("status")
private Integer status;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 工作空间ID
*/
@TableField("workspace_id")
private String workspaceId;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建人
*/
@TableField(value = "create_by", fill = FieldFill.INSERT)
private String createBy;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新人
*/
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
private String updateBy;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 解析状态枚举
*/
public enum ParseStatus {
NOT_PARSED(0, "未解析"),
PARSING(1, "解析中"),
PARSED(2, "已解析"),
FAILED(3, "解析失败");
private final Integer code;
private final String desc;
ParseStatus(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static ParseStatus fromCode(Integer code) {
for (ParseStatus status : values()) {
if (status.getCode().equals(code)) {
return status;
}
}
return NOT_PARSED;
}
}
/**
* 完成动作枚举
*/
public enum FinishAction {
GO_HOME("goHome", "自动返航"),
HOVER("hover", "原地悬停"),
LANDING("landing", "原地降落");
private final String code;
private final String desc;
FinishAction(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,195 @@
package com.central.device.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 航点实体
*
* @author dzc
* @date 2025-12-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("wayline_waypoint")
public class WaylineWaypoint implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 航线任务ID(关联wayline_route.route_id)
*/
@TableField("route_id")
private String routeId;
/**
* 航点序号(从0开始)
*/
@TableField("waypoint_index")
private Integer waypointIndex;
/**
* 经度
*/
@TableField("longitude")
private BigDecimal longitude;
/**
* 纬度
*/
@TableField("latitude")
private BigDecimal latitude;
/**
* 相对高度(m)-相对起飞点
*/
@TableField("height")
private BigDecimal height;
/**
* 执行高度(m)
*/
@TableField("execute_height")
private BigDecimal executeHeight;
/**
* 椭球高度(m)
*/
@TableField("ellipsoid_height")
private BigDecimal ellipsoidHeight;
/**
* 飞行速度(m/s)
*/
@TableField("speed")
private BigDecimal speed;
/**
* 航向模式
*/
@TableField("heading_mode")
private String headingMode;
/**
* 航向角(度)
*/
@TableField("heading_angle")
private BigDecimal headingAngle;
/**
* 云台俯仰角(度)
*/
@TableField("gimbal_pitch_angle")
private BigDecimal gimbalPitchAngle;
/**
* 转弯模式
*/
@TableField("turn_mode")
private String turnMode;
/**
* 转弯阻尼距离(m)
*/
@TableField("turn_damping_dist")
private BigDecimal turnDampingDist;
/**
* 是否直线飞行:0-否,1-是
*/
@TableField("use_straight_line")
private Integer useStraightLine;
/**
* 是否风险点:0-否,1-是
*/
@TableField("is_risky")
private Integer isRisky;
/**
* 动作组数量
*/
@TableField("action_group_count")
private Integer actionGroupCount;
/**
* 租户ID
*/
@TableField("tenant_id")
private String tenantId;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 航向模式枚举
*/
public enum HeadingMode {
AUTO("auto", "自动"),
MANUAL("manual", "手动"),
TOWARD_POINT_OF_INTEREST("towardPointOfInterest", "朝向兴趣点"),
RC_CONTROL("rcControl", "遥控器控制");
private final String code;
private final String desc;
HeadingMode(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
/**
* 转弯模式枚举
*/
public enum TurnMode {
TO_POINT_AND_STOP("toPointAndStop", "到点停止"),
TO_POINT_AND_GO_WITH_STOP("toPointAndGoWithStop", "到点不停"),
COORDINATE_TURN("coordinateTurn", "协调转弯"),
MANUAL_CONTROL("manualControl", "手动控制");
private final String code;
private final String desc;
TurnMode(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
}
@@ -0,0 +1,87 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.DroneFlightTrack;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface DroneFlightTrackMapper extends BaseMapper<DroneFlightTrack> {
/**
* 根据设备SN和查询条件获取轨迹点
*
* @param deviceSn 设备SN
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @param limit 限制数量(可选)
* @return 轨迹点列表
*/
List<DroneFlightTrack> selectTrackPoints(@Param("deviceSn") String deviceSn,
@Param("jobId") String jobId,
@Param("routeId") String routeId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime,
@Param("limit") Integer limit);
/**
* 根据设备SN获取最新的轨迹点
*
* @param deviceSn 设备SN
* @return 最新轨迹点
*/
DroneFlightTrack selectLatestTrackPoint(@Param("deviceSn") String deviceSn);
/**
* 根据设备SN删除指定时间范围的轨迹
*
* @param deviceSn 设备SN
* @param beforeTime 删除此时间之前的轨迹
* @return 影响行数
*/
int deleteByDeviceSnAndTimeBefore(@Param("deviceSn") String deviceSn,
@Param("beforeTime") LocalDateTime beforeTime);
/**
* 统计轨迹点数量
*
* @param deviceSn 设备SN(可选)
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @return 轨迹点数量
*/
Long countTrackPoints(@Param("deviceSn") String deviceSn,
@Param("jobId") String jobId,
@Param("routeId") String routeId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
/**
* 批量插入轨迹点
*
* @param trackPoints 轨迹点列表
* @return 影响行数
*/
int batchInsert(@Param("trackPoints") List<DroneFlightTrack> trackPoints);
/**
* 根据航线任务ID删除飞行轨迹
*
* @param routeId 航线任务ID
* @return 影响行数
*/
int deleteByRouteId(@Param("routeId") String routeId);
}
@@ -0,0 +1,58 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineAction;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 航点动作Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface WaylineActionMapper extends BaseMapper<WaylineAction> {
/**
* 根据航点ID查询动作列表
*
* @param waypointId 航点ID
* @return 动作列表
*/
List<WaylineAction> selectByWaypointId(@Param("waypointId") Long waypointId);
/**
* 根据航线任务ID查询动作列表
*
* @param routeId 航线任务ID
* @return 动作列表
*/
List<WaylineAction> selectByRouteId(@Param("routeId") String routeId);
/**
* 根据航线任务ID删除动作
*
* @param routeId 航线任务ID
* @return 影响行数
*/
int deleteByRouteId(@Param("routeId") String routeId);
/**
* 批量插入动作
*
* @param actions 动作列表
* @return 影响行数
*/
int batchInsert(@Param("actions") List<WaylineAction> actions);
/**
* 统计动作数量
*
* @param routeId 航线任务ID
* @return 动作数量
*/
Integer countByRouteId(@Param("routeId") String routeId);
}
@@ -0,0 +1,102 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineRoute;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
import java.util.List;
/**
* 航线任务Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface WaylineRouteMapper extends BaseMapper<WaylineRoute> {
/**
* 根据航迹文件ID查询航线任务列表
*
* @param fileWaylineId 航迹文件ID
* @return 航线任务列表
*/
List<WaylineRoute> selectByFileWaylineId(@Param("fileWaylineId") String fileWaylineId);
/**
* 根据设备SN查询绑定的航线任务列表
*
* @param deviceSn 设备SN
* @return 航线任务列表
*/
List<WaylineRoute> selectByDeviceSn(@Param("deviceSn") String deviceSn);
/**
* 根据航线任务ID查询
*
* @param routeId 航线任务ID
* @return 航线任务
*/
WaylineRoute selectByRouteId(@Param("routeId") String routeId);
/**
* 更新解析状态
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
* @return 影响行数
*/
int updateParseStatus(@Param("routeId") String routeId, @Param("parseStatus") Integer parseStatus);
/**
* 更新解析状态和错误信息
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
* @param parseError 解析错误信息
* @return 影响行数
*/
int updateParseStatusWithError(@Param("routeId") String routeId,
@Param("parseStatus") Integer parseStatus,
@Param("parseError") String parseError);
/**
* 更新航线任务统计信息
*
* @param routeId 航线任务ID
* @param waypointCount 航点数量
* @param actionCount 动作数量
* @param totalDistance 总航程
* @param totalDuration 总时长
* @param autoFlightSpeed 自动飞行速度
* @return 影响行数
*/
int updateRouteStats(@Param("routeId") String routeId,
@Param("waypointCount") Integer waypointCount,
@Param("actionCount") Integer actionCount,
@Param("totalDistance") BigDecimal totalDistance,
@Param("totalDuration") BigDecimal totalDuration,
@Param("autoFlightSpeed") BigDecimal autoFlightSpeed);
/**
* 根据设备SN和航迹文件ID查询航线任务
*
* @param deviceSn 设备SN
* @param waylineId 航迹文件ID
* @return 航线任务列表
*/
List<WaylineRoute> selectByDeviceSnAndFileWaylineId(@Param("deviceSn") String deviceSn,
@Param("waylineId") String waylineId);
/**
* 删除设备与航迹文件的绑定(包括相关数据)
*
* @param deviceSn 设备SN
* @param waylineId 航迹文件ID
* @return 影响行数
*/
int deleteBindingByDeviceAndWayline(@Param("deviceSn") String deviceSn,
@Param("waylineId") String waylineId);
}
@@ -0,0 +1,50 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineWaypoint;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 航点Mapper接口
*
* @author dzc
* @date 2025-12-17
*/
@Mapper
public interface WaylineWaypointMapper extends BaseMapper<WaylineWaypoint> {
/**
* 根据航线任务ID查询航点列表(按序号排序)
*
* @param routeId 航线任务ID
* @return 航点列表
*/
List<WaylineWaypoint> selectByRouteIdOrderByIndex(@Param("routeId") String routeId);
/**
* 根据航线任务ID删除航点
*
* @param routeId 航线任务ID
* @return 影响行数
*/
int deleteByRouteId(@Param("routeId") String routeId);
/**
* 批量插入航点
*
* @param waypoints 航点列表
* @return 影响行数
*/
int batchInsert(@Param("waypoints") List<WaylineWaypoint> waypoints);
/**
* 统计航点数量
*
* @param routeId 航线任务ID
* @return 航点数量
*/
Integer countByRouteId(@Param("routeId") String routeId);
}
@@ -0,0 +1,37 @@
package com.central.device.model.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 绑定设备DTO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class BindDeviceDTO {
/**
* 设备SN
*/
@NotBlank(message = "设备SN不能为空")
private String deviceSn;
/**
* 航线ID
*/
@NotBlank(message = "航线ID不能为空")
private String waylineId;
/**
* 航线名称
*/
@NotBlank(message = "航线名称不能为空")
private String waylineName;
/**
* 工作空间ID
*/
private String workspaceId;
}
@@ -0,0 +1,38 @@
package com.central.device.model.dto;
import lombok.Data;
/**
* 创建航线任务DTO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class WaylineRouteCreateDTO {
/**
* 航线任务名称
*/
private String routeName;
/**
* 关联航迹文件ID
*/
private String fileWaylineId;
/**
* 绑定设备SN
*/
private String deviceSn;
/**
* 设备名称
*/
private String deviceName;
/**
* 备注
*/
private String remark;
}
@@ -0,0 +1,151 @@
package com.central.device.model.vo;
import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class FlightTrackVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 设备SN
*/
private String deviceSn;
/**
* 任务ID
*/
private String jobId;
/**
* 航线任务ID
*/
private String routeId;
/**
* 轨迹点列表
*/
private List<TrackPointVO> trackPoints;
/**
* 总点数
*/
private Integer totalPoints;
/**
* 飞行时长(秒)
*/
private Long duration;
/**
* 开始时间
*/
private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime;
/**
* 总航程(米)
*/
private Double totalDistance;
/**
* 最大速度(米/秒)
*/
private Double maxSpeed;
/**
* 平均速度(米/秒)
*/
private Double avgSpeed;
/**
* 最大偏离距离(米)
*/
private Double maxDeviationDistance;
/**
* 轨迹点VO
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class TrackPointVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 经度
*/
private Double lng;
/**
* 纬度
*/
private Double lat;
/**
* 海拔高度(米)
*/
private Double alt;
/**
* 相对高度(米)
*/
private Double height;
/**
* 水平速度(米/秒)
*/
private Double speed;
/**
* 航向角(度)
*/
private Double heading;
/**
* 电池电量(%)
*/
private Integer batteryPercent;
/**
* 记录时间
*/
private LocalDateTime time;
/**
* 偏离距离(米)
*/
private Double deviationDistance;
/**
* 是否偏离
*/
private Boolean isDeviation;
/**
* 飞行模式
*/
private Integer flightMode;
}
}
@@ -0,0 +1,52 @@
package com.central.device.model.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 航线详情VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class RouteDetailVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 航线任务信息
*/
private WaylineRouteVO routeInfo;
/**
* 航点列表
*/
private List<WaypointVO> waypoints;
/**
* 动作列表
*/
private List<WaypointActionVO> actions;
/**
* 总航点数
*/
private Integer totalWaypoints;
/**
* 总动作数
*/
private Integer totalActions;
/**
* 总距离(米)
*/
private Double totalDistance;
/**
* 总时长(秒)
*/
private Double totalDuration;
}
@@ -0,0 +1,115 @@
package com.central.device.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Builder;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 航线任务VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class WaylineRouteVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 航线任务ID
*/
private String routeId;
/**
* 航线任务名称
*/
private String routeName;
/**
* 关联航迹文件ID
*/
private String fileWaylineId;
/**
* 设备SN
*/
private String deviceSn;
/**
* 设备名称
*/
private String deviceName;
/**
* 解析状态
*/
private Integer parseStatus;
/**
* 解析状态描述
*/
private String parseStatusDesc;
/**
* 解析错误信息
*/
private String parseError;
/**
* 航点数量
*/
private Integer waypointCount;
/**
* 动作总数
*/
private Integer actionCount;
/**
* 总航程(m)
*/
private BigDecimal totalDistance;
/**
* 预计时长(s)
*/
private BigDecimal totalDuration;
/**
* 自动飞行速度(m/s)
*/
private BigDecimal autoFlightSpeed;
/**
* 完成动作
*/
private String finishAction;
/**
* 状态
*/
private Integer status;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
@@ -0,0 +1,92 @@
package com.central.device.model.vo;
import lombok.Data;
import java.io.Serializable;
import java.util.Map;
/**
* 航点动作VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
public class WaypointActionVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 动作组ID
*/
private Integer actionGroupId;
/**
* 动作序号(组内)
*/
private Integer actionIndex;
/**
* 动作类型
*/
private String actionType;
/**
* 动作类型描述
*/
private String actionTypeDesc;
/**
* 动作参数
*/
private Map<String, Object> actionParams;
/**
* 触发类型
*/
private String triggerType;
/**
* 触发类型描述
*/
private String triggerTypeDesc;
/**
* 延迟时间(毫秒)
*/
private Long delayTime;
/**
* 相机位置索引
*/
private Integer payloadPositionIndex;
/**
* 悬停时间(秒)
*/
private Double hoverTime;
/**
* 飞机航向角
*/
private Double aircraftHeading;
/**
* 云台俯仰旋转角度
*/
private Double gimbalPitchRotateAngle;
/**
* 云台偏航旋转角度
*/
private Double gimbalYawRotateAngle;
/**
* 焦距(毫米)
*/
private Double focalLength;
/**
* 音频文件路径
*/
private String megaphoneFilePath;
}
@@ -0,0 +1,115 @@
package com.central.device.model.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Builder;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
/**
* 航点VO
*
* @author dzc
* @date 2025-12-17
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class WaypointVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 航点序号
*/
private Integer index;
/**
* 经度
*/
private BigDecimal longitude;
/**
* 纬度
*/
private BigDecimal latitude;
/**
* 相对高度(m)
*/
private BigDecimal height;
/**
* 执行高度(m)
*/
private BigDecimal executeHeight;
/**
* 椭球高度(m)
*/
private BigDecimal ellipsoidHeight;
/**
* 飞行速度(m/s)
*/
private BigDecimal speed;
/**
* 航向模式
*/
private String headingMode;
/**
* 航向角(度)
*/
private BigDecimal headingAngle;
/**
* 云台俯仰角(度)
*/
private BigDecimal gimbalPitchAngle;
/**
* 云台横滚角(度)
*/
private BigDecimal gimbalRollAngle;
/**
* 云台偏航角(度)
*/
private BigDecimal gimbalYawAngle;
/**
* 转弯模式
*/
private String turnMode;
/**
* 转弯阻尼距离(m)
*/
private BigDecimal turnDampingDist;
/**
* 是否直线飞行
*/
private Boolean useStraightLine;
/**
* 是否风险点
*/
private Boolean isRisky;
/**
* 动作组数量
*/
private Integer actionGroupCount;
/**
* 动作列表
*/
private List<WaypointActionVO> actions;
}
@@ -0,0 +1,641 @@
package com.central.device.parser;
import com.central.device.parser.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* KMZ文件解析器
* 解析大疆无人机航线文件(KMZ格式),提取航点和动作数据
*
* @author dzc
* @date 2025-12-17
*/
@Component
@Slf4j
public class KmzFileParser {
/**
* 解析KMZ文件
*
* @param kmzBytes KMZ文件字节数组
* @return 解析结果
*/
public KmzParseResult parseKmz(byte[] kmzBytes) {
try {
// 1. 解压KMZ文件
Map<String, byte[]> extractedFiles = unzipKmz(kmzBytes);
// 2. 解析template.kml获取主要信息
byte[] templateKml = extractedFiles.get("wpmz/template.kml");
if (templateKml == null) {
return KmzParseResult.builder()
.success(false)
.errorMessage("template.kml文件不存在")
.build();
}
KmzParseResult result = parseTemplateKml(templateKml);
// 3. 使用任务配置中的autoFlightSpeed填充航点速度
fillWaypointSpeedsFromMissionConfig(result);
// 4. 解析waylines.wpml获取补充信息
byte[] waylinesWpml = extractedFiles.get("wpmz/waylines.wpml");
if (waylinesWpml != null) {
enrichWithWpmlData(result, waylinesWpml);
}
// 5. 如果没有从XML获取到数据,则计算航程和时长
if (result.getTotalDistance() == null || result.getTotalDuration() == null) {
calculateDistanceAndDuration(result);
}
result.setSuccess(true);
return result;
} catch (Exception e) {
log.error("解析KMZ文件失败", e);
return KmzParseResult.builder()
.success(false)
.errorMessage("解析失败: " + e.getMessage())
.build();
}
}
/**
* 解压KMZ文件
*/
private Map<String, byte[]> unzipKmz(byte[] kmzBytes) throws IOException {
Map<String, byte[]> files = new HashMap<>();
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(kmzBytes))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory()) {
byte[] content = zis.readAllBytes();
files.put(entry.getName(), content);
}
zis.closeEntry();
}
}
return files;
}
/**
* 解析template.kml文件
*/
private KmzParseResult parseTemplateKml(byte[] kmlBytes) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(kmlBytes));
KmzParseResult.KmzParseResultBuilder resultBuilder = KmzParseResult.builder();
List<WaypointData> waypoints = new ArrayList<>();
List<ActionData> actions = new ArrayList<>();
// 解析任务配置
MissionConfig missionConfig = parseMissionConfig(document);
resultBuilder.missionConfig(missionConfig);
// 解析航点
NodeList placemarks = document.getElementsByTagName("Placemark");
for (int i = 0; i < placemarks.getLength(); i++) {
Node placemarkNode = placemarks.item(i);
if (placemarkNode.getNodeType() == Node.ELEMENT_NODE) {
Element placemarkElement = (Element) placemarkNode;
WaypointData waypoint = parseWaypoint(placemarkElement);
if (waypoint != null) {
waypoints.add(waypoint);
// 解析该航点的动作
List<ActionData> waypointActions = parseActions(placemarkElement, waypoint.getIndex());
actions.addAll(waypointActions);
}
}
}
// 设置航点动作关联
for (WaypointData waypoint : waypoints) {
waypoint.setActions(new ArrayList<>());
for (ActionData action : actions) {
if (action.getWaypointIndex().equals(waypoint.getIndex())) {
waypoint.getActions().add(action);
}
}
}
// 4. 从XML中读取距离和时长信息
extractDistanceAndDuration(resultBuilder, document);
return resultBuilder
.waypoints(waypoints)
.actions(actions)
.build();
}
/**
* 解析任务配置
*/
private MissionConfig parseMissionConfig(Document document) {
MissionConfig.MissionConfigBuilder configBuilder = MissionConfig.builder();
NodeList missionConfigs = document.getElementsByTagName("wpml:missionConfig");
if (missionConfigs.getLength() > 0) {
Element missionConfigElement = (Element) missionConfigs.item(0);
configBuilder
.flyToWaylineMode(getElementText(missionConfigElement, "wpml:flyToWaylineMode"))
.finishAction(getElementText(missionConfigElement, "wpml:finishAction"))
.takeOffSecurityHeight(getElementBigDecimal(missionConfigElement, "wpml:takeOffSecurityHeight"))
.globalRthHeight(getElementBigDecimal(missionConfigElement, "wpml:globalRTHHeight"))
.exitOnRcLost(getElementText(missionConfigElement, "wpml:exitOnRcLost"))
.coordinateMode(getElementText(missionConfigElement, "wpml:coordinateMode"))
.heightMode(getElementText(missionConfigElement, "wpml:heightMode"));
}
// 解析模板类型
NodeList templateTypes = document.getElementsByTagName("wpml:templateType");
if (templateTypes.getLength() > 0) {
configBuilder.templateType(templateTypes.item(0).getTextContent());
}
// 解析自动飞行速度
NodeList autoFlightSpeeds = document.getElementsByTagName("wpml:autoFlightSpeed");
if (autoFlightSpeeds.getLength() > 0) {
String speedText = autoFlightSpeeds.item(0).getTextContent();
try {
configBuilder.autoFlightSpeed(new BigDecimal(speedText));
} catch (NumberFormatException e) {
log.warn("解析自动飞行速度失败: {}", speedText);
}
}
return configBuilder.build();
}
/**
* 解析航点
*/
private WaypointData parseWaypoint(Element placemarkElement) {
WaypointData.WaypointDataBuilder waypointBuilder = WaypointData.builder();
// 获取航点序号
String indexText = getElementText(placemarkElement, "wpml:index");
if (indexText == null) {
return null;
}
Integer index = Integer.parseInt(indexText);
waypointBuilder.index(index);
// 获取坐标
String coordinates = getElementText(placemarkElement, "coordinates");
if (coordinates != null) {
String[] coords = coordinates.split(",");
if (coords.length >= 2) {
waypointBuilder
.longitude(new BigDecimal(coords[0]))
.latitude(new BigDecimal(coords[1]));
}
}
// 获取高度信息
waypointBuilder
.height(getElementBigDecimal(placemarkElement, "wpml:height"))
.executeHeight(getElementBigDecimal(placemarkElement, "wpml:executeHeight"))
.ellipsoidHeight(getElementBigDecimal(placemarkElement, "wpml:ellipsoidHeight"));
// 获取飞行参数
waypointBuilder
.speed(getElementBigDecimal(placemarkElement, "wpml:waypointSpeed"))
.headingAngle(getElementBigDecimal(placemarkElement, "wpml:waypointHeadingAngle"))
.gimbalPitchAngle(getElementBigDecimal(placemarkElement, "wpml:gimbalPitchAngle"))
.gimbalRollAngle(getElementBigDecimal(placemarkElement, "wpml:gimbalRollAngle"))
.gimbalYawAngle(getElementBigDecimal(placemarkElement, "wpml:gimbalYawAngle"));
// 获取转弯信息
waypointBuilder
.turnMode(getElementText(placemarkElement, "wpml:turnMode"))
.turnDampingDist(getElementBigDecimal(placemarkElement, "wpml:turnDampingDist"))
.useStraightLine(getElementBoolean(placemarkElement, "wpml:useStraightLine", true))
.isRisky(getElementBoolean(placemarkElement, "wpml:isRisky", false));
// 统计动作组数量
NodeList actionGroups = placemarkElement.getElementsByTagName("wpml:actionGroup");
waypointBuilder.actionGroupCount(actionGroups.getLength());
return waypointBuilder.build();
}
/**
* 解析动作
*/
private List<ActionData> parseActions(Element placemarkElement, Integer waypointIndex) {
List<ActionData> actions = new ArrayList<>();
NodeList actionGroups = placemarkElement.getElementsByTagName("wpml:actionGroup");
for (int groupIndex = 0; groupIndex < actionGroups.getLength(); groupIndex++) {
Element actionGroupElement = (Element) actionGroups.item(groupIndex);
NodeList actionNodes = actionGroupElement.getElementsByTagName("wpml:action");
for (int actionIndex = 0; actionIndex < actionNodes.getLength(); actionIndex++) {
Element actionElement = (Element) actionNodes.item(actionIndex);
ActionData.ActionDataBuilder actionBuilder = ActionData.builder()
.waypointIndex(waypointIndex)
.actionGroupId(groupIndex)
.actionIndex(actionIndex);
// 获取动作类型
String actionType = getElementText(actionElement, "wpml:actionActuatorFunc");
actionBuilder.actionType(actionType);
// 解析动作参数
Map<String, Object> actionParams = new HashMap<>();
// 通用参数
actionBuilder
.payloadPositionIndex(getElementInteger(actionElement, "wpml:payloadParamIndex"))
.triggerType(getElementText(actionGroupElement, "wpml:triggerType"));
// 根据动作类型解析特定参数
parseActionSpecificParams(actionElement, actionBuilder, actionParams, actionType);
actionBuilder.actionParams(actionParams);
actions.add(actionBuilder.build());
}
}
return actions;
}
/**
* 解析动作特定参数
*/
private void parseActionSpecificParams(Element actionElement, ActionData.ActionDataBuilder actionBuilder, Map<String, Object> actionParams, String actionType) {
if ("hover".equals(actionType)) {
Double hoverTime = getElementDouble(actionElement, "wpml:hoverTime");
actionBuilder.hoverTime(hoverTime);
if (hoverTime != null) {
actionParams.put("hoverTime", hoverTime);
}
} else if ("rotateYaw".equals(actionType)) {
Double aircraftHeading = getElementDouble(actionElement, "wpml:aircraftHeading");
actionBuilder.aircraftHeading(aircraftHeading);
if (aircraftHeading != null) {
actionParams.put("heading", aircraftHeading);
}
} else if ("gimbalRotate".equals(actionType)) {
Double gimbalPitchRotateAngle = getElementDouble(actionElement, "wpml:gimbalPitchRotateAngle");
Double gimbalRollRotateAngle = getElementDouble(actionElement, "wpml:gimbalRollRotateAngle");
Double gimbalYawRotateAngle = getElementDouble(actionElement, "wpml:gimbalYawRotateAngle");
Double gimbalRotateSpeed = getElementDouble(actionElement, "wpml:gimbalRotateSpeed");
actionBuilder
.gimbalPitchRotateAngle(gimbalPitchRotateAngle)
.gimbalRollRotateAngle(gimbalRollRotateAngle)
.gimbalYawRotateAngle(gimbalYawRotateAngle)
.gimbalRotateSpeed(gimbalRotateSpeed);
if (gimbalPitchRotateAngle != null) {
actionParams.put("pitch", gimbalPitchRotateAngle);
}
if (gimbalYawRotateAngle != null) {
actionParams.put("yaw", gimbalYawRotateAngle);
}
} else if ("zoom".equals(actionType)) {
Double focalLength = getElementDouble(actionElement, "wpml:focalLength");
actionBuilder.focalLength(focalLength);
if (focalLength != null) {
actionParams.put("focalLength", focalLength);
}
} else if ("megaphone".equals(actionType)) {
String filePath = getElementText(actionElement, "wpml:megaphoneOperateFilePath");
actionBuilder.megaphoneFilePath(filePath);
if (filePath != null) {
actionParams.put("filePath", filePath);
}
}
// 拍照和录像的参数
String photoFileFormat = getElementText(actionElement, "wpml:photoFileFormat");
if (photoFileFormat != null) {
actionBuilder.photoFileFormat(photoFileFormat);
actionParams.put("fileFormat", photoFileFormat);
}
String videoFileFormat = getElementText(actionElement, "wpml:videoFileFormat");
if (videoFileFormat != null) {
actionBuilder.videoFileFormat(videoFileFormat);
actionParams.put("fileFormat", videoFileFormat);
}
}
/**
* 从XML中提取距离和时长信息
*/
private void extractDistanceAndDuration(KmzParseResult.KmzParseResultBuilder resultBuilder, Document document) {
// 尝试从多个位置提取距离和时长
// 1. 从 Folder/Document 中提取
NodeList folders = document.getElementsByTagName("Folder");
if (folders.getLength() > 0) {
Element folderElement = (Element) folders.item(0);
// 提取距离
String distanceText = getElementText(folderElement, "wpml:distance");
if (distanceText != null && !distanceText.isEmpty()) {
try {
resultBuilder.totalDistance(Double.parseDouble(distanceText));
log.info("从XML中提取到距离: {}", distanceText);
} catch (NumberFormatException e) {
log.warn("解析距离失败: {}", distanceText);
}
}
// 提取时长
String durationText = getElementText(folderElement, "wpml:duration");
if (durationText != null && !durationText.isEmpty()) {
try {
resultBuilder.totalDuration(Double.parseDouble(durationText));
log.info("从XML中提取到时长: {}", durationText);
} catch (NumberFormatException e) {
log.warn("解析时长失败: {}", durationText);
}
}
}
// 2. 从 Document 根节点直接提取
if (document.getDocumentElement() != null) {
Element docElement = document.getDocumentElement();
// 尝试其他可能的标签名称
String[] distanceTags = {"distance", "wpml:distance", "totalDistance"};
String[] durationTags = {"duration", "wpml:duration", "totalDuration"};
for (String tag : distanceTags) {
String distanceText = getElementText(docElement, tag);
if (distanceText != null && !distanceText.isEmpty()) {
try {
resultBuilder.totalDistance(Double.parseDouble(distanceText));
log.info("从根节点提取到距离: {}", distanceText);
break;
} catch (NumberFormatException e) {
log.debug("解析距离失败: tag={}, value={}", tag, distanceText);
}
}
}
for (String tag : durationTags) {
String durationText = getElementText(docElement, tag);
if (durationText != null && !durationText.isEmpty()) {
try {
resultBuilder.totalDuration(Double.parseDouble(durationText));
log.info("从根节点提取到时长: {}", durationText);
break;
} catch (NumberFormatException e) {
log.debug("解析时长失败: tag={}, value={}", tag, durationText);
}
}
}
}
// 3. 从所有子节点中搜索
NodeList allNodes = document.getElementsByTagName("*");
for (int i = 0; i < allNodes.getLength(); i++) {
Element element = (Element) allNodes.item(i);
// 查找包含"duration"文本的节点
if (resultBuilder.build().getTotalDuration() == null) {
String nodeName = element.getNodeName().toLowerCase();
String durationText = element.getTextContent().trim();
// 只从明确表示持续时间的节点中提取
boolean isDurationNode = (nodeName.contains("duration") &&
!nodeName.contains("timestamp") &&
!nodeName.contains("time")) ||
nodeName.equals("wpml:duration");
if (isDurationNode && durationText.matches(".*\\d+\\.?\\d*.*")) {
try {
// 尝试提取数字
String numStr = durationText.replaceAll("[^\\d.]", "");
// 过滤掉时间戳(通常大于10^10)
if (!numStr.isEmpty()) {
double value = Double.parseDouble(numStr);
// 只接受合理的持续时间值(秒),过滤掉时间戳(毫秒)
if (value < 100000) { // 100000秒约等于27小时,作为合理上限
resultBuilder.totalDuration(value);
log.info("从文本内容提取到时长: {}", value);
} else {
log.debug("忽略时间戳值: {}", value);
}
}
} catch (NumberFormatException e) {
log.debug("从文本解析时长失败: {}", durationText);
}
}
}
}
}
/**
* 使用任务配置中的autoFlightSpeed填充航点速度
*/
private void fillWaypointSpeedsFromMissionConfig(KmzParseResult result) {
if (result.getMissionConfig() == null || result.getMissionConfig().getAutoFlightSpeed() == null) {
log.debug("任务配置中没有autoFlightSpeed,跳过航点速度填充");
return;
}
BigDecimal autoFlightSpeed = result.getMissionConfig().getAutoFlightSpeed();
List<WaypointData> waypoints = result.getWaypoints();
if (waypoints != null && !waypoints.isEmpty()) {
int updatedCount = 0;
for (WaypointData waypoint : waypoints) {
// 只有当航点没有设置速度时,才使用autoFlightSpeed
if (waypoint.getSpeed() == null) {
waypoint.setSpeed(autoFlightSpeed);
updatedCount++;
}
}
log.info("使用autoFlightSpeed({})填充了{}个航点的速度", autoFlightSpeed, updatedCount);
}
}
/**
* 使用WPML数据丰富解析结果
*/
private void enrichWithWpmlData(KmzParseResult result, byte[] wpmlBytes) {
// TODO: 解析waylines.wpml文件,补充执行高度等信息
// 这里可以根据需要实现WPML格式的解析
log.debug("解析waylines.wpml文件,大小: {} bytes", wpmlBytes.length);
}
/**
* 计算航程和时长
*/
private void calculateDistanceAndDuration(KmzParseResult result) {
List<WaypointData> waypoints = result.getWaypoints();
if (waypoints == null || waypoints.size() < 2) {
return;
}
double totalDistance = 0;
double totalDuration = 0;
// 获取默认飞行速度(优先使用任务配置中的autoFlightSpeed)
BigDecimal defaultSpeed = BigDecimal.valueOf(1.0); // 默认1m/s
if (result.getMissionConfig() != null && result.getMissionConfig().getAutoFlightSpeed() != null) {
defaultSpeed = result.getMissionConfig().getAutoFlightSpeed();
log.debug("使用任务配置中的autoFlightSpeed作为默认速度: {}", defaultSpeed);
}
// 首先计算所有航点的动作时间总和
double totalActionTime = 0;
for (WaypointData waypoint : waypoints) {
if (waypoint.getActions() != null && !waypoint.getActions().isEmpty()) {
for (ActionData action : waypoint.getActions()) {
if ("hover".equals(action.getActionType()) && action.getHoverTime() != null) {
totalActionTime += action.getHoverTime();
}
}
}
}
// 计算总飞行距离
double totalFlyDistance = 0;
for (int i = 1; i < waypoints.size(); i++) {
WaypointData prev = waypoints.get(i - 1);
WaypointData curr = waypoints.get(i);
// 计算两航点间的距离
double distance = calculateDistance(
prev.getLongitude().doubleValue(),
prev.getLatitude().doubleValue(),
curr.getLongitude().doubleValue(),
curr.getLatitude().doubleValue()
);
totalFlyDistance += distance;
}
// 计算飞行时间(使用平均速度)
double avgSpeed = defaultSpeed.doubleValue();
// 计算所有设置了速度的航点的平均速度
double speedSum = 0;
int speedCount = 0;
for (WaypointData waypoint : waypoints) {
if (waypoint.getSpeed() != null) {
speedSum += waypoint.getSpeed().doubleValue();
speedCount++;
}
}
if (speedCount > 0) {
avgSpeed = speedSum / speedCount;
}
// 飞行时间 = 距离 / 平均速度
double flyTime = avgSpeed > 0 ? totalFlyDistance / avgSpeed : 0;
// 总时长 = 飞行时间 + 动作时间
totalDuration = flyTime + totalActionTime;
totalDistance = totalFlyDistance;
result.setTotalDistance(totalDistance);
result.setTotalDuration(totalDuration);
// 添加调试日志
log.info("解析完成 - 航点数: {}, 总距离: {}米, 总时长: {}秒",
waypoints.size(), totalDistance, totalDuration);
}
/**
* 计算两点间距离(Haversine公式)
*/
private double calculateDistance(double lng1, double lat1, double lng2, double lat2) {
final double R = 6371000; // 地球半径(米)
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
// 辅助方法
private String getElementText(Element parent, String tagName) {
NodeList nodes = parent.getElementsByTagName(tagName);
if (nodes.getLength() > 0) {
return nodes.item(0).getTextContent().trim();
}
return null;
}
private BigDecimal getElementBigDecimal(Element parent, String tagName) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
try {
return new BigDecimal(text);
} catch (NumberFormatException e) {
log.warn("解析BigDecimal失败: {} = {}", tagName, text);
}
}
return null;
}
private Integer getElementInteger(Element parent, String tagName) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
log.warn("解析Integer失败: {} = {}", tagName, text);
}
}
return null;
}
private Double getElementDouble(Element parent, String tagName) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
try {
return Double.parseDouble(text);
} catch (NumberFormatException e) {
log.warn("解析Double失败: {} = {}", tagName, text);
}
}
return null;
}
private Boolean getElementBoolean(Element parent, String tagName, Boolean defaultValue) {
String text = getElementText(parent, tagName);
if (text != null && !text.isEmpty()) {
return Boolean.parseBoolean(text);
}
return defaultValue;
}
}
@@ -0,0 +1,106 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.util.Map;
/**
* 动作数据
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class ActionData {
/**
* 航点序号
*/
private Integer waypointIndex;
/**
* 动作组ID
*/
private Integer actionGroupId;
/**
* 动作序号(组内)
*/
private Integer actionIndex;
/**
* 动作类型
*/
private String actionType;
/**
* 动作参数
*/
private Map<String, Object> actionParams;
/**
* 触发类型
*/
private String triggerType;
/**
* 延迟时间(毫秒)
*/
private Long delayTime;
/**
* 相机位置索引
*/
private Integer payloadPositionIndex;
/**
* 拍照相关参数
*/
private String photoFileFormat;
/**
* 录像相关参数
*/
private String videoFileFormat;
/**
* 云台俯仰旋转角度
*/
private Double gimbalPitchRotateAngle;
/**
* 云台横滚旋转角度
*/
private Double gimbalRollRotateAngle;
/**
* 云台偏航旋转角度
*/
private Double gimbalYawRotateAngle;
/**
* 云台旋转速度
*/
private Double gimbalRotateSpeed;
/**
* 飞机航向角
*/
private Double aircraftHeading;
/**
* 悬停时间(秒)
*/
private Double hoverTime;
/**
* 焦距(毫米)
*/
private Double focalLength;
/**
* 音频文件路径
*/
private String megaphoneFilePath;
}
@@ -0,0 +1,51 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.util.List;
/**
* KMZ文件解析结果
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class KmzParseResult {
/**
* 任务配置
*/
private MissionConfig missionConfig;
/**
* 航点列表
*/
private List<WaypointData> waypoints;
/**
* 动作列表
*/
private List<ActionData> actions;
/**
* 解析错误信息
*/
private String errorMessage;
/**
* 解析是否成功
*/
private boolean success;
/**
* 总航程(米)
*/
private Double totalDistance;
/**
* 总时长(秒)
*/
private Double totalDuration;
}
@@ -0,0 +1,71 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.math.BigDecimal;
/**
* 任务配置
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class MissionConfig {
/**
* 飞往航线模式
*/
private String flyToWaylineMode;
/**
* 完成动作
*/
private String finishAction;
/**
* 起飞安全高度
*/
private BigDecimal takeOffSecurityHeight;
/**
* 全局返航高度
*/
private BigDecimal globalRthHeight;
/**
* 遥控器失联动作
*/
private String exitOnRcLost;
/**
* 坐标系
*/
private String coordinateMode;
/**
* 高度模式
*/
private String heightMode;
/**
* 自动飞行速度
*/
private BigDecimal autoFlightSpeed;
/**
* 无人机信息
*/
private String droneInfo;
/**
* 载荷信息
*/
private String payloadInfo;
/**
* 模板类型
*/
private String templateType;
}
@@ -0,0 +1,107 @@
package com.central.device.parser.model;
import lombok.Data;
import lombok.Builder;
import java.math.BigDecimal;
import java.util.List;
/**
* 航点数据
*
* @author dzc
* @date 2025-12-17
*/
@Data
@Builder
public class WaypointData {
/**
* 航点序号
*/
private Integer index;
/**
* 经度
*/
private BigDecimal longitude;
/**
* 纬度
*/
private BigDecimal latitude;
/**
* 相对高度(米)
*/
private BigDecimal height;
/**
* 执行高度(米)
*/
private BigDecimal executeHeight;
/**
* 椭球高度(米)
*/
private BigDecimal ellipsoidHeight;
/**
* 飞行速度(米/秒)
*/
private BigDecimal speed;
/**
* 航向模式
*/
private String headingMode;
/**
* 航向角(度)
*/
private BigDecimal headingAngle;
/**
* 云台俯仰角(度)
*/
private BigDecimal gimbalPitchAngle;
/**
* 云台横滚角(度)
*/
private BigDecimal gimbalRollAngle;
/**
* 云台偏航角(度)
*/
private BigDecimal gimbalYawAngle;
/**
* 转弯模式
*/
private String turnMode;
/**
* 转弯阻尼距离(米)
*/
private BigDecimal turnDampingDist;
/**
* 是否使用直线飞行
*/
private Boolean useStraightLine;
/**
* 是否为风险点
*/
private Boolean isRisky;
/**
* 动作组数量
*/
private Integer actionGroupCount;
/**
* 动作列表
*/
private List<ActionData> actions;
}
@@ -0,0 +1,76 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.DroneFlightTrack;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IDroneFlightTrackService extends IService<DroneFlightTrack> {
/**
* 记录轨迹点
*
* @param track 轨迹点数据
* @return 是否成功
*/
boolean recordTrackPoint(DroneFlightTrack track);
/**
* 批量记录轨迹点
*
* @param tracks 轨迹点列表
* @return 成功数量
*/
int batchRecordTrackPoints(List<DroneFlightTrack> tracks);
/**
* 获取设备飞行轨迹
*
* @param deviceSn 设备SN
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @param limit 限制数量(可选)
* @return 轨迹点列表
*/
List<DroneFlightTrack> getTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime, Integer limit);
/**
* 获取设备最新轨迹点
*
* @param deviceSn 设备SN
* @return 最新轨迹点
*/
DroneFlightTrack getLatestTrackPoint(String deviceSn);
/**
* 删除指定时间之前的轨迹
*
* @param deviceSn 设备SN
* @param beforeTime 删除此时间之前的轨迹
* @return 删除数量
*/
int deleteTrackPointsBefore(String deviceSn, LocalDateTime beforeTime);
/**
* 统计轨迹点数量
*
* @param deviceSn 设备SN(可选)
* @param jobId 任务ID(可选)
* @param routeId 航线任务ID(可选)
* @param startTime 开始时间(可选)
* @param endTime 结束时间(可选)
* @return 轨迹点数量
*/
Long countTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime);
}
@@ -0,0 +1,46 @@
package com.central.device.service;
import com.central.device.parser.model.KmzParseResult;
import com.central.device.model.vo.WaypointActionVO;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* 航线解析服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IWaylineParseService {
/**
* 解析航线任务
*
* @param routeId 航线任务ID
* @return 解析结果
*/
KmzParseResult parseRoute(String routeId);
/**
* 异步解析航线任务
*
* @param routeId 航线任务ID
* @return CompletableFuture
*/
CompletableFuture<Void> parseRouteAsync(String routeId);
/**
* 批量解析航线任务
*
* @param routeIds 航线任务ID列表
*/
void batchParseRoutes(String... routeIds);
/**
* 根据航线ID获取动作列表
*
* @param routeId 航线任务ID
* @return 动作列表
*/
List<WaypointActionVO> getActionsByRouteId(String routeId);
}
@@ -0,0 +1,90 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaylineRoute;
import java.util.List;
/**
* 航线任务服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IWaylineRouteService extends IService<WaylineRoute> {
/**
* 根据航迹文件ID查询航线任务列表
*
* @param fileWaylineId 航迹文件ID
* @return 航线任务列表
*/
List<WaylineRoute> listByFileWaylineId(String fileWaylineId);
/**
* 根据设备SN查询绑定的航线任务列表
*
* @param deviceSn 设备SN
* @return 航线任务列表
*/
List<WaylineRoute> listByDeviceSn(String deviceSn);
/**
* 根据航线任务ID查询
*
* @param routeId 航线任务ID
* @return 航线任务
*/
WaylineRoute getByRouteId(String routeId);
/**
* 创建航线任务
*
* @param routeName 航线任务名称
* @param fileWaylineId 航迹文件ID
* @param deviceSn 设备SN
* @param deviceName 设备名称
* @param remark 备注
* @return 创建的航线任务
*/
WaylineRoute createRoute(String routeName, String fileWaylineId, String deviceSn, String deviceName, String remark);
/**
* 更新解析状态
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
*/
void updateParseStatus(String routeId, Integer parseStatus);
/**
* 更新解析状态和错误信息
*
* @param routeId 航线任务ID
* @param parseStatus 解析状态
* @param parseError 解析错误信息
*/
void updateParseStatus(String routeId, Integer parseStatus, String parseError);
/**
* 更新航线任务统计信息
*
* @param routeId 航线任务ID
* @param waypointCount 航点数量
* @param actionCount 动作数量
* @param totalDistance 总航程
* @param totalDuration 总时长
*/
void updateRouteStats(String routeId, Integer waypointCount, Integer actionCount,
Double totalDistance, Double totalDuration);
/**
* 绑定航迹文件到设备并解析
*
* @param deviceSn 设备SN
* @param waylineId 航线ID
* @param waylineName 航线名称
* @param workspaceId 工作空间ID
*/
void bindWaylineToDevice(String deviceSn, String waylineId, String waylineName, String workspaceId);
}
@@ -0,0 +1,39 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaylineWaypoint;
import java.util.List;
/**
* 航点服务接口
*
* @author dzc
* @date 2025-12-17
*/
public interface IWaylineWaypointService extends IService<WaylineWaypoint> {
/**
* 根据航线任务ID查询航点列表(按序号排序)
*
* @param routeId 航线任务ID
* @return 航点列表
*/
List<WaylineWaypoint> listByRouteIdOrderByIndex(String routeId);
/**
* 根据航线任务ID删除航点
*
* @param routeId 航线任务ID
* @return 删除数量
*/
int deleteByRouteId(String routeId);
/**
* 统计航点数量
*
* @param routeId 航线任务ID
* @return 航点数量
*/
Integer countByRouteId(String routeId);
}
@@ -0,0 +1,156 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.mapper.DroneFlightTrackMapper;
import com.central.device.service.IDroneFlightTrackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 飞行轨迹服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
@Slf4j
public class DroneFlightTrackServiceImpl extends ServiceImpl<DroneFlightTrackMapper, DroneFlightTrack> implements IDroneFlightTrackService {
@Override
public boolean recordTrackPoint(DroneFlightTrack track) {
try {
// 设置记录时间
if (track.getRecordTime() == null) {
track.setRecordTime(LocalDateTime.now());
}
return save(track);
} catch (Exception e) {
log.error("记录轨迹点失败: deviceSn={}", track.getDeviceSn(), e);
return false;
}
}
@Override
public int batchRecordTrackPoints(List<DroneFlightTrack> tracks) {
if (tracks == null || tracks.isEmpty()) {
return 0;
}
try {
// 设置记录时间
LocalDateTime now = LocalDateTime.now();
tracks.forEach(track -> {
if (track.getRecordTime() == null) {
track.setRecordTime(now);
}
});
return baseMapper.batchInsert(tracks);
} catch (Exception e) {
log.error("批量记录轨迹点失败", e);
return 0;
}
}
@Override
public List<DroneFlightTrack> getTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime, Integer limit) {
try {
return baseMapper.selectTrackPoints(deviceSn, jobId, routeId, startTime, endTime, limit);
} catch (Exception e) {
log.error("获取轨迹点失败: deviceSn={}, jobId={}", deviceSn, jobId, e);
return null;
}
}
@Override
public DroneFlightTrack getLatestTrackPoint(String deviceSn) {
try {
return baseMapper.selectLatestTrackPoint(deviceSn);
} catch (Exception e) {
log.error("获取最新轨迹点失败: deviceSn={}", deviceSn, e);
return null;
}
}
@Override
public int deleteTrackPointsBefore(String deviceSn, LocalDateTime beforeTime) {
try {
return baseMapper.deleteByDeviceSnAndTimeBefore(deviceSn, beforeTime);
} catch (Exception e) {
log.error("删除历史轨迹失败: deviceSn={}, beforeTime={}", deviceSn, beforeTime, e);
return 0;
}
}
@Override
public Long countTrackPoints(String deviceSn, String jobId, String routeId,
LocalDateTime startTime, LocalDateTime endTime) {
try {
return baseMapper.countTrackPoints(deviceSn, jobId, routeId, startTime, endTime);
} catch (Exception e) {
log.error("统计轨迹点数量失败", e);
return 0L;
}
}
/**
* 从无人机OSD数据构建轨迹点
*
* @param deviceSn 设备SN
* @param osdData OSD数据
* @param jobId 任务ID
* @param routeId 航线任务ID
* @return 轨迹点
*/
public DroneFlightTrack buildTrackFromOsd(String deviceSn, Object osdData, String jobId, String routeId) {
DroneFlightTrack track = new DroneFlightTrack();
track.setDeviceSn(deviceSn);
track.setJobId(jobId);
track.setRouteId(routeId);
// TODO: 根据实际的OSD数据格式提取位置信息
// 这里需要根据实际的数据结构进行解析
try {
// 示例代码,需要根据实际情况调整
if (osdData instanceof com.alibaba.fastjson.JSONObject) {
com.alibaba.fastjson.JSONObject json = (com.alibaba.fastjson.JSONObject) osdData;
// 提取位置信息
track.setLongitude(json.getBigDecimal("longitude"));
track.setLatitude(json.getBigDecimal("latitude"));
track.setAltitude(json.getBigDecimal("elevation"));
track.setHeight(json.getBigDecimal("height"));
// 提取速度信息
track.setHorizontalSpeed(json.getBigDecimal("horizontal_speed"));
track.setVerticalSpeed(json.getBigDecimal("vertical_speed"));
// 提取姿态信息
track.setHeading(json.getBigDecimal("attitude_head"));
track.setPitch(json.getBigDecimal("attitude_pitch"));
track.setRoll(json.getBigDecimal("attitude_roll"));
// 其他信息
track.setFlightMode(json.getInteger("flight_mode"));
track.setBatteryPercent(json.getInteger("battery_percent"));
// 记录时间
if (json.containsKey("timestamp")) {
Long timestamp = json.getLong("timestamp");
track.setRecordTime(LocalDateTime.now()); // 实际应该转换timestamp
}
}
} catch (Exception e) {
log.warn("解析OSD数据失败", e);
}
return track;
}
}
@@ -0,0 +1,386 @@
package com.central.device.service.impl;
import com.central.device.entity.WaylineAction;
import com.central.device.entity.WaylineRoute;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.feign.FileCenterService;
import com.central.device.mapper.WaylineActionMapper;
import com.central.device.mapper.WaylineRouteMapper;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.parser.KmzFileParser;
import com.central.device.parser.model.ActionData;
import com.central.device.parser.model.KmzParseResult;
import com.central.device.parser.model.WaypointData;
import com.central.device.service.IWaylineParseService;
import com.central.device.service.ILineFileService;
import com.central.device.model.LineFile;
import com.central.device.model.vo.WaypointActionVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* 航线解析服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
@Slf4j
public class WaylineParseServiceImpl implements IWaylineParseService {
@Autowired
private WaylineRouteMapper waylineRouteMapper;
@Autowired
private WaylineWaypointMapper waylineWaypointMapper;
@Autowired
private WaylineActionMapper waylineActionMapper;
@Autowired
private KmzFileParser kmzFileParser;
@Autowired
private ILineFileService lineFileService;
@Resource
private FileCenterService fileCenterService;
@Autowired
private ObjectMapper objectMapper;
@Override
@Transactional
public KmzParseResult parseRoute(String routeId) {
try {
// 1. 获取航线任务信息
WaylineRoute route = waylineRouteMapper.selectByRouteId(routeId);
if (route == null) {
throw new RuntimeException("航线任务不存在: " + routeId);
}
// 2. 更新状态为解析中
waylineRouteMapper.updateParseStatus(routeId, WaylineRoute.ParseStatus.PARSING.getCode());
// 3. 下载并解析KMZ文件
byte[] kmzBytes = downloadKmzFile(route.getFileWaylineId());
if (kmzBytes == null || kmzBytes.length == 0) {
throw new RuntimeException("KMZ文件下载失败或为空");
}
// 4. 解析KMZ文件
KmzParseResult parseResult = kmzFileParser.parseKmz(kmzBytes);
if (!parseResult.isSuccess()) {
throw new RuntimeException("KMZ文件解析失败: " + parseResult.getErrorMessage());
}
// 5. 保存解析结果
saveParseResult(routeId, parseResult);
// 6. 更新统计信息
updateRouteStats(routeId, parseResult);
// 7. 更新状态为已解析
waylineRouteMapper.updateParseStatus(routeId, WaylineRoute.ParseStatus.PARSED.getCode());
log.info("航线任务解析成功: routeId={}, 航点数={}, 动作数={}",
routeId, parseResult.getWaypoints().size(), parseResult.getActions().size());
return parseResult;
} catch (Exception e) {
log.error("解析航线任务失败: routeId={}", routeId, e);
waylineRouteMapper.updateParseStatusWithError(
routeId,
WaylineRoute.ParseStatus.FAILED.getCode(),
e.getMessage()
);
throw new RuntimeException("解析失败: " + e.getMessage(), e);
}
}
@Override
@Async("waylineParseExecutor")
public CompletableFuture<Void> parseRouteAsync(String routeId) {
try {
parseRoute(routeId);
return CompletableFuture.completedFuture(null);
} catch (Exception e) {
log.error("异步解析航线任务失败: routeId={}", routeId, e);
return CompletableFuture.failedFuture(e);
}
}
@Override
@Async("waylineParseExecutor")
public void batchParseRoutes(String... routeIds) {
if (routeIds == null || routeIds.length == 0) {
return;
}
log.info("开始批量解析航线任务,数量: {}", routeIds.length);
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (String routeId : routeIds) {
CompletableFuture<Void> future = parseRouteAsync(routeId);
futures.add(future);
}
// 等待所有任务完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenRun(() -> log.info("批量解析航线任务完成"))
.exceptionally(e -> {
log.error("批量解析航线任务出现异常", e);
return null;
});
}
/**
* 下载KMZ文件
*/
private byte[] downloadKmzFile(String fileWaylineId) {
try {
// 根据fileWaylineId从wayline_file表获取文件信息
LineFile lineFile = lineFileService.findLineFileByWaylineId(fileWaylineId);
if (lineFile == null) {
throw new RuntimeException("航迹文件不存在: " + fileWaylineId);
}
String fileurl = fileCenterService.getFileViewUrl(lineFile.getWaylineId());
if (fileurl == null || fileurl.isEmpty()) {
throw new RuntimeException("航迹文件URL为空");
}
// 下载文件
try (InputStream in = new URL(fileurl).openStream()) {
return in.readAllBytes();
}
} catch (IOException e) {
log.error("下载KMZ文件失败: fileWaylineId={}", fileWaylineId, e);
throw new RuntimeException("下载文件失败: " + e.getMessage(), e);
}
}
/**
* 保存解析结果
*/
private void saveParseResult(String routeId, KmzParseResult parseResult) {
// 1. 清除旧的解析数据
waylineWaypointMapper.deleteByRouteId(routeId);
waylineActionMapper.deleteByRouteId(routeId);
// 2. 保存航点数据
List<WaypointData> waypointDataList = parseResult.getWaypoints();
if (waypointDataList != null && !waypointDataList.isEmpty()) {
List<WaylineWaypoint> waypoints = new ArrayList<>();
for (WaypointData data : waypointDataList) {
WaylineWaypoint waypoint = buildWaypointEntity(routeId, data);
waypoints.add(waypoint);
}
// 批量插入航点
waylineWaypointMapper.batchInsert(waypoints);
}
// 3. 保存动作数据
List<ActionData> actionDataList = parseResult.getActions();
if (actionDataList != null && !actionDataList.isEmpty()) {
// 根据航点索引获取航点ID
List<WaylineWaypoint> waypointEntities = waylineWaypointMapper.selectByRouteIdOrderByIndex(routeId);
Map<Integer, Long> waypointIndexToIdMap = new HashMap<>();
for (WaylineWaypoint waypoint : waypointEntities) {
waypointIndexToIdMap.put(waypoint.getWaypointIndex(), waypoint.getId());
}
List<WaylineAction> actions = new ArrayList<>();
for (ActionData data : actionDataList) {
WaylineAction action = buildActionEntity(routeId, data, waypointIndexToIdMap);
if (action != null) {
actions.add(action);
}
}
// 批量插入动作
waylineActionMapper.batchInsert(actions);
}
}
/**
* 构建航点实体
*/
private WaylineWaypoint buildWaypointEntity(String routeId, WaypointData data) {
WaylineWaypoint waypoint = new WaylineWaypoint();
waypoint.setRouteId(routeId);
waypoint.setWaypointIndex(data.getIndex());
waypoint.setLongitude(data.getLongitude());
waypoint.setLatitude(data.getLatitude());
waypoint.setHeight(data.getHeight());
waypoint.setExecuteHeight(data.getExecuteHeight());
waypoint.setEllipsoidHeight(data.getEllipsoidHeight());
waypoint.setSpeed(data.getSpeed());
waypoint.setHeadingMode(data.getHeadingMode());
waypoint.setHeadingAngle(data.getHeadingAngle());
waypoint.setGimbalPitchAngle(data.getGimbalPitchAngle());
waypoint.setTurnMode(data.getTurnMode());
waypoint.setTurnDampingDist(data.getTurnDampingDist());
waypoint.setUseStraightLine(data.getUseStraightLine() != null && data.getUseStraightLine() ? 1 : 0);
waypoint.setIsRisky(data.getIsRisky() != null && data.getIsRisky() ? 1 : 0);
waypoint.setActionGroupCount(data.getActionGroupCount());
return waypoint;
}
/**
* 构建动作实体
*/
private WaylineAction buildActionEntity(String routeId, ActionData data, Map<Integer, Long> waypointIndexToIdMap) {
Long waypointId = waypointIndexToIdMap.get(data.getWaypointIndex());
if (waypointId == null) {
log.warn("航点ID未找到: waypointIndex={}", data.getWaypointIndex());
return null;
}
WaylineAction action = new WaylineAction();
action.setWaypointId(waypointId);
action.setRouteId(routeId);
action.setActionGroupId(data.getActionGroupId());
action.setActionIndex(data.getActionIndex());
action.setActionType(data.getActionType());
action.setTriggerType(data.getTriggerType());
// 将动作参数转换为JSON字符串
if (data.getActionParams() != null && !data.getActionParams().isEmpty()) {
try {
String paramsJson = objectMapper.writeValueAsString(data.getActionParams());
action.setActionParams(paramsJson);
} catch (Exception e) {
log.warn("动作参数序列化失败", e);
}
}
return action;
}
/**
* 更新航线任务统计信息
*/
private void updateRouteStats(String routeId, KmzParseResult parseResult) {
int waypointCount = parseResult.getWaypoints() != null ? parseResult.getWaypoints().size() : 0;
int actionCount = parseResult.getActions() != null ? parseResult.getActions().size() : 0;
Double totalDistance = parseResult.getTotalDistance();
Double totalDuration = parseResult.getTotalDuration();
// 转换Double为BigDecimal
BigDecimal distance = totalDistance != null ? BigDecimal.valueOf(totalDistance) : null;
BigDecimal duration = totalDuration != null ? BigDecimal.valueOf(totalDuration) : null;
// 获取autoFlightSpeed
BigDecimal autoFlightSpeed = null;
if (parseResult.getMissionConfig() != null && parseResult.getMissionConfig().getAutoFlightSpeed() != null) {
autoFlightSpeed = parseResult.getMissionConfig().getAutoFlightSpeed();
}
waylineRouteMapper.updateRouteStats(routeId, waypointCount, actionCount, distance, duration, autoFlightSpeed);
}
@Override
public List<WaypointActionVO> getActionsByRouteId(String routeId) {
List<WaylineAction> actions = waylineActionMapper.selectByRouteId(routeId);
List<WaypointActionVO> vos = new ArrayList<>();
if (actions != null && !actions.isEmpty()) {
for (WaylineAction action : actions) {
WaypointActionVO vo = new WaypointActionVO();
vo.setActionGroupId(action.getActionGroupId());
vo.setActionIndex(action.getActionIndex());
vo.setActionType(action.getActionType());
vo.setTriggerType(action.getTriggerType());
// 解析动作参数,从中提取其他字段
if (StringUtils.hasText(action.getActionParams())) {
try {
Map<String, Object> params = objectMapper.readValue(action.getActionParams(), Map.class);
vo.setActionParams(params);
// 从参数中提取具体字段(如果存在)
if (params.containsKey("delayTime")) {
Object delayTime = params.get("delayTime");
if (delayTime instanceof Number) {
vo.setDelayTime(((Number) delayTime).longValue());
}
}
if (params.containsKey("payloadPositionIndex")) {
Object payloadIndex = params.get("payloadPositionIndex");
if (payloadIndex instanceof Number) {
vo.setPayloadPositionIndex(((Number) payloadIndex).intValue());
}
}
if (params.containsKey("hoverTime")) {
Object hoverTime = params.get("hoverTime");
if (hoverTime instanceof Number) {
vo.setHoverTime(((Number) hoverTime).doubleValue());
}
}
if (params.containsKey("aircraftHeading")) {
Object heading = params.get("aircraftHeading");
if (heading instanceof Number) {
vo.setAircraftHeading(((Number) heading).doubleValue());
}
}
if (params.containsKey("gimbalPitchRotateAngle")) {
Object pitch = params.get("gimbalPitchRotateAngle");
if (pitch instanceof Number) {
vo.setGimbalPitchRotateAngle(((Number) pitch).doubleValue());
}
}
if (params.containsKey("gimbalYawRotateAngle")) {
Object yaw = params.get("gimbalYawRotateAngle");
if (yaw instanceof Number) {
vo.setGimbalYawRotateAngle(((Number) yaw).doubleValue());
}
}
if (params.containsKey("focalLength")) {
Object focalLength = params.get("focalLength");
if (focalLength instanceof Number) {
vo.setFocalLength(((Number) focalLength).doubleValue());
}
}
// megaphone相关的参数
if (params.containsKey("megaphoneOperateFilePath")) {
Object filePath = params.get("megaphoneOperateFilePath");
if (filePath != null) {
vo.setMegaphoneFilePath(filePath.toString());
}
} else if (params.containsKey("megaphoneFilePath")) {
Object filePath = params.get("megaphoneFilePath");
if (filePath != null) {
vo.setMegaphoneFilePath(filePath.toString());
}
}
} catch (Exception e) {
log.warn("解析动作参数失败: routeId={}, actionId={}", routeId, action.getId(), e);
}
}
vos.add(vo);
}
}
return vos;
}
}
@@ -0,0 +1,173 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.WaylineRoute;
import com.central.device.mapper.WaylineRouteMapper;
import com.central.device.mapper.WaylineActionMapper;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.mapper.DroneFlightTrackMapper;
import com.central.device.service.IWaylineRouteService;
import com.central.device.model.LineFile;
import com.central.device.service.IWaylineParseService;
import com.central.device.parser.model.KmzParseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
/**
* 航线任务服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
@Slf4j
public class WaylineRouteServiceImpl extends ServiceImpl<WaylineRouteMapper, WaylineRoute> implements IWaylineRouteService {
@Autowired
private IWaylineParseService waylineParseService;
@Autowired
private WaylineActionMapper waylineActionMapper;
@Autowired
private WaylineWaypointMapper waylineWaypointMapper;
@Autowired
private DroneFlightTrackMapper droneFlightTrackMapper;
@Override
public List<WaylineRoute> listByFileWaylineId(String fileWaylineId) {
return baseMapper.selectByFileWaylineId(fileWaylineId);
}
@Override
public List<WaylineRoute> listByDeviceSn(String deviceSn) {
return baseMapper.selectByDeviceSn(deviceSn);
}
@Override
public WaylineRoute getByRouteId(String routeId) {
return baseMapper.selectByRouteId(routeId);
}
@Override
@Transactional
public WaylineRoute createRoute(String routeName, String fileWaylineId, String deviceSn, String deviceName, String remark) {
// 创建航线任务
WaylineRoute route = new WaylineRoute();
route.setRouteId(UUID.randomUUID().toString());
route.setRouteName(routeName);
route.setFileWaylineId(fileWaylineId);
route.setDeviceSn(deviceSn);
route.setDeviceName(deviceName);
route.setRemark(remark);
// 设置默认值
route.setParseStatus(WaylineRoute.ParseStatus.NOT_PARSED.getCode());
route.setWaypointCount(0);
route.setActionCount(0);
route.setStatus(1);
route.setCoordinateMode("WGS84");
route.setHeightMode("relativeToStartPoint");
// 保存到数据库
save(route);
log.info("创建航线任务成功: routeId={}, routeName={}, deviceSn={}",
route.getRouteId(), routeName, deviceSn);
return route;
}
@Override
@Transactional
public void updateParseStatus(String routeId, Integer parseStatus) {
baseMapper.updateParseStatus(routeId, parseStatus);
}
@Override
@Transactional
public void updateParseStatus(String routeId, Integer parseStatus, String parseError) {
baseMapper.updateParseStatusWithError(routeId, parseStatus, parseError);
}
@Override
@Transactional
public void updateRouteStats(String routeId, Integer waypointCount, Integer actionCount,
Double totalDistance, Double totalDuration) {
// 转换Double为BigDecimal
BigDecimal distance = totalDistance != null ? BigDecimal.valueOf(totalDistance) : null;
BigDecimal duration = totalDuration != null ? BigDecimal.valueOf(totalDuration) : null;
baseMapper.updateRouteStats(routeId, waypointCount, actionCount, distance, duration, null);
}
@Override
@Transactional
public void bindWaylineToDevice(String deviceSn, String waylineId, String waylineName, String workspaceId) {
log.info("开始绑定航迹文件到设备: deviceSn={}, waylineId={}, waylineName={}",
deviceSn, waylineId, waylineName);
// 1. 检查并删除已存在的绑定(避免重复数据)
List<WaylineRoute> existingRoutes = baseMapper.selectByDeviceSnAndFileWaylineId(deviceSn, waylineId);
if (existingRoutes != null && !existingRoutes.isEmpty()) {
log.info("发现已存在的绑定关系,删除旧数据: deviceSn={}, waylineId={}, count={}",
deviceSn, waylineId, existingRoutes.size());
// 先删除相关的航点、动作和飞行轨迹数据
for (WaylineRoute existingRoute : existingRoutes) {
// 删除航点动作数据
waylineActionMapper.deleteByRouteId(existingRoute.getRouteId());
// 删除航点数据
waylineWaypointMapper.deleteByRouteId(existingRoute.getRouteId());
// 删除飞行轨迹数据
droneFlightTrackMapper.deleteByRouteId(existingRoute.getRouteId());
log.debug("已删除航线任务的相关数据: routeId={}", existingRoute.getRouteId());
}
// 删除航线任务
baseMapper.deleteBindingByDeviceAndWayline(deviceSn, waylineId);
}
// 2. 创建航线任务
String routeName = StringUtils.hasText(waylineName) ? waylineName : waylineName;
WaylineRoute route = createRoute(routeName, waylineId, deviceSn, null, null);
// 3. 设置工作空间ID
if (StringUtils.hasText(workspaceId)) {
route.setWorkspaceId(workspaceId);
updateById(route);
}
// 4. 解析航迹文件
try {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.PARSING.getCode());
KmzParseResult result = waylineParseService.parseRoute(route.getRouteId());
if (result.isSuccess()) {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.PARSED.getCode());
log.info("航迹文件解析成功: routeId={}, waypointCount={}",
route.getRouteId(), result.getWaypoints().size());
} else {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.FAILED.getCode(),
result.getErrorMessage());
throw new RuntimeException("航迹文件解析失败: " + result.getErrorMessage());
}
} catch (Exception e) {
updateParseStatus(route.getRouteId(), WaylineRoute.ParseStatus.FAILED.getCode(),
e.getMessage());
throw new RuntimeException("解析航迹文件时发生错误: " + e.getMessage(), e);
}
log.info("航迹文件绑定成功: routeId={}, deviceSn={}", route.getRouteId(), deviceSn);
}
}
@@ -0,0 +1,34 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.service.IWaylineWaypointService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 航点服务实现
*
* @author dzc
* @date 2025-12-17
*/
@Service
public class WaylineWaypointServiceImpl extends ServiceImpl<WaylineWaypointMapper, WaylineWaypoint> implements IWaylineWaypointService {
@Override
public List<WaylineWaypoint> listByRouteIdOrderByIndex(String routeId) {
return baseMapper.selectByRouteIdOrderByIndex(routeId);
}
@Override
public int deleteByRouteId(String routeId) {
return baseMapper.deleteByRouteId(routeId);
}
@Override
public Integer countByRouteId(String routeId) {
return baseMapper.countByRouteId(routeId);
}
}
@@ -103,6 +103,40 @@ public class DeviceStatusSseController {
} }
} }
/**
* 使用 Beacon API 断开SSE连接(POST方式)
* 用于浏览器刷新/关闭时,sendBeacon只支持POST请求
* 这是一个备用端点,与DELETE端点功能相同
*
* @param deviceSn 设备SN
* @param body 包含 sessionId 的请求体
* @return 断开结果
*/
@Operation(summary = "Beacon方式断开SSE连接(浏览器刷新/关闭时使用)")
@PostMapping("/device-status/{deviceSn}/disconnect")
public org.springframework.http.ResponseEntity<String> disconnectDeviceStatusByBeacon(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@org.springframework.web.bind.annotation.RequestBody(required = false) java.util.Map<String, String> body) {
String clientSessionId = body != null ? body.get("sessionId") : null;
if (clientSessionId == null || clientSessionId.trim().isEmpty()) {
log.warn("Beacon断开请求缺少sessionId: deviceSn={}", deviceSn);
return org.springframework.http.ResponseEntity.badRequest().body("缺少sessionId");
}
String sessionId = clientSessionId + "_" + deviceSn;
log.info("Beacon方式断开SSE连接: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = sseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
if (success) {
return org.springframework.http.ResponseEntity.ok("连接已断开");
} else {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
/** /**
* 订阅无人机遥测数据(msg_alarm) * 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,开始接收无人机实时遥测数据 * 进入操控台时调用,开始接收无人机实时遥测数据
@@ -223,4 +257,37 @@ public class DeviceStatusSseController {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开"); return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
} }
} }
/**
* 使用 Beacon API 断开无人机遥测数据SSE连接(POST方式)
* 用于浏览器刷新/关闭时,sendBeacon只支持POST请求
*
* @param deviceSn 设备SN
* @param body 包含 sessionId 的请求体
* @return 断开结果
*/
@Operation(summary = "Beacon方式断开无人机遥测数据SSE连接(浏览器刷新/关闭时使用)")
@PostMapping("/drone-telemetry/{deviceSn}/disconnect")
public org.springframework.http.ResponseEntity<String> disconnectDroneTelemetrySseByBeacon(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@org.springframework.web.bind.annotation.RequestBody(required = false) java.util.Map<String, String> body) {
String clientSessionId = body != null ? body.get("sessionId") : null;
if (clientSessionId == null || clientSessionId.trim().isEmpty()) {
log.warn("Beacon断开无人机SSE请求缺少sessionId: deviceSn={}", deviceSn);
return org.springframework.http.ResponseEntity.badRequest().body("缺少sessionId");
}
String sessionId = "drone_" + clientSessionId + "_" + deviceSn;
log.info("Beacon方式断开无人机遥测数据SSE连接: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = sseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
if (success) {
return org.springframework.http.ResponseEntity.ok("无人机遥测数据连接已断开");
} else {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
} }
@@ -2,9 +2,13 @@ package com.central.device.sse.manager;
import com.central.device.sse.dto.DeviceRealtimeDataDTO; import com.central.device.sse.dto.DeviceRealtimeDataDTO;
import com.central.device.sse.model.EmitterWrapper; import com.central.device.sse.model.EmitterWrapper;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.handler.DeviceMessageHandler; import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.DeviceSubscriptionManager; import com.central.device.websocket.manager.DeviceSubscriptionManager;
import com.central.device.websocket.manager.SubscriptionPoolService;
import com.central.device.websocket.manager.SubscriptionPoolService.TopicType;
import com.central.device.websocket.model.DeviceRealtimeData; import com.central.device.websocket.model.DeviceRealtimeData;
import com.central.device.websocket.model.SubscriptionTopic;
import com.central.device.websocket.model.DroneRealtimeData; import com.central.device.websocket.model.DroneRealtimeData;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -41,6 +45,12 @@ public class SseEmitterManager {
@Autowired @Autowired
private DeviceMessageHandler messageHandler; private DeviceMessageHandler messageHandler;
@Autowired
private SubscriptionPoolService subscriptionPoolService;
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
/** /**
* SSE连接池: sessionId -> EmitterWrapper * SSE连接池: sessionId -> EmitterWrapper
*/ */
@@ -48,6 +58,7 @@ public class SseEmitterManager {
/** /**
* 设备订阅计数: deviceSn -> count(引用计数) * 设备订阅计数: deviceSn -> count(引用计数)
* 【保留】用于本地快速查询,与Redis订阅池配合使用
*/ */
private final ConcurrentHashMap<String, Integer> deviceRefCount = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, Integer> deviceRefCount = new ConcurrentHashMap<>();
@@ -56,6 +67,11 @@ public class SseEmitterManager {
*/ */
private ScheduledExecutorService heartbeatExecutor; private ScheduledExecutorService heartbeatExecutor;
/**
* 孤儿订阅清理执行器
*/
private ScheduledExecutorService cleanupExecutor;
/** /**
* 初始化 * 初始化
*/ */
@@ -64,8 +80,15 @@ public class SseEmitterManager {
// 设置DeviceMessageHandler的SSE管理器引用(解决循环依赖) // 设置DeviceMessageHandler的SSE管理器引用(解决循环依赖)
messageHandler.setSseEmitterManager(this); messageHandler.setSseEmitterManager(this);
// 【P1优化】设置JetLinksWebSocketClient的订阅池服务引用
// 用于WebSocket重连时基于Redis状态重新订阅
jetLinksWebSocketClient.setSubscriptionPoolService(subscriptionPoolService);
// 启动心跳 // 启动心跳
startHeartbeat(); startHeartbeat();
// 启动孤儿订阅清理任务
startOrphanSubscriptionCleanup();
} }
/** /**
@@ -123,15 +146,23 @@ public class SseEmitterManager {
log.error("发送连接确认消息失败: session={}, error={}", sessionId, e.getMessage()); log.error("发送连接确认消息失败: session={}, error={}", sessionId, e.getMessage());
} }
// 增加设备引用计数 // 增加本地引用计数(快速查询用)
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1); int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
// 关键:如果是首次订阅该设备,触发WebSocket懒加载和设备订阅 // 【关键】使用Redis订阅池管理订阅,支持多客户端隔离
if (refCount == 1) { // 添加机库状态订阅(fire_alarm, online, offline)
log.info("设备 {} 首次订阅,触发WebSocket懒加载", deviceSn); boolean isFirstFireAlarm = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.FIRE_ALARM);
boolean isFirstOnline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isFirstOffline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.OFFLINE);
// 只有当该设备的某个主题是首次被订阅时,才触发WebSocket订阅
if (isFirstFireAlarm || isFirstOnline || isFirstOffline) {
log.info("设备 {} 首次订阅(Redis池),触发WebSocket懒加载, isFirstFireAlarm={}, isFirstOnline={}, isFirstOffline={}",
deviceSn, isFirstFireAlarm, isFirstOnline, isFirstOffline);
deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId); deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId);
} else { } else {
log.info("设备 {} 新增订阅,复用现有连接,当前引用计数: {}", deviceSn, refCount); log.info("设备 {} 新增订阅,复用现有WebSocket订阅,本地引用计数: {}, Redis订阅数: {}",
deviceSn, refCount, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.FIRE_ALARM));
} }
// 立即推送一次当前设备数据(如果存在) // 立即推送一次当前设备数据(如果存在)
@@ -148,6 +179,7 @@ public class SseEmitterManager {
/** /**
* 移除SSE连接(减少设备引用计数,必要时取消订阅) * 移除SSE连接(减少设备引用计数,必要时取消订阅)
* 【v3.1优化】使用Redis订阅池,支持多客户端隔离,互不影响
*/ */
private void removeEmitter(String sessionId, String deviceSn) { private void removeEmitter(String sessionId, String deviceSn) {
EmitterWrapper wrapper = emitters.remove(sessionId); EmitterWrapper wrapper = emitters.remove(sessionId);
@@ -169,27 +201,79 @@ public class SseEmitterManager {
log.info("移除SSE连接: session={}, deviceSn={}, isDroneTelemetry={}, 剩余连接数: {}", log.info("移除SSE连接: session={}, deviceSn={}, isDroneTelemetry={}, 剩余连接数: {}",
sessionId, deviceSn, isDroneTelemetry, emitters.size()); sessionId, deviceSn, isDroneTelemetry, emitters.size());
// 【关键】如果是无人机SSE连接,需要先取消 msg_alarm 订阅 // 减少本地引用计数(快速查询用)
// 无论引用计数是否归零,都要取消无人机遥测数据订阅 Integer localRefCount = deviceRefCount.compute(deviceSn, (k, v) -> {
if (isDroneTelemetry) {
log.info("无人机SSE连接断开,取消 msg_alarm 订阅: deviceSn={}", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
}
// 减少设备引用计数
Integer refCount = deviceRefCount.compute(deviceSn, (k, v) -> {
if (v == null || v <= 1) { if (v == null || v <= 1) {
return null; // 移除key return null; // 移除key
} }
return v - 1; return v - 1;
}); });
// 关键:如果引用计数归零,取消所有设备订阅(机库订阅) // 【关键】使用Redis订阅池管理取消订阅,保证多客户端隔离
if (refCount == null) { if (isDroneTelemetry) {
log.info("设备 {} 引用计数归零,取消所有订阅", deviceSn); // 无人机SSE连接:取消该session的msg_alarm订阅
deviceSubscriptionManager.unsubscribeDevice(deviceSn); boolean isLastMsgAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
// 【P0修复】同时移除在 addDroneTelemetryEmitter 中添加的 ONLINE/OFFLINE 订阅
// 这些订阅是为了触发WebSocket懒加载而添加的,断开时必须同步移除
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
log.info("无人机SSE连接断开: sessionId={}, deviceSn={}, isLastMsgAlarm={}, isLastOnline={}, isLastOffline={}",
sessionId, deviceSn, isLastMsgAlarm, isLastOnline, isLastOffline);
// 只有当这是最后一个msg_alarm订阅者时,才取消无人机遥测WebSocket订阅
if (isLastMsgAlarm) {
log.info("设备 {} 无人机遥测数据最后一个订阅者离开,取消WebSocket订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
} else {
log.info("设备 {} 无人机遥测数据仍有其他订阅者,保持WebSocket订阅, 剩余: {}",
deviceSn, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.MSG_ALARM));
}
// 如果ONLINE和OFFLINE都是最后一个订阅者,且没有机库SSE连接订阅,则取消设备基础订阅
if (isLastOnline && isLastOffline) {
// 检查是否还有fire_alarm订阅(机库SSE连接)
boolean hasFireAlarmSubscribers = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.FIRE_ALARM);
if (!hasFireAlarmSubscribers) {
log.info("设备 {} 所有基础主题订阅者都已离开,取消设备WebSocket订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
} else {
log.info("设备 {} 仍有机库SSE连接,保持设备WebSocket订阅", deviceSn);
}
}
} else { } else {
log.info("设备 {} 仍有 {} 个订阅,保持连接", deviceSn, refCount); // 机库SSE连接:取消该session的fire_alarm, online, offline订阅
boolean isLastFireAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.FIRE_ALARM);
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
log.info("机库SSE连接断开: sessionId={}, deviceSn={}, isLastFireAlarm={}, isLastOnline={}, isLastOffline={}",
sessionId, deviceSn, isLastFireAlarm, isLastOnline, isLastOffline);
// 【P0修复】分别处理每个主题的WebSocket订阅取消,而不是要求所有条件同时满足
// 1. 如果 fire_alarm 是最后一个订阅者,取消 FIRE_ALARM 主题的WebSocket订阅
if (isLastFireAlarm) {
log.info("设备 {} 机库数据(FIRE_ALARM)最后一个订阅者离开,取消该主题的WebSocket订阅", deviceSn);
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM);
} else {
log.info("设备 {} FIRE_ALARM仍有其他订阅者,保持WebSocket订阅, 剩余: {}",
deviceSn, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.FIRE_ALARM));
}
// 2. 如果 ONLINE 和 OFFLINE 都是最后一个订阅者,检查是否还有 msg_alarm 订阅
if (isLastOnline && isLastOffline) {
boolean hasMsgAlarmSubscribers = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM);
if (!hasMsgAlarmSubscribers) {
log.info("设备 {} ONLINE/OFFLINE基础主题最后一个订阅者离开,取消WebSocket订阅", deviceSn);
jetLinksWebSocketClient.unsubscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
// 移除设备数据缓存
messageHandler.removeDevice(deviceSn);
} else {
log.info("设备 {} 仍有无人机遥测(MSG_ALARM)订阅,保持ONLINE/OFFLINE的WebSocket订阅", deviceSn);
}
}
} }
} }
@@ -284,6 +368,7 @@ public class SseEmitterManager {
/** /**
* 启动心跳 * 启动心跳
* 【优化】缩短心跳间隔到15秒,更快检测断开的连接
*/ */
private void startHeartbeat() { private void startHeartbeat() {
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(); heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
@@ -308,16 +393,126 @@ public class SseEmitterManager {
}); });
// 清理失败的连接 // 清理失败的连接
deadEmitters.forEach(sessionId -> { if (!deadEmitters.isEmpty()) {
EmitterWrapper wrapper = emitters.get(sessionId); log.info("心跳检测到 {} 个断开的连接,开始清理", deadEmitters.size());
if (wrapper != null) { deadEmitters.forEach(sessionId -> {
removeEmitter(sessionId, wrapper.getDeviceSn()); EmitterWrapper wrapper = emitters.get(sessionId);
if (wrapper != null) {
log.info("心跳清理断开的SSE连接: session={}, deviceSn={}, isDroneTelemetry={}",
sessionId, wrapper.getDeviceSn(), wrapper.getIsDroneTelemetry());
removeEmitter(sessionId, wrapper.getDeviceSn());
}
});
}
}, 15000, 15000, TimeUnit.MILLISECONDS); // 【优化】每15秒发送一次心跳(原30秒)
log.info("SSE心跳已启动,间隔: 15秒");
}
/**
* 启动孤儿订阅清理任务
* 定期检查Redis订阅池中的session是否还有对应的SSE连接
* 如果没有,则清理该session的所有订阅
* 【优化】缩短间隔到30秒,更快清理孤儿订阅
*/
private void startOrphanSubscriptionCleanup() {
cleanupExecutor = Executors.newSingleThreadScheduledExecutor();
cleanupExecutor.scheduleAtFixedRate(() -> {
try {
cleanupOrphanSubscriptions();
} catch (Exception e) {
log.error("孤儿订阅清理任务执行失败: {}", e.getMessage(), e);
}
}, 30000, 30000, TimeUnit.MILLISECONDS); // 【优化】每30秒执行一次(原60秒)
log.info("孤儿订阅清理任务已启动,间隔: 30秒");
}
/**
* 清理孤儿订阅
* 检查Redis订阅池中记录的session是否还有对应的SSE连接
* 用于处理浏览器刷新等场景下,前端无法正常发送断开请求的情况
* 【修复】同时清理WebSocket订阅,而不仅仅是Redis记录
*/
private void cleanupOrphanSubscriptions() {
// 获取当前所有活跃的SSE session
java.util.Set<String> activeSessionIds = new java.util.HashSet<>(emitters.keySet());
log.debug("孤儿订阅清理开始: 当前活跃SSE连接数={}", activeSessionIds.size());
// 获取所有Redis中的session
java.util.Set<String> allRedisSessionIds = subscriptionPoolService.getAllSessionIds();
if (allRedisSessionIds.isEmpty()) {
log.debug("孤儿订阅清理完成: Redis中没有订阅记录");
return;
}
int cleanedCount = 0;
// 遍历Redis中的session,检查是否还有对应的SSE连接
for (String sessionId : allRedisSessionIds) {
if (!activeSessionIds.contains(sessionId)) {
log.info("发现孤儿订阅: sessionId={}, 开始清理", sessionId);
// 清理该session的所有订阅,并获取需要取消WebSocket订阅的列表
java.util.List<SubscriptionPoolService.DeviceTopicPair> toUnsubscribe =
subscriptionPoolService.removeAllSubscriptions(sessionId);
// 【关键】实际取消WebSocket订阅
for (SubscriptionPoolService.DeviceTopicPair pair : toUnsubscribe) {
String deviceSn = pair.getDeviceSn();
SubscriptionPoolService.TopicType topicType = pair.getTopicType();
log.info("孤儿清理: 取消设备 {} 的 {} WebSocket订阅", deviceSn, topicType);
// 根据主题类型取消对应的WebSocket订阅
switch (topicType) {
case FIRE_ALARM:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM);
break;
case MSG_ALARM:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_MSG_ALARM);
break;
case ONLINE:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.ONLINE);
break;
case OFFLINE:
jetLinksWebSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.OFFLINE);
break;
}
} }
});
}, 30000, 30000, TimeUnit.MILLISECONDS); // 每30秒发送一次心跳 // 如果清理了该设备的所有订阅,移除设备数据缓存
if (!toUnsubscribe.isEmpty()) {
// 检查该设备是否还有其他订阅
String deviceSn = toUnsubscribe.get(0).getDeviceSn();
boolean hasAnySubscriber =
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.FIRE_ALARM) ||
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.MSG_ALARM) ||
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.ONLINE) ||
subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.OFFLINE);
log.info("SSE心跳已启动,间隔: 30秒"); if (!hasAnySubscriber) {
log.info("孤儿清理: 设备 {} 所有订阅已清理,移除设备数据缓存", deviceSn);
messageHandler.removeDevice(deviceSn);
}
}
cleanedCount++;
}
}
if (cleanedCount > 0) {
log.info("孤儿订阅清理完成: 清理了 {} 个孤儿session", cleanedCount);
// 打印当前订阅状态
if (log.isDebugEnabled()) {
subscriptionPoolService.printSubscriptionStatus();
}
} else {
log.debug("孤儿订阅清理完成: 没有发现孤儿订阅");
}
} }
/** /**
@@ -412,24 +607,32 @@ public class SseEmitterManager {
log.error("发送无人机连接确认消息失败: session={}, error={}", sessionId, e.getMessage()); log.error("发送无人机连接确认消息失败: session={}, error={}", sessionId, e.getMessage());
} }
// 增加设备引用计数(无人机专用) // 增加本地引用计数(快速查询用)
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1); int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
// 【关键修复】无论引用计数是多少,都需要订阅无人机遥测数据(msg_alarm) // 【关键】使用Redis订阅池管理无人机遥测数据订阅
// 因为机库订阅(addEmitter)只订阅了 fire_alarm,不包括 msg_alarm // 添加 msg_alarm 订阅到Redis池
// 所以这里需要额外订阅 msg_alarm 主题 boolean isFirstMsgAlarm = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
log.info("设备 {} 订阅无人机遥测数据,当前引用计数: {}", deviceSn, refCount);
// 如果是首次订阅该设备(refCount == 1),需要先订阅基础主题 log.info("设备 {} 订阅无人机遥测数据: sessionId={}, isFirstSubscriber={}, localRefCount={}",
if (refCount == 1) { deviceSn, sessionId, isFirstMsgAlarm, refCount);
log.info("设备 {} 首次订阅,触发WebSocket懒加载并订阅基础主题", deviceSn);
// 如果是首次订阅该设备的基础主题,需要先订阅基础主题
boolean isFirstOnline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.ONLINE);
boolean isFirstOffline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.OFFLINE);
if (isFirstOnline || isFirstOffline) {
log.info("设备 {} 首次订阅基础主题,触发WebSocket懒加载", deviceSn);
deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId); deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId);
} }
// 无论如何都要订阅无人机遥测数据主题(msg_alarm) // 只有当该设备的 msg_alarm 是首次被订阅时,才向WebSocket发送订阅
// 这是独立于机库订阅的,需要单独调用 if (isFirstMsgAlarm) {
log.info("设备 {} 订阅无人机遥测主题 msg_alarm", deviceSn); log.info("设备 {} 无人机遥测数据首次订阅(Redis池),向WebSocket发送订阅", deviceSn);
deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn); deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn);
} else {
log.info("设备 {} 无人机遥测数据已有其他订阅者,复用现有WebSocket订阅, Redis订阅数: {}",
deviceSn, subscriptionPoolService.getSubscriberCount(deviceSn, TopicType.MSG_ALARM));
}
// 立即推送一次当前无人机数据(如果存在) // 立即推送一次当前无人机数据(如果存在)
com.central.device.websocket.model.DeviceRealtimeData currentData = messageHandler.getDeviceData(deviceSn); com.central.device.websocket.model.DeviceRealtimeData currentData = messageHandler.getDeviceData(deviceSn);
@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.config.WebSocketProperties; import com.central.device.websocket.config.WebSocketProperties;
import com.central.device.websocket.handler.DeviceMessageHandler; import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.DeviceCommandManager; import com.central.device.websocket.manager.DeviceCommandManager;
import com.central.device.websocket.manager.SubscriptionPoolService;
import com.central.device.websocket.manager.TokenManager; import com.central.device.websocket.manager.TokenManager;
import com.central.device.websocket.model.SubscriptionMessage; import com.central.device.websocket.model.SubscriptionMessage;
import com.central.device.websocket.model.SubscriptionTopic; import com.central.device.websocket.model.SubscriptionTopic;
@@ -95,6 +96,11 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
*/ */
private ScheduledExecutorService reconnectExecutor; private ScheduledExecutorService reconnectExecutor;
/**
* 订阅池服务(用于获取当前有效订阅状态)
*/
private SubscriptionPoolService subscriptionPoolService;
/** /**
* 构造函数 * 构造函数
*/ */
@@ -107,6 +113,13 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
this.webSocketClient = new StandardWebSocketClient(); this.webSocketClient = new StandardWebSocketClient();
} }
/**
* 设置订阅池服务(延迟注入,避免循环依赖)
*/
public void setSubscriptionPoolService(SubscriptionPoolService subscriptionPoolService) {
this.subscriptionPoolService = subscriptionPoolService;
}
/** /**
* 初始化(仅初始化线程池,不自动连接) * 初始化(仅初始化线程池,不自动连接)
*/ */
@@ -435,6 +448,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
public void unsubscribeDevice(String deviceSn, SubscriptionTopic... topics) { public void unsubscribeDevice(String deviceSn, SubscriptionTopic... topics) {
if (!isConnected()) { if (!isConnected()) {
log.warn("WebSocket未连接,无法取消订阅: {}", deviceSn); log.warn("WebSocket未连接,无法取消订阅: {}", deviceSn);
// 即使未连接,也要清理本地状态
cleanupLocalState(deviceSn, topics);
return; return;
} }
@@ -450,15 +465,37 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
unsubscribeTopic(topic, deviceSn); unsubscribeTopic(topic, deviceSn);
} }
// 检查是否所有设备的订阅都已取消,如果是则断开WebSocket连接以节省资源 // 【修复】基于 subscribedTopics(实际订阅列表)来判断是否断开连接
// 注意:这里检查deviceSubscriptionCounts而不是subscribedTopics // 而不是依赖可能不同步的 deviceSubscriptionCounts
// 因为一个设备可能有多个主题订阅(fire_alarm + msg_alarm) if (subscribedTopics.isEmpty()) {
if (deviceSubscriptionCounts.isEmpty()) { log.info("所有主题订阅已取消,自动断开WebSocket连接以节省资源");
log.info("所有设备的所有订阅已取消,自动断开WebSocket连接以节省资源"); // 清空本地计数器
deviceSubscriptionCounts.clear();
closeConnection(); closeConnection();
} else { } else {
log.info("仍有{}个设备有活跃订阅,保持WebSocket连接: {}", log.info("仍有{}个主题订阅,保持WebSocket连接: {}",
deviceSubscriptionCounts.size(), deviceSubscriptionCounts.keySet()); subscribedTopics.size(), subscribedTopics);
}
}
/**
* 清理设备的本地订阅状态(WebSocket未连接时使用)
*/
private void cleanupLocalState(String deviceSn, SubscriptionTopic... topics) {
if (topics == null) return;
for (SubscriptionTopic topicEnum : topics) {
String topic = topicEnum.getTopic(deviceSn);
subscribedTopics.remove(topic);
}
// 检查该设备是否还有其他主题订阅
boolean hasOtherTopics = subscribedTopics.stream()
.anyMatch(t -> t.contains("/" + deviceSn + "/"));
if (!hasOtherTopics) {
deviceSubscriptionCounts.remove(deviceSn);
log.info("设备 {} 本地订阅状态已清理", deviceSn);
} }
} }
@@ -468,6 +505,12 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
private void subscribeTopic(SubscriptionTopic topicEnum, String deviceSn) { private void subscribeTopic(SubscriptionTopic topicEnum, String deviceSn) {
String topic = topicEnum.getTopic(deviceSn); String topic = topicEnum.getTopic(deviceSn);
// 【修复】如果主题已经在订阅列表中,跳过重复订阅
if (subscribedTopics.contains(topic)) {
log.debug("主题已订阅,跳过重复订阅: topic={}, deviceSn={}", topic, deviceSn);
return;
}
SubscriptionMessage message = SubscriptionMessage.builder() SubscriptionMessage message = SubscriptionMessage.builder()
.type("sub") .type("sub")
.topic(topic) .topic(topic)
@@ -478,12 +521,11 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
send(JSON.toJSONString(message)); send(JSON.toJSONString(message));
subscribedTopics.add(topic); subscribedTopics.add(topic);
// 更新设备订阅计数 // 更新设备订阅计数(只有实际发送订阅时才增加)
deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet(); deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet();
log.info("发送订阅消息: topic={}, id={}, message={}, 设备{}订阅计数: {}", log.info("发送订阅消息: topic={}, 设备{}订阅计数: {}",
topic, message.getId(), JSON.toJSONString(message), topic, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
} }
/** /**
@@ -508,23 +550,29 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
send(JSON.toJSONString(message)); send(JSON.toJSONString(message));
subscribedTopics.remove(topic); subscribedTopics.remove(topic);
// 更新设备订阅计数 // 【修复】检查该设备是否还有其他主题订阅(基于实际订阅列表)
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn); boolean hasOtherTopics = subscribedTopics.stream()
if (count != null) { .anyMatch(t -> t.contains("/" + deviceSn + "/"));
int newCount = count.decrementAndGet();
if (newCount <= 0) { if (!hasOtherTopics) {
deviceSubscriptionCounts.remove(deviceSn); // 该设备没有其他订阅了,直接移除计数器
log.info("设备{}所有订阅已取消,从订阅计数中移除", deviceSn); deviceSubscriptionCounts.remove(deviceSn);
log.info("设备 {} 所有主题订阅已取消,从计数器中移除", deviceSn);
} else {
// 更新设备订阅计数
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn);
if (count != null) {
count.decrementAndGet();
} }
} }
log.info("取消订阅主题: topic={}, id={}, 剩余订阅数: {}, 剩余主题: {}, 设备{}剩余订阅计数: {}", log.info("取消订阅主题: topic={}, 剩余主题数: {}, 剩余主题: {}",
topic, message.getId(), subscribedTopics.size(), subscribedTopics, topic, subscribedTopics.size(), subscribedTopics);
deviceSn, count != null ? count.get() : 0);
} }
/** /**
* 重新订阅所有主题 * 重新订阅所有主题
* 【P1优化】基于Redis订阅池状态决定订阅哪些主题,避免与实际订阅状态不同步
*/ */
private void resubscribeAll() { private void resubscribeAll() {
if (subscribedTopics.isEmpty()) { if (subscribedTopics.isEmpty()) {
@@ -539,7 +587,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
// 清空设备订阅计数,重新订阅时会重新计算 // 清空设备订阅计数,重新订阅时会重新计算
deviceSubscriptionCounts.clear(); deviceSubscriptionCounts.clear();
// 按设备分组重新订阅(订阅所有标准主题) // 按设备分组重新订阅
Set<String> deviceSns = new HashSet<>(); Set<String> deviceSns = new HashSet<>();
topics.forEach(topic -> { topics.forEach(topic -> {
String deviceSn = extractDeviceSn(topic); String deviceSn = extractDeviceSn(topic);
@@ -548,14 +596,55 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
} }
}); });
// 为每个设备重新订阅标准主题(订阅关键主题) // 【P1优化】根据Redis订阅池状态决定订阅哪些主题
// 如果有订阅池服务,则只订阅Redis中有记录的主题
deviceSns.forEach(deviceSn -> { deviceSns.forEach(deviceSn -> {
subscribeDevice(deviceSn, if (subscriptionPoolService != null) {
SubscriptionTopic.ONLINE, // 基于Redis订阅池状态重新订阅
SubscriptionTopic.OFFLINE, boolean hasFireAlarm = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.FIRE_ALARM);
SubscriptionTopic.EVENT_FIRE_ALARM, // fire_alarm(机库状态数据) boolean hasMsgAlarm = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.MSG_ALARM);
SubscriptionTopic.EVENT_MSG_ALARM // msg_alarm(无人机遥测数据) boolean hasOnline = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.ONLINE);
); boolean hasOffline = subscriptionPoolService.hasSubscribers(deviceSn, SubscriptionPoolService.TopicType.OFFLINE);
log.info("设备 {} Redis订阅状态: fire_alarm={}, msg_alarm={}, online={}, offline={}",
deviceSn, hasFireAlarm, hasMsgAlarm, hasOnline, hasOffline);
// 只有Redis中有订阅者的主题才重新订阅
java.util.List<SubscriptionTopic> topicsToSubscribe = new java.util.ArrayList<>();
// 基础主题(有任何SSE连接就需要订阅)
if (hasOnline || hasFireAlarm || hasMsgAlarm) {
topicsToSubscribe.add(SubscriptionTopic.ONLINE);
}
if (hasOffline || hasFireAlarm || hasMsgAlarm) {
topicsToSubscribe.add(SubscriptionTopic.OFFLINE);
}
// 机库数据主题
if (hasFireAlarm) {
topicsToSubscribe.add(SubscriptionTopic.EVENT_FIRE_ALARM);
}
// 无人机遥测数据主题(只有进入操控台才订阅)
if (hasMsgAlarm) {
topicsToSubscribe.add(SubscriptionTopic.EVENT_MSG_ALARM);
}
if (!topicsToSubscribe.isEmpty()) {
subscribeDevice(deviceSn, topicsToSubscribe.toArray(new SubscriptionTopic[0]));
log.info("设备 {} 基于Redis状态重新订阅: {}", deviceSn, topicsToSubscribe);
} else {
log.info("设备 {} 在Redis中没有订阅者,跳过重新订阅", deviceSn);
}
} else {
// 没有订阅池服务,回退到默认行为(订阅所有基础主题)
log.warn("订阅池服务未设置,使用默认重新订阅策略");
subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM // 只订阅机库数据,不订阅msg_alarm
);
}
}); });
} }
@@ -0,0 +1,405 @@
package com.central.device.websocket.manager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* 订阅池服务 - 使用Redis管理客户端订阅
*
* 核心功能:
* 1. 每个客户端(sessionId)有独立的订阅记录
* 2. 多个客户端订阅同一设备时互不影响
* 3. 只有当所有客户端都取消订阅后,才真正取消WebSocket订阅
* 4. 支持分布式部署(多实例共享Redis)
*
* Redis数据结构:
* - device:sub:{deviceSn}:{topicType} -> Set<sessionId>
* 记录每个设备的每个主题类型被哪些session订阅
*
* - device:sub:session:{sessionId} -> Set<deviceSn:topicType>
* 记录每个session订阅了哪些设备的哪些主题(用于快速清理)
*
* @author dzc
* @date 2025-01-20
*/
@Slf4j
@Service
public class SubscriptionPoolService {
private static final String KEY_PREFIX = "device:sub:";
private static final String SESSION_KEY_PREFIX = "device:sub:session:";
// 订阅记录过期时间(24小时,防止僵尸数据)
private static final long EXPIRE_HOURS = 24;
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 主题类型枚举
*/
public enum TopicType {
FIRE_ALARM("fire_alarm"), // 机库状态数据
MSG_ALARM("msg_alarm"), // 无人机遥测数据
ONLINE("online"), // 设备上线
OFFLINE("offline"); // 设备下线
private final String value;
TopicType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
/**
* 添加订阅
*
* @param sessionId 客户端会话ID
* @param deviceSn 设备SN
* @param topicType 主题类型
* @return true 如果是该设备该主题的第一个订阅者(需要向WebSocket发送订阅),false 表示已有其他人订阅
*/
public boolean addSubscription(String sessionId, String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
String sessionKey = buildSessionKey(sessionId);
String subscriptionValue = deviceSn + ":" + topicType.getValue();
try {
// 1. 添加到主题订阅集合
Long addResult = redisTemplate.opsForSet().add(topicKey, sessionId);
// 2. 添加到session的订阅记录(用于快速清理)
redisTemplate.opsForSet().add(sessionKey, subscriptionValue);
// 3. 设置过期时间(防止僵尸数据)
redisTemplate.expire(topicKey, EXPIRE_HOURS, TimeUnit.HOURS);
redisTemplate.expire(sessionKey, EXPIRE_HOURS, TimeUnit.HOURS);
// 4. 获取当前订阅数
Long count = redisTemplate.opsForSet().size(topicKey);
boolean isFirstSubscriber = addResult != null && addResult > 0 && count != null && count == 1;
log.info("添加订阅: sessionId={}, deviceSn={}, topicType={}, isFirst={}, totalCount={}",
sessionId, deviceSn, topicType.getValue(), isFirstSubscriber, count);
return isFirstSubscriber;
} catch (Exception e) {
log.error("添加订阅失败: sessionId={}, deviceSn={}, topicType={}, error={}",
sessionId, deviceSn, topicType.getValue(), e.getMessage());
return true; // 出错时保守处理,返回true确保订阅
}
}
/**
* 移除订阅
*
* @param sessionId 客户端会话ID
* @param deviceSn 设备SN
* @param topicType 主题类型
* @return true 如果是该设备该主题的最后一个订阅者(需要向WebSocket发送取消订阅),false 表示还有其他人订阅
*/
public boolean removeSubscription(String sessionId, String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
String sessionKey = buildSessionKey(sessionId);
String subscriptionValue = deviceSn + ":" + topicType.getValue();
try {
// 1. 从主题订阅集合移除
Long removeResult = redisTemplate.opsForSet().remove(topicKey, sessionId);
// 2. 从session的订阅记录移除
redisTemplate.opsForSet().remove(sessionKey, subscriptionValue);
// 3. 获取剩余订阅数
Long remainingCount = redisTemplate.opsForSet().size(topicKey);
// 4. 如果没有订阅者了,删除key
boolean isLastSubscriber = remainingCount == null || remainingCount == 0;
if (isLastSubscriber) {
redisTemplate.delete(topicKey);
}
log.info("移除订阅: sessionId={}, deviceSn={}, topicType={}, isLast={}, remainingCount={}",
sessionId, deviceSn, topicType.getValue(), isLastSubscriber, remainingCount);
return isLastSubscriber;
} catch (Exception e) {
log.error("移除订阅失败: sessionId={}, deviceSn={}, topicType={}, error={}",
sessionId, deviceSn, topicType.getValue(), e.getMessage());
return true; // 出错时保守处理,返回true确保取消订阅
}
}
/**
* 移除session的所有订阅
* 用于客户端断开连接时快速清理
*
* @param sessionId 客户端会话ID
* @return 需要真正取消WebSocket订阅的设备和主题列表
*/
public java.util.List<DeviceTopicPair> removeAllSubscriptions(String sessionId) {
String sessionKey = buildSessionKey(sessionId);
java.util.List<DeviceTopicPair> toUnsubscribe = new java.util.ArrayList<>();
try {
// 1. 获取该session的所有订阅
Set<String> subscriptions = redisTemplate.opsForSet().members(sessionKey);
if (subscriptions == null || subscriptions.isEmpty()) {
log.debug("Session {} 没有订阅记录", sessionId);
return toUnsubscribe;
}
log.info("清理session订阅: sessionId={}, subscriptionCount={}", sessionId, subscriptions.size());
// 2. 逐个移除订阅
for (String subscription : subscriptions) {
String[] parts = subscription.split(":", 2);
if (parts.length != 2) {
continue;
}
String deviceSn = parts[0];
String topicTypeStr = parts[1];
TopicType topicType = parseTopicType(topicTypeStr);
if (topicType != null) {
boolean isLast = removeSubscription(sessionId, deviceSn, topicType);
if (isLast) {
toUnsubscribe.add(new DeviceTopicPair(deviceSn, topicType));
}
}
}
// 3. 删除session的订阅记录key
redisTemplate.delete(sessionKey);
log.info("Session {} 订阅清理完成,需要取消WebSocket订阅的数量: {}", sessionId, toUnsubscribe.size());
} catch (Exception e) {
log.error("清理session订阅失败: sessionId={}, error={}", sessionId, e.getMessage());
}
return toUnsubscribe;
}
/**
* 检查设备的某个主题是否有订阅者
*/
public boolean hasSubscribers(String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
try {
Long count = redisTemplate.opsForSet().size(topicKey);
return count != null && count > 0;
} catch (Exception e) {
log.error("检查订阅者失败: deviceSn={}, topicType={}, error={}",
deviceSn, topicType.getValue(), e.getMessage());
return false;
}
}
/**
* 获取设备某个主题的订阅者数量
*/
public long getSubscriberCount(String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
try {
Long count = redisTemplate.opsForSet().size(topicKey);
return count != null ? count : 0;
} catch (Exception e) {
log.error("获取订阅者数量失败: deviceSn={}, topicType={}, error={}",
deviceSn, topicType.getValue(), e.getMessage());
return 0;
}
}
/**
* 获取设备某个主题的所有订阅者
*/
public Set<String> getSubscribers(String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
try {
return redisTemplate.opsForSet().members(topicKey);
} catch (Exception e) {
log.error("获取订阅者列表失败: deviceSn={}, topicType={}, error={}",
deviceSn, topicType.getValue(), e.getMessage());
return java.util.Collections.emptySet();
}
}
/**
* 获取session的所有订阅
*/
public Set<String> getSessionSubscriptions(String sessionId) {
String sessionKey = buildSessionKey(sessionId);
try {
return redisTemplate.opsForSet().members(sessionKey);
} catch (Exception e) {
log.error("获取session订阅失败: sessionId={}, error={}", sessionId, e.getMessage());
return java.util.Collections.emptySet();
}
}
/**
* 刷新订阅的过期时间(心跳时调用)
*/
public void refreshSubscription(String sessionId, String deviceSn, TopicType topicType) {
String topicKey = buildTopicKey(deviceSn, topicType);
String sessionKey = buildSessionKey(sessionId);
try {
redisTemplate.expire(topicKey, EXPIRE_HOURS, TimeUnit.HOURS);
redisTemplate.expire(sessionKey, EXPIRE_HOURS, TimeUnit.HOURS);
} catch (Exception e) {
log.debug("刷新订阅过期时间失败: sessionId={}, deviceSn={}", sessionId, deviceSn);
}
}
/**
* 打印当前订阅状态(调试用)
*/
public void printSubscriptionStatus() {
try {
Set<String> keys = redisTemplate.keys(KEY_PREFIX + "*");
if (keys == null || keys.isEmpty()) {
log.info("当前没有任何订阅");
return;
}
log.info("========== 订阅池状态 ==========");
for (String key : keys) {
if (key.startsWith(SESSION_KEY_PREFIX)) {
continue; // 跳过session key
}
Set<String> members = redisTemplate.opsForSet().members(key);
log.info(" {} -> {} 个订阅者: {}", key, members != null ? members.size() : 0, members);
}
log.info("================================");
} catch (Exception e) {
log.error("打印订阅状态失败: {}", e.getMessage());
}
}
/**
* 获取所有有订阅记录的sessionId
* 用于孤儿订阅清理
*/
public Set<String> getAllSessionIds() {
try {
Set<String> sessionKeys = redisTemplate.keys(SESSION_KEY_PREFIX + "*");
if (sessionKeys == null || sessionKeys.isEmpty()) {
return java.util.Collections.emptySet();
}
// 从key中提取sessionId
Set<String> sessionIds = new java.util.HashSet<>();
for (String key : sessionKeys) {
String sessionId = key.substring(SESSION_KEY_PREFIX.length());
sessionIds.add(sessionId);
}
return sessionIds;
} catch (Exception e) {
log.error("获取所有sessionId失败: {}", e.getMessage());
return java.util.Collections.emptySet();
}
}
/**
* 清理孤儿订阅
* 检查Redis中记录的session是否在活跃session列表中
* 如果不在,则清理该session的所有订阅
*
* @param activeSessionIds 当前活跃的sessionId集合
* @return 清理的孤儿session数量
*/
public int cleanupOrphanSessions(Set<String> activeSessionIds) {
int cleanedCount = 0;
try {
Set<String> allSessionIds = getAllSessionIds();
if (allSessionIds.isEmpty()) {
return 0;
}
for (String sessionId : allSessionIds) {
// 如果session不在活跃列表中,说明是孤儿订阅
if (!activeSessionIds.contains(sessionId)) {
log.info("发现孤儿订阅: sessionId={}, 开始清理", sessionId);
// 清理该session的所有订阅
java.util.List<DeviceTopicPair> toUnsubscribe = removeAllSubscriptions(sessionId);
log.info("孤儿订阅清理完成: sessionId={}, 需要取消WebSocket订阅的数量: {}",
sessionId, toUnsubscribe.size());
cleanedCount++;
}
}
if (cleanedCount > 0) {
log.info("孤儿订阅清理完成,共清理 {} 个孤儿session", cleanedCount);
}
} catch (Exception e) {
log.error("清理孤儿订阅失败: {}", e.getMessage());
}
return cleanedCount;
}
// ========== 私有方法 ==========
private String buildTopicKey(String deviceSn, TopicType topicType) {
return KEY_PREFIX + deviceSn + ":" + topicType.getValue();
}
private String buildSessionKey(String sessionId) {
return SESSION_KEY_PREFIX + sessionId;
}
private TopicType parseTopicType(String value) {
for (TopicType type : TopicType.values()) {
if (type.getValue().equals(value)) {
return type;
}
}
return null;
}
/**
* 设备-主题对,用于返回需要取消订阅的列表
*/
public static class DeviceTopicPair {
private final String deviceSn;
private final TopicType topicType;
public DeviceTopicPair(String deviceSn, TopicType topicType) {
this.deviceSn = deviceSn;
this.topicType = topicType;
}
public String getDeviceSn() {
return deviceSn;
}
public TopicType getTopicType() {
return topicType;
}
@Override
public String toString() {
return deviceSn + ":" + topicType.getValue();
}
}
}
@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.DroneFlightTrackMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.DroneFlightTrack">
<id column="id" property="id" />
<result column="device_sn" property="deviceSn" />
<result column="job_id" property="jobId" />
<result column="route_id" property="routeId" />
<result column="longitude" property="longitude" />
<result column="latitude" property="latitude" />
<result column="altitude" property="altitude" />
<result column="height" property="height" />
<result column="horizontal_speed" property="horizontalSpeed" />
<result column="vertical_speed" property="verticalSpeed" />
<result column="heading" property="heading" />
<result column="pitch" property="pitch" />
<result column="roll" property="roll" />
<result column="flight_mode" property="flightMode" />
<result column="battery_percent" property="batteryPercent" />
<result column="deviation_distance" property="deviationDistance" />
<result column="is_deviation" property="isDeviation" />
<result column="record_time" property="recordTime" />
<result column="tenant_id" property="tenantId" />
<result column="create_time" property="createTime" />
</resultMap>
<!-- 根据设备SN和查询条件获取轨迹点 -->
<select id="selectTrackPoints" resultMap="BaseResultMap">
SELECT * FROM drone_flight_track
WHERE 1=1
<if test="deviceSn != null and deviceSn != ''">
AND device_sn = #{deviceSn}
</if>
<if test="jobId != null and jobId != ''">
AND job_id = #{jobId}
</if>
<if test="routeId != null and routeId != ''">
AND route_id = #{routeId}
</if>
<if test="startTime != null">
AND record_time >= #{startTime}
</if>
<if test="endTime != null">
AND record_time &lt;= #{endTime}
</if>
ORDER BY record_time ASC
<if test="limit != null and limit > 0">
LIMIT #{limit}
</if>
</select>
<!-- 根据设备SN获取最新的轨迹点 -->
<select id="selectLatestTrackPoint" resultMap="BaseResultMap">
SELECT * FROM drone_flight_track
WHERE device_sn = #{deviceSn}
ORDER BY record_time DESC
LIMIT 1
</select>
<!-- 根据设备SN删除指定时间范围的轨迹 -->
<delete id="deleteByDeviceSnAndTimeBefore">
DELETE FROM drone_flight_track
WHERE device_sn = #{deviceSn}
AND record_time &lt; #{beforeTime}
</delete>
<!-- 统计轨迹点数量 -->
<select id="countTrackPoints" resultType="java.lang.Long">
SELECT COUNT(*) FROM drone_flight_track
WHERE 1=1
<if test="deviceSn != null and deviceSn != ''">
AND device_sn = #{deviceSn}
</if>
<if test="jobId != null and jobId != ''">
AND job_id = #{jobId}
</if>
<if test="routeId != null and routeId != ''">
AND route_id = #{routeId}
</if>
<if test="startTime != null">
AND record_time >= #{startTime}
</if>
<if test="endTime != null">
AND record_time &lt;= #{endTime}
</if>
</select>
<!-- 批量插入轨迹点 -->
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO drone_flight_track (
device_sn, job_id, route_id, longitude, latitude, altitude, height,
horizontal_speed, vertical_speed, heading, pitch, roll, flight_mode,
battery_percent, deviation_distance, is_deviation, record_time,
tenant_id, create_time
) VALUES
<foreach collection="trackPoints" item="item" separator=",">
(
#{item.deviceSn}, #{item.jobId}, #{item.routeId}, #{item.longitude}, #{item.latitude},
#{item.altitude}, #{item.height}, #{item.horizontalSpeed}, #{item.verticalSpeed},
#{item.heading}, #{item.pitch}, #{item.roll}, #{item.flightMode}, #{item.batteryPercent},
#{item.deviationDistance}, #{item.isDeviation}, #{item.recordTime}, #{item.tenantId}, NOW()
)
</foreach>
</insert>
<!-- 根据航线任务ID删除飞行轨迹 -->
<delete id="deleteByRouteId">
DELETE FROM drone_flight_track
WHERE route_id = #{routeId}
</delete>
</mapper>
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.WaylineActionMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.WaylineAction">
<id column="id" property="id" />
<result column="waypoint_id" property="waypointId" />
<result column="route_id" property="routeId" />
<result column="action_group_id" property="actionGroupId" />
<result column="action_index" property="actionIndex" />
<result column="action_type" property="actionType" />
<result column="action_params" property="actionParams" />
<result column="trigger_type" property="triggerType" />
<result column="tenant_id" property="tenantId" />
<result column="create_time" property="createTime" />
</resultMap>
<!-- 根据航点ID查询动作列表 -->
<select id="selectByWaypointId" resultMap="BaseResultMap">
SELECT * FROM wayline_action
WHERE waypoint_id = #{waypointId}
ORDER BY action_group_id ASC, action_index ASC
</select>
<!-- 根据航线任务ID查询动作列表 -->
<select id="selectByRouteId" resultMap="BaseResultMap">
SELECT * FROM wayline_action
WHERE route_id = #{routeId}
ORDER BY action_group_id ASC, action_index ASC
</select>
<!-- 根据航线任务ID删除动作 -->
<delete id="deleteByRouteId">
DELETE FROM wayline_action
WHERE route_id = #{routeId}
</delete>
<!-- 批量插入动作 -->
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO wayline_action (
waypoint_id, route_id, action_group_id, action_index,
action_type, action_params, trigger_type, tenant_id, create_time
) VALUES
<foreach collection="actions" item="item" separator=",">
(
#{item.waypointId}, #{item.routeId}, #{item.actionGroupId}, #{item.actionIndex},
#{item.actionType}, #{item.actionParams}, #{item.triggerType}, #{item.tenantId}, NOW()
)
</foreach>
</insert>
<!-- 统计动作数量 -->
<select id="countByRouteId" resultType="java.lang.Integer">
SELECT COUNT(*) FROM wayline_action
WHERE route_id = #{routeId}
</select>
</mapper>
@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.WaylineRouteMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.WaylineRoute">
<id column="id" property="id" />
<result column="route_id" property="routeId" />
<result column="route_name" property="routeName" />
<result column="file_wayline_id" property="fileWaylineId" />
<result column="device_sn" property="deviceSn" />
<result column="device_name" property="deviceName" />
<result column="parse_status" property="parseStatus" />
<result column="parse_error" property="parseError" />
<result column="waypoint_count" property="waypointCount" />
<result column="action_count" property="actionCount" />
<result column="total_distance" property="totalDistance" />
<result column="total_duration" property="totalDuration" />
<result column="auto_flight_speed" property="autoFlightSpeed" />
<result column="take_off_point" property="takeOffPoint" />
<result column="finish_action" property="finishAction" />
<result column="exit_on_rc_lost" property="exitOnRcLost" />
<result column="global_rth_height" property="globalRthHeight" />
<result column="coordinate_mode" property="coordinateMode" />
<result column="height_mode" property="heightMode" />
<result column="status" property="status" />
<result column="remark" property="remark" />
<result column="workspace_id" property="workspaceId" />
<result column="tenant_id" property="tenantId" />
<result column="create_by" property="createBy" />
<result column="create_time" property="createTime" />
<result column="update_by" property="updateBy" />
<result column="update_time" property="updateTime" />
</resultMap>
<!-- 根据航迹文件ID查询航线任务列表 -->
<select id="selectByFileWaylineId" resultMap="BaseResultMap">
SELECT * FROM wayline_route
WHERE file_wayline_id = #{fileWaylineId}
AND status = 1
ORDER BY create_time DESC
</select>
<!-- 根据设备SN查询绑定的航线任务列表 -->
<select id="selectByDeviceSn" resultMap="BaseResultMap">
SELECT * FROM wayline_route
WHERE device_sn = #{deviceSn}
AND status = 1
ORDER BY create_time DESC
</select>
<!-- 根据航线任务ID查询 -->
<select id="selectByRouteId" resultMap="BaseResultMap">
SELECT * FROM wayline_route
WHERE route_id = #{routeId}
</select>
<!-- 更新解析状态 -->
<update id="updateParseStatus">
UPDATE wayline_route
SET parse_status = #{parseStatus},
update_time = NOW()
WHERE route_id = #{routeId}
</update>
<!-- 更新解析状态和错误信息 -->
<update id="updateParseStatusWithError">
UPDATE wayline_route
SET parse_status = #{parseStatus},
parse_error = #{parseError},
update_time = NOW()
WHERE route_id = #{routeId}
</update>
<!-- 更新航线任务统计信息 -->
<update id="updateRouteStats">
UPDATE wayline_route
SET waypoint_count = #{waypointCount},
action_count = #{actionCount},
total_distance = #{totalDistance},
total_duration = #{totalDuration},
auto_flight_speed = #{autoFlightSpeed},
update_time = NOW()
WHERE route_id = #{routeId}
</update>
<!-- 根据设备SN和航迹文件ID查询航线任务 -->
<select id="selectByDeviceSnAndFileWaylineId" resultMap="BaseResultMap">
SELECT * FROM wayline_route
WHERE device_sn = #{deviceSn}
AND file_wayline_id = #{waylineId}
AND status = 1
ORDER BY create_time DESC
</select>
<!-- 删除设备与航迹文件的绑定(级联删除相关数据) -->
<delete id="deleteBindingByDeviceAndWayline">
DELETE FROM wayline_route
WHERE device_sn = #{deviceSn}
AND file_wayline_id = #{waylineId}
</delete>
</mapper>
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.device.mapper.WaylineWaypointMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.central.device.entity.WaylineWaypoint">
<id column="id" property="id" />
<result column="route_id" property="routeId" />
<result column="waypoint_index" property="waypointIndex" />
<result column="longitude" property="longitude" />
<result column="latitude" property="latitude" />
<result column="height" property="height" />
<result column="execute_height" property="executeHeight" />
<result column="ellipsoid_height" property="ellipsoidHeight" />
<result column="speed" property="speed" />
<result column="heading_mode" property="headingMode" />
<result column="heading_angle" property="headingAngle" />
<result column="gimbal_pitch_angle" property="gimbalPitchAngle" />
<result column="turn_mode" property="turnMode" />
<result column="turn_damping_dist" property="turnDampingDist" />
<result column="use_straight_line" property="useStraightLine" />
<result column="is_risky" property="isRisky" />
<result column="action_group_count" property="actionGroupCount" />
<result column="tenant_id" property="tenantId" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
</resultMap>
<!-- 根据航线任务ID查询航点列表(按序号排序) -->
<select id="selectByRouteIdOrderByIndex" resultMap="BaseResultMap">
SELECT * FROM wayline_waypoint
WHERE route_id = #{routeId}
ORDER BY waypoint_index ASC
</select>
<!-- 根据航线任务ID删除航点 -->
<delete id="deleteByRouteId">
DELETE FROM wayline_waypoint
WHERE route_id = #{routeId}
</delete>
<!-- 批量插入航点 -->
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO wayline_waypoint (
route_id, waypoint_index, longitude, latitude, height,
execute_height, ellipsoid_height, speed, heading_mode,
heading_angle, gimbal_pitch_angle, turn_mode, turn_damping_dist,
use_straight_line, is_risky, action_group_count, tenant_id, create_time
) VALUES
<foreach collection="waypoints" item="item" separator=",">
(
#{item.routeId}, #{item.waypointIndex}, #{item.longitude}, #{item.latitude}, #{item.height},
#{item.executeHeight}, #{item.ellipsoidHeight}, #{item.speed}, #{item.headingMode},
#{item.headingAngle}, #{item.gimbalPitchAngle}, #{item.turnMode}, #{item.turnDampingDist},
#{item.useStraightLine}, #{item.isRisky}, #{item.actionGroupCount}, #{item.tenantId}, NOW()
)
</foreach>
</insert>
<!-- 统计航点数量 -->
<select id="countByRouteId" resultType="java.lang.Integer">
SELECT COUNT(*) FROM wayline_waypoint
WHERE route_id = #{routeId}
</select>
</mapper>
@@ -0,0 +1,161 @@
-- 大疆航线管理系统数据库表结构
-- 创建时间: 2025-12-17
-- 说明: 用于无人机航线管理与轨迹显示功能
-- 1. 航线任务表 (wayline_route)
-- 存储航线任务信息,关联航迹文件和设备
CREATE TABLE `wayline_route` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`route_id` VARCHAR(64) NOT NULL COMMENT '航线任务ID(UUID)',
`route_name` VARCHAR(100) NOT NULL COMMENT '航线任务名称',
`file_wayline_id` VARCHAR(64) NOT NULL COMMENT '关联航迹文件ID(wayline_file.wayline_id)',
`device_sn` VARCHAR(64) DEFAULT NULL COMMENT '绑定设备SN',
`device_name` VARCHAR(100) DEFAULT NULL COMMENT '设备名称(冗余)',
`parse_status` TINYINT DEFAULT 0 COMMENT '解析状态:0-未解析,1-解析中,2-已解析,3-解析失败',
`parse_error` VARCHAR(500) DEFAULT NULL COMMENT '解析错误信息',
`waypoint_count` INT DEFAULT 0 COMMENT '航点数量',
`action_count` INT DEFAULT 0 COMMENT '动作总数',
`total_distance` DECIMAL(10,2) DEFAULT NULL COMMENT '总航程(m)',
`total_duration` DECIMAL(10,2) DEFAULT NULL COMMENT '预计时长(s)',
`auto_flight_speed` DECIMAL(6,2) DEFAULT NULL COMMENT '自动飞行速度(m/s)',
`take_off_point` VARCHAR(100) DEFAULT NULL COMMENT '起飞点坐标(经度,纬度,高度)',
`finish_action` VARCHAR(50) DEFAULT NULL COMMENT '完成动作:goHome/hover/landing',
`exit_on_rc_lost` VARCHAR(50) DEFAULT NULL COMMENT '遥控器失联动作',
`global_rth_height` DECIMAL(6,2) DEFAULT NULL COMMENT '全局返航高度(m)',
`coordinate_mode` VARCHAR(20) DEFAULT 'WGS84' COMMENT '坐标系',
`height_mode` VARCHAR(50) DEFAULT 'relativeToStartPoint' COMMENT '高度模式',
`status` TINYINT DEFAULT 1 COMMENT '状态:0-禁用,1-启用',
`remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
`workspace_id` VARCHAR(64) DEFAULT NULL COMMENT '工作空间ID',
`tenant_id` VARCHAR(64) DEFAULT NULL COMMENT '租户ID',
`create_by` VARCHAR(64) DEFAULT NULL COMMENT '创建人',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_by` VARCHAR(64) DEFAULT NULL COMMENT '更新人',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_route_id` (`route_id`),
KEY `idx_file_wayline_id` (`file_wayline_id`),
KEY `idx_device_sn` (`device_sn`),
KEY `idx_parse_status` (`parse_status`),
KEY `idx_tenant_id` (`tenant_id`),
KEY `idx_workspace_id` (`workspace_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='航线任务表';
-- 2. 航点表 (wayline_waypoint)
-- 存储解析后的航点数据
CREATE TABLE `wayline_waypoint` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`route_id` VARCHAR(64) NOT NULL COMMENT '航线任务ID(关联wayline_route.route_id)',
`waypoint_index` INT NOT NULL COMMENT '航点序号(从0开始)',
`longitude` DECIMAL(12,9) NOT NULL COMMENT '经度',
`latitude` DECIMAL(12,9) NOT NULL COMMENT '纬度',
`height` DECIMAL(10,3) DEFAULT NULL COMMENT '相对高度(m)-相对起飞点',
`execute_height` DECIMAL(10,3) DEFAULT NULL COMMENT '执行高度(m)',
`ellipsoid_height` DECIMAL(10,3) DEFAULT NULL COMMENT '椭球高度(m)',
`speed` DECIMAL(6,2) DEFAULT NULL COMMENT '飞行速度(m/s)',
`heading_mode` VARCHAR(50) DEFAULT NULL COMMENT '航向模式',
`heading_angle` DECIMAL(6,2) DEFAULT NULL COMMENT '航向角(度)',
`gimbal_pitch_angle` DECIMAL(6,2) DEFAULT NULL COMMENT '云台俯仰角(度)',
`turn_mode` VARCHAR(64) DEFAULT NULL COMMENT '转弯模式',
`turn_damping_dist` DECIMAL(6,2) DEFAULT NULL COMMENT '转弯阻尼距离(m)',
`use_straight_line` TINYINT DEFAULT 1 COMMENT '是否直线飞行:0-否,1-是',
`is_risky` TINYINT DEFAULT 0 COMMENT '是否风险点:0-否,1-是',
`action_group_count` INT DEFAULT 0 COMMENT '动作组数量',
`tenant_id` VARCHAR(64) DEFAULT NULL COMMENT '租户ID',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_route_id` (`route_id`),
KEY `idx_waypoint_index` (`route_id`, `waypoint_index`),
KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='航线航点表';
-- 3. 航点动作表 (wayline_action)
-- 存储航点的动作数据
CREATE TABLE `wayline_action` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`waypoint_id` BIGINT NOT NULL COMMENT '航点ID(关联wayline_waypoint.id)',
`route_id` VARCHAR(64) NOT NULL COMMENT '航线任务ID(冗余字段,便于查询)',
`action_group_id` INT NOT NULL COMMENT '动作组ID',
`action_index` INT NOT NULL COMMENT '动作序号(组内)',
`action_type` VARCHAR(64) NOT NULL COMMENT '动作类型',
`action_params` JSON DEFAULT NULL COMMENT '动作参数(JSON格式)',
`trigger_type` VARCHAR(50) DEFAULT 'reachPoint' COMMENT '触发类型:reachPoint-到达航点,betweenAdjacentPoints-航点间',
`tenant_id` VARCHAR(64) DEFAULT NULL COMMENT '租户ID',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_waypoint_id` (`waypoint_id`),
KEY `idx_route_id` (`route_id`),
KEY `idx_action_type` (`action_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='航点动作表';
-- 4. 飞行轨迹表 (drone_flight_track)
-- 存储实时飞行轨迹数据
CREATE TABLE `drone_flight_track` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`device_sn` VARCHAR(64) NOT NULL COMMENT '设备SN',
`job_id` VARCHAR(64) DEFAULT NULL COMMENT '任务ID(关联wayline_job.job_id)',
`route_id` VARCHAR(64) DEFAULT NULL COMMENT '航线任务ID(关联wayline_route.route_id)',
`longitude` DECIMAL(12,9) NOT NULL COMMENT '经度',
`latitude` DECIMAL(12,9) NOT NULL COMMENT '纬度',
`altitude` DECIMAL(10,3) DEFAULT NULL COMMENT '海拔高度(m)',
`height` DECIMAL(10,3) DEFAULT NULL COMMENT '相对高度(m)',
`horizontal_speed` DECIMAL(6,2) DEFAULT NULL COMMENT '水平速度(m/s)',
`vertical_speed` DECIMAL(6,2) DEFAULT NULL COMMENT '垂直速度(m/s)',
`heading` DECIMAL(6,2) DEFAULT NULL COMMENT '航向角(度)',
`pitch` DECIMAL(6,2) DEFAULT NULL COMMENT '俯仰角(度)',
`roll` DECIMAL(6,2) DEFAULT NULL COMMENT '横滚角(度)',
`flight_mode` INT DEFAULT NULL COMMENT '飞行模式',
`battery_percent` INT DEFAULT NULL COMMENT '电池电量(%)',
`deviation_distance` DECIMAL(10,3) DEFAULT NULL COMMENT '偏离距离(m)-与计划航线的偏离',
`is_deviation` TINYINT DEFAULT 0 COMMENT '是否偏离:0-否,1-是',
`record_time` DATETIME NOT NULL COMMENT '记录时间(无人机上报时间)',
`tenant_id` VARCHAR(64) DEFAULT NULL COMMENT '租户ID',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `idx_device_sn` (`device_sn`),
KEY `idx_job_id` (`job_id`),
KEY `idx_route_id` (`route_id`),
KEY `idx_device_job` (`device_sn`, `job_id`),
KEY `idx_record_time` (`record_time`),
KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='无人机飞行轨迹表';
-- 添加外键约束(可选,根据实际需要决定是否添加)
-- ALTER TABLE `wayline_route` ADD CONSTRAINT `fk_route_file_wayline` FOREIGN KEY (`file_wayline_id`) REFERENCES `wayline_file` (`wayline_id`);
-- ALTER TABLE `wayline_waypoint` ADD CONSTRAINT `fk_waypoint_route` FOREIGN KEY (`route_id`) REFERENCES `wayline_route` (`route_id`);
-- ALTER TABLE `wayline_action` ADD CONSTRAINT `fk_action_waypoint` FOREIGN KEY (`waypoint_id`) REFERENCES `wayline_waypoint` (`id`);
-- 插入示例数据
INSERT INTO `wayline_route` (
`route_id`, `route_name`, `file_wayline_id`, `device_sn`, `device_name`,
`parse_status`, `waypoint_count`, `total_distance`, `total_duration`
) VALUES (
UUID(),
'平安寨巡检航线-无人机A',
'10df53e4b9114a87904fb010bc46922b',
'1ZNBJ1D00C00GH',
'巡检无人机A',
2,
8,
52.79,
114.7
);
-- 插入示例航点数据
INSERT INTO `wayline_waypoint` (
`route_id`, `waypoint_index`, `longitude`, `latitude`, `height`,
`speed`, `heading_angle`, `gimbal_pitch_angle`
) VALUES
('uuid-here', 0, 110.124939717, 25.760780235, 6.117, 0.3, -108.6, -36.73),
('uuid-here', 1, 110.124939768, 25.760780392, 2.9, 0.3, -108.6, -36.73),
('uuid-here', 2, 110.124939651, 25.760780383, 5.51, 0.3, -108.6, -36.73);
-- 插入示例动作数据
INSERT INTO `wayline_action` (
`waypoint_id`, `route_id`, `action_group_id`, `action_index`,
`action_type`, `action_params`
) VALUES
(1, 'uuid-here', 0, 0, 'rotateYaw', '{"heading": -108.354}'),
(1, 'uuid-here', 1, 0, 'takePhoto', '{}'),
(2, 'uuid-here', 0, 0, 'takePhoto', '{}');
@@ -89,7 +89,7 @@ public class TourismController {
@GetMapping("/{tourismId}/devices") @GetMapping("/{tourismId}/devices")
public Result getTourismDevices(@PathVariable("tourismId") Long tourismId) { public Result getTourismDevices(@PathVariable("tourismId") Long tourismId) {
try { try {
var devices = tourismService.getDevicesByTourismId(tourismId); List<Map<String, Object>> devices = tourismService.getDevicesByTourismId(tourismId);
return Result.succeed(devices, "获取景区设备列表成功"); return Result.succeed(devices, "获取景区设备列表成功");
} catch (Exception e) { } catch (Exception e) {
log.error("获取景区设备列表失败", e); log.error("获取景区设备列表失败", e);
-2
View File
@@ -4,8 +4,6 @@
* - 生产环境由网关/容器转发,此文件不生效 * - 生产环境由网关/容器转发,此文件不生效
*/ */
const GATEWAY = process.env.GATEWAY_ORIGIN || 'http://192.168.2.214:9900'; const GATEWAY = process.env.GATEWAY_ORIGIN || 'http://192.168.2.214:9900';
// WebSocket 网关地址(与 HTTP 网关相同)
const WS_GATEWAY = GATEWAY.replace('http://', 'ws://').replace('https://', 'wss://');
// SRS流媒体服务器地址 // SRS流媒体服务器地址
const SRS_SERVER = process.env.SRS_SERVER || 'http://220.205.16.27:8024'; const SRS_SERVER = process.env.SRS_SERVER || 'http://220.205.16.27:8024';
Binary file not shown.
@@ -0,0 +1,152 @@
import React, { useState, useEffect } from 'react';
import { Modal, Form, Select, message, Spin } from 'antd';
import { deviceApi } from '@/services/device';
import { waylineRouteApi } from '@/services/waylineRoute';
const { Option } = Select;
interface BindDeviceModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
wayline: any;
onSuccess?: () => void;
}
const BindDeviceModal: React.FC<BindDeviceModalProps> = ({
visible,
onVisibleChange,
wayline,
onSuccess
}) => {
const [form] = Form.useForm();
const [deviceList, setDeviceList] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [submitting, setSubmitting] = useState(false);
// 加载设备列表
const loadDeviceList = async () => {
setLoading(true);
try {
// 获取所有设备列表
const res = await deviceApi.deviceList({ page: 1, limit: 1000 });
if (res?.data) {
setDeviceList(res.data);
}
} catch (error) {
console.error('加载设备列表失败:', error);
message.error('加载设备列表失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
if (visible) {
loadDeviceList();
}
}, [visible]);
const handleOk = async () => {
try {
const values = await form.validateFields();
if (!values.deviceSn) {
message.error('请选择设备');
return;
}
setSubmitting(true);
const hide = message.loading('正在绑定设备...');
try {
// 调用后端接口,绑定设备并解析航线
const res = await waylineRouteApi.bindWaylineToDevice({
deviceSn: values.deviceSn,
waylineId: wayline.waylineId,
waylineName: wayline.name,
workspaceId: wayline.workspaceId
});
if (res.resp_code === 0) {
message.success('设备绑定成功,航线解析完成');
onSuccess?.();
handleCancel();
} else {
message.error(res.resp_msg || '绑定失败');
}
} catch (error: any) {
console.error('绑定设备失败:', error);
const errorMsg = error?.response?.data?.resp_msg || error?.message || '绑定失败';
message.error(errorMsg);
} finally {
hide();
setSubmitting(false);
}
} catch (error) {
// 表单验证失败
}
};
const handleCancel = () => {
form.resetFields();
onVisibleChange(false);
};
return (
<Modal
title="绑定设备"
open={visible}
onOk={handleOk}
onCancel={handleCancel}
confirmLoading={submitting}
width={600}
destroyOnClose
>
<Form
form={form}
layout="vertical"
initialValues={{
waylineName: wayline?.name,
waylineId: wayline?.waylineId
}}
>
<Form.Item label="航线名称">
<span>{wayline?.name}</span>
</Form.Item>
<Form.Item label="航线ID">
<span>{wayline?.waylineId}</span>
</Form.Item>
<Form.Item
label="选择设备"
name="deviceSn"
rules={[{ required: true, message: '请选择设备' }]}
>
<Select
placeholder="请选择要绑定的设备"
showSearch
filterOption={(input, option) =>
option?.children?.toString().toLowerCase().includes(input.toLowerCase())
}
loading={loading}
>
{deviceList.map(device => (
<Option key={device.deviceSn} value={device.deviceSn}>
{device.deviceName || device.deviceSn}
{device.deviceName && device.deviceSn && ` (${device.deviceSn})`}
</Option>
))}
</Select>
</Form.Item>
{deviceList.length === 0 && !loading && (
<div style={{ textAlign: 'center', color: '#999', padding: '20px 0' }}>
暂无可用设备
</div>
)}
</Form>
</Modal>
);
};
export default BindDeviceModal;
@@ -0,0 +1,292 @@
import React, { useState, useEffect } from 'react';
import { Modal, Table, Tag, Tabs, Card, Spin, message, Descriptions, Space } from 'antd';
import {
EnvironmentOutlined,
ControlOutlined,
ClockCircleOutlined,
NumberOutlined,
LineOutlined
} from '@ant-design/icons';
import { waylineRouteApi, WaypointVO, WaypointActionVO } from '@/services/waylineRoute';
const { TabPane } = Tabs;
interface WaylineDetailModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
wayline: any;
}
const WaylineDetailModal: React.FC<WaylineDetailModalProps> = ({
visible,
onVisibleChange,
wayline
}) => {
const [loading, setLoading] = useState(false);
const [routeDetail, setRouteDetail] = useState<any>(null);
const [activeTab, setActiveTab] = useState('waypoints');
useEffect(() => {
if (visible && wayline?.waylineId) {
loadRouteDetail();
}
}, [visible, wayline]);
const loadRouteDetail = async () => {
setLoading(true);
try {
// 首先通过waylineId获取航线任务列表,查找对应的routeId
const res = await waylineRouteApi.getRouteListByFileWaylineId(wayline.waylineId);
if (res.resp_code === 0 && res.data && res.data.length > 0) {
const routeId = res.data[0].routeId;
const detailRes = await waylineRouteApi.getRouteDetail(routeId);
if (detailRes.resp_code === 0) {
setRouteDetail(detailRes.data);
} else {
message.error('获取航线详情失败');
}
} else {
// 如果没有绑定的航线任务,提示用户
message.info('该航迹文件尚未绑定设备,请先绑定设备');
}
} catch (error) {
console.error('加载航线详情失败:', error);
message.error('加载航线详情失败');
} finally {
setLoading(false);
}
};
// 航点表格列定义
const waypointColumns = [
{
title: '序号',
dataIndex: 'index',
width: 60,
align: 'center',
},
{
title: '经度',
dataIndex: 'longitude',
width: 120,
render: (text: number) => text?.toFixed(6),
},
{
title: '纬度',
dataIndex: 'latitude',
width: 120,
render: (text: number) => text?.toFixed(6),
},
{
title: '高度(m)',
dataIndex: 'height',
width: 80,
align: 'center',
},
{
title: '速度(m/s)',
dataIndex: 'speed',
width: 80,
align: 'center',
},
{
title: '航向角(°)',
dataIndex: 'headingAngle',
width: 80,
align: 'center',
},
{
title: '直线飞行',
dataIndex: 'useStraightLine',
width: 80,
align: 'center',
render: (value: boolean) => (
<Tag color={value ? 'green' : 'blue'}>
{value ? '是' : '否'}
</Tag>
),
},
];
// 动作表格列定义
const actionColumns = [
{
title: '动作组',
dataIndex: 'actionGroupId',
width: 60,
align: 'center',
},
{
title: '序号',
dataIndex: 'actionIndex',
width: 60,
align: 'center',
},
{
title: '动作类型',
dataIndex: 'actionType',
width: 120,
render: (text: string) => {
const colors: Record<string, string> = {
'fly': 'blue',
'rotate': 'green',
'gimbal': 'orange',
'camera': 'purple',
'hover': 'cyan',
};
return <Tag color={colors[text] || 'default'}>{text}</Tag>;
},
},
{
title: '触发类型',
dataIndex: 'triggerType',
width: 100,
render: (text: string) => {
const colors: Record<string, string> = {
'trigger': 'red',
'time': 'green',
'distance': 'blue',
};
return <Tag color={colors[text] || 'default'}>{text}</Tag>;
},
},
{
title: '延迟时间(ms)',
dataIndex: 'delayTime',
width: 100,
align: 'center',
},
{
title: '悬停时间(s)',
dataIndex: 'hoverTime',
width: 100,
align: 'center',
},
{
title: '航向角(°)',
dataIndex: 'aircraftHeading',
width: 80,
align: 'center',
},
];
return (
<Modal
title={`航迹详情 - ${wayline?.name}`}
open={visible}
onCancel={() => onVisibleChange(false)}
footer={null}
width={1000}
style={{ top: 20 }}
>
<Spin spinning={loading}>
{routeDetail ? (
<div>
{/* 基本信息 */}
<Card size="small" style={{ marginBottom: 16 }}>
<Descriptions title="航线信息" size="small" column={3}>
<Descriptions.Item label="航线名称">
{routeDetail.routeInfo?.routeName}
</Descriptions.Item>
<Descriptions.Item label="航点数量">
<NumberOutlined style={{ marginRight: 4 }} />
{routeDetail.totalWaypoints}个
</Descriptions.Item>
<Descriptions.Item label="动作数量">
<ControlOutlined style={{ marginRight: 4 }} />
{routeDetail.totalActions}个
</Descriptions.Item>
<Descriptions.Item label="总航程">
<LineOutlined style={{ marginRight: 4 }} />
{routeDetail.totalDistance?.toFixed(2)}米
</Descriptions.Item>
<Descriptions.Item label="预计时长">
<ClockCircleOutlined style={{ marginRight: 4 }} />
{routeDetail.totalDuration?.toFixed(2)}秒
</Descriptions.Item>
<Descriptions.Item label="解析状态">
<Tag color={routeDetail.routeInfo?.parseStatus === 2 ? 'green' : 'orange'}>
{routeDetail.routeInfo?.parseStatusDesc}
</Tag>
</Descriptions.Item>
</Descriptions>
</Card>
{/* 航点和动作详情 */}
<Tabs activeKey={activeTab} onChange={setActiveTab}>
<TabPane
tab={
<span>
<EnvironmentOutlined />
航点列表 ({routeDetail.waypoints?.length || 0})
</span>
}
key="waypoints"
>
<Table
columns={waypointColumns}
dataSource={routeDetail.waypoints || []}
rowKey="index"
size="small"
pagination={{
pageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
}}
scroll={{ x: 600 }}
/>
</TabPane>
<TabPane
tab={
<span>
<ControlOutlined />
动作列表 ({routeDetail.actions?.length || 0})
</span>
}
key="actions"
>
<Table
columns={actionColumns}
dataSource={routeDetail.actions || []}
rowKey={(record) => `${record.actionGroupId}-${record.actionIndex}`}
size="small"
pagination={{
pageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
}}
scroll={{ x: 700 }}
expandable={{
expandedRowRender: (record: WaypointActionVO) => {
if (!record.actionParams || Object.keys(record.actionParams).length === 0) {
return <div style={{ color: '#999' }}>无参数</div>;
}
return (
<div style={{ margin: 0 }}>
{Object.entries(record.actionParams).map(([key, value]) => (
<Space key={key} style={{ marginBottom: 4 }}>
<span style={{ color: '#666' }}>{key}:</span>
<span>{String(value)}</span>
</Space>
))}
</div>
);
},
rowExpandable: (record) => record.actionParams && Object.keys(record.actionParams).length > 0,
}}
/>
</TabPane>
</Tabs>
</div>
) : (
<div style={{ textAlign: 'center', padding: '50px 0', color: '#999' }}>
暂无数据或该航迹文件尚未绑定设备
</div>
)}
</Spin>
</Modal>
);
};
export default WaylineDetailModal;
@@ -3,7 +3,7 @@ import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components'; import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components'; import type { ProColumns } from '@ant-design/pro-components';
import { Space, message } from 'antd'; import { Space, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons'; import { DownloadOutlined, LinkOutlined, EyeOutlined } from '@ant-design/icons';
import { deviceApi } from '@/services/device'; import { deviceApi } from '@/services/device';
import { downloadByUrl } from '@/utils/download'; import { downloadByUrl } from '@/utils/download';
@@ -15,9 +15,11 @@ interface WaylineTableProps {
params?: Record<string, any>; params?: Record<string, any>;
onEdit?: (record: any) => void; onEdit?: (record: any) => void;
onDelete?: (record: any) => void; onDelete?: (record: any) => void;
onBindDevice?: (record: any) => void;
onViewDetail?: (record: any) => void;
} }
const WaylineTable = forwardRef<WaylineTableRef, WaylineTableProps>(({ params, onEdit, onDelete }, ref) => { const WaylineTable = forwardRef<WaylineTableRef, WaylineTableProps>(({ params, onEdit, onDelete, onBindDevice, onViewDetail }, ref) => {
const actionRef = useRef<ActionType>(); const actionRef = useRef<ActionType>();
useImperativeHandle(ref, () => ({ reload: () => actionRef.current?.reload() })); useImperativeHandle(ref, () => ({ reload: () => actionRef.current?.reload() }));
@@ -80,6 +82,12 @@ const WaylineTable = forwardRef<WaylineTableRef, WaylineTableProps>(({ params, o
<a onClick={() => handleDownload(record)} title="下载航线文件"> <a onClick={() => handleDownload(record)} title="下载航线文件">
<DownloadOutlined /> 下载 <DownloadOutlined /> 下载
</a> </a>
<a onClick={() => onBindDevice?.(record)} title="绑定设备">
<LinkOutlined /> 绑定设备
</a>
<a onClick={() => onViewDetail?.(record)} title="查看详情">
<EyeOutlined /> 详情
</a>
<a style={{ color: '#1677ff' }} onClick={() => onDelete?.(record)}>删除</a> <a style={{ color: '#1677ff' }} onClick={() => onDelete?.(record)}>删除</a>
</Space> </Space>
) )
@@ -5,6 +5,8 @@ import { PlusOutlined } from '@ant-design/icons';
import { deviceApi } from '@/services/device'; import { deviceApi } from '@/services/device';
import WaylineTable, { WaylineTableRef } from './components/WaylineTable'; import WaylineTable, { WaylineTableRef } from './components/WaylineTable';
import WaylineForm, { WaylineFormValues } from './components/WaylineForm'; import WaylineForm, { WaylineFormValues } from './components/WaylineForm';
import BindDeviceModal from './components/BindDeviceModal';
import WaylineDetailModal from './components/WaylineDetailModal';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui'; import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
const WaylinePage: React.FC = () => { const WaylinePage: React.FC = () => {
@@ -13,6 +15,10 @@ const WaylinePage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<any | null>(null); const [current, setCurrent] = useState<any | null>(null);
const [bindDeviceOpen, setBindDeviceOpen] = useState(false);
const [selectedWayline, setSelectedWayline] = useState<any | null>(null);
const [detailOpen, setDetailOpen] = useState(false);
const [detailWayline, setDetailWayline] = useState<any | null>(null);
const add = async (values: WaylineFormValues) => { const add = async (values: WaylineFormValues) => {
const hide = message.loading('保存中...'); const hide = message.loading('保存中...');
@@ -60,6 +66,16 @@ const WaylinePage: React.FC = () => {
}); });
}; };
const handleBindDevice = (record: any) => {
setSelectedWayline(record);
setBindDeviceOpen(true);
};
const handleViewDetail = (record: any) => {
setDetailWayline(record);
setDetailOpen(true);
};
return ( return (
<PageContainer header={{ title: '航线管理' }}> <PageContainer header={{ title: '航线管理' }}>
<SearchBarPlus <SearchBarPlus
@@ -81,12 +97,29 @@ const WaylinePage: React.FC = () => {
params={query} params={query}
onEdit={(r) => { setCurrent(r); setEditOpen(true); }} onEdit={(r) => { setCurrent(r); setEditOpen(true); }}
onDelete={(r) => del(r)} onDelete={(r) => del(r)}
onBindDevice={handleBindDevice}
onViewDetail={handleViewDetail}
/> />
</GlassCard> </GlassCard>
<WaylineForm title="新增航线" visible={createOpen} onVisibleChange={setCreateOpen} onFinish={add} /> <WaylineForm title="新增航线" visible={createOpen} onVisibleChange={setCreateOpen} onFinish={add} />
<WaylineForm title="编辑航线" visible={editOpen} onVisibleChange={setEditOpen} onFinish={edit} initialValues={current || {}} /> <WaylineForm title="编辑航线" visible={editOpen} onVisibleChange={setEditOpen} onFinish={edit} initialValues={current || {}} />
<BindDeviceModal
visible={bindDeviceOpen}
onVisibleChange={setBindDeviceOpen}
wayline={selectedWayline}
onSuccess={() => {
tableRef.current?.reload();
}}
/>
<WaylineDetailModal
visible={detailOpen}
onVisibleChange={setDetailOpen}
wayline={detailWayline}
/>
</PageContainer> </PageContainer>
); );
}; };
@@ -525,6 +525,23 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
} }
}, [handleMouseMove]); }, [handleMouseMove]);
// 关闭面板时,主动断开所有连接
const handleClose = () => {
// 1. 断开设备控制服务
deviceControlWs.disconnect();
// 2. 断开无人机SSE连接(会调用后端接口取消订阅)
if (deviceSn) {
disconnectDroneSSE(deviceSn);
}
// 3. 重置无人机数据
resetDroneData();
// 4. 退出DRC模式
setDrcMode(false);
drcModeRef.current = false;
// 5. 调用父组件的关闭回调
onClose();
};
// 视频尺寸切换 // 视频尺寸切换
const handleVideoSizeToggle = () => { const handleVideoSizeToggle = () => {
if (videoSize === 'normal') { if (videoSize === 'normal') {
@@ -665,7 +682,7 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
<span className={styles.voltage}>{flightData.vol}V</span> <span className={styles.voltage}>{flightData.vol}V</span>
</div> </div>
</div> </div>
<button className={styles.closeBtn} onClick={onClose} onMouseDown={e => e.stopPropagation()}> <button className={styles.closeBtn} onClick={handleClose} onMouseDown={e => e.stopPropagation()}>
<CloseOutlined /> <CloseOutlined />
</button> </button>
</div> </div>
@@ -12,7 +12,7 @@
top: 64px; top: 64px;
right: 0; right: 0;
bottom: 0; bottom: 0;
width: 420px; // 稍微加宽一点 width: 360px; // 减小宽度避免滚动条
background: linear-gradient( background: linear-gradient(
135deg, 135deg,
rgba(6, 12, 20, 0.98) 0%, rgba(6, 12, 20, 0.98) 0%,
@@ -225,6 +225,50 @@
border-left: 2px solid @cyan; border-left: 2px solid @cyan;
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 1px; letter-spacing: 1px;
display: flex;
justify-content: space-between;
align-items: center;
.takeoffBtn {
padding: 4px 10px;
font-size: 11px;
background: linear-gradient(135deg, rgba(255, 77, 79, 0.25), rgba(0, 255, 136, 0.25));
border: 1px solid @neon-green;
color: @neon-green;
cursor: pointer;
transition: all 0.3s;
display: flex;
align-items: center;
gap: 4px;
text-transform: none;
letter-spacing: 0;
position: relative;
overflow: hidden;
&::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(90deg, @neon-red, @neon-green);
opacity: 0.15;
z-index: -1;
}
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(255, 77, 79, 0.35), rgba(0, 255, 136, 0.35));
box-shadow: 0 0 12px rgba(0, 255, 136, 0.4), 0 0 8px rgba(255, 77, 79, 0.3);
border-color: @neon-green;
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
filter: grayscale(0.5);
}
}
} }
.grid { .grid {
@@ -256,28 +300,39 @@
} }
.actions { .actions {
display: grid; display: flex;
grid-template-columns: 1fr 1fr; flex-direction: column;
gap: 12px; gap: 10px;
margin-top: 32px; margin-top: 24px;
.actionRow {
display: flex;
gap: 10px;
button {
flex: 1;
}
}
button { button {
padding: 12px; padding: 10px 12px;
background: rgba(0, 240, 255, 0.1); background: rgba(0, 240, 255, 0.1);
border: 1px solid rgba(0, 240, 255, 0.3); border: 1px solid rgba(0, 240, 255, 0.3);
color: @cyan; color: @cyan;
font-weight: 600; font-weight: 600;
font-size: 13px;
cursor: pointer; cursor: pointer;
transition: all 0.3s; transition: all 0.3s;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 8px; gap: 6px;
white-space: nowrap;
&:hover:not(:disabled) { &:hover:not(:disabled) {
background: rgba(0, 240, 255, 0.2); background: rgba(0, 240, 255, 0.2);
box-shadow: 0 0 15px rgba(0, 240, 255, 0.2); box-shadow: 0 0 15px rgba(0, 240, 255, 0.2);
transform: translateY(-2px); transform: translateY(-1px);
} }
&:disabled { opacity: 0.5; cursor: not-allowed; filter: grayscale(1); } &:disabled { opacity: 0.5; cursor: not-allowed; filter: grayscale(1); }
@@ -289,6 +344,16 @@
text-shadow: none; text-shadow: none;
&:hover:not(:disabled) { background: rgba(0, 240, 255, 0.4); } &:hover:not(:disabled) { background: rgba(0, 240, 255, 0.4); }
} }
&.task {
background: rgba(255, 170, 0, 0.15);
border-color: @neon-orange;
color: @neon-orange;
&:hover:not(:disabled) {
background: rgba(255, 170, 0, 0.25);
box-shadow: 0 0 15px rgba(255, 170, 0, 0.2);
}
}
} }
} }
} }
@@ -10,6 +10,8 @@ import {
DashboardOutlined, DashboardOutlined,
SignalFilled, SignalFilled,
LoadingOutlined, LoadingOutlined,
AimOutlined,
UnorderedListOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { deviceApi } from '@/services/device'; import { deviceApi } from '@/services/device';
import { ordersApi } from '@/services/orders'; import { ordersApi } from '@/services/orders';
@@ -23,13 +25,19 @@ interface RightPanelProps {
tourism: any; tourism: any;
onClose: () => void; onClose: () => void;
onControlClick: (device: any, realtimeData: any) => void; onControlClick: (device: any, realtimeData: any) => void;
onTaskPanelOpen?: (device: any) => void; // 打开任务管理面板回调
viewer?: any; // Cesium Viewer 实例
Cesium?: any; // Cesium 库
} }
const RightPanel: React.FC<RightPanelProps> = ({ const RightPanel: React.FC<RightPanelProps> = ({
visible, visible,
tourism, tourism,
onClose, onClose,
onControlClick onControlClick,
onTaskPanelOpen,
viewer,
Cesium
}) => { }) => {
const [deviceList, setDeviceList] = useState<any[]>([]); const [deviceList, setDeviceList] = useState<any[]>([]);
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>(''); const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
@@ -81,6 +89,16 @@ const RightPanel: React.FC<RightPanelProps> = ({
if (deviceSn !== selectedDeviceSn) setSelectedDeviceSn(deviceSn); if (deviceSn !== selectedDeviceSn) setSelectedDeviceSn(deviceSn);
}; };
// 关闭面板时,主动断开SSE连接
const handleClose = () => {
// 先断开SSE连接
if (selectedDeviceSn) {
disconnectSSE(selectedDeviceSn);
}
// 然后调用父组件的关闭回调
onClose();
};
const selectedDevice = deviceList.find((d) => d.deviceSn === selectedDeviceSn); const selectedDevice = deviceList.find((d) => d.deviceSn === selectedDeviceSn);
const dockData = realtimeData?.rawData?.dockData; const dockData = realtimeData?.rawData?.dockData;
const battery = realtimeData?.battery ?? 0; const battery = realtimeData?.battery ?? 0;
@@ -192,7 +210,7 @@ const RightPanel: React.FC<RightPanelProps> = ({
</div> </div>
<div className={styles.subTitle}>{deviceList.length} DEVICES ONLINE</div> <div className={styles.subTitle}>{deviceList.length} DEVICES ONLINE</div>
</div> </div>
<button className={styles.closeBtn} onClick={onClose}><CloseOutlined /></button> <button className={styles.closeBtn} onClick={handleClose}><CloseOutlined /></button>
</div> </div>
</div> </div>
@@ -235,7 +253,16 @@ const RightPanel: React.FC<RightPanelProps> = ({
{/* Block A: 机库信息 */} {/* Block A: 机库信息 */}
<div className={styles.section}> <div className={styles.section}>
<div className={styles.sectionHeader}>机库信息 / DOCK INFO</div> <div className={styles.sectionHeader}>
<span>机库信息 / DOCK INFO</span>
<button
className={styles.takeoffBtn}
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0}
onClick={handleTakeoff}
>
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞
</button>
</div>
{/* 状态卡片 */} {/* 状态卡片 */}
<div className={styles.statusCard}> <div className={styles.statusCard}>
@@ -273,15 +300,14 @@ const RightPanel: React.FC<RightPanelProps> = ({
{/* 操作区 */} {/* 操作区 */}
<div className={styles.actions}> <div className={styles.actions}>
<button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}> <div className={styles.actionRow}>
<VideoCameraOutlined /> 进入操控台 <button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}>
</button> <VideoCameraOutlined /> 进入操控台
<button </button>
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0} <button className={styles.task} onClick={() => onTaskPanelOpen?.(selectedDevice)}>
onClick={handleTakeoff} <UnorderedListOutlined /> 任务管理
> </button>
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞 </div>
</button>
</div> </div>
</div> </div>
</TabPane> </TabPane>
@@ -337,6 +363,7 @@ const RightPanel: React.FC<RightPanelProps> = ({
)} )}
</Spin> </Spin>
</div> </div>
</div> </div>
); );
}; };
@@ -0,0 +1,512 @@
@cyan: #00f0ff;
@neon-green: #00ff88;
@neon-orange: #ffaa00;
@neon-red: #ff4d4f;
.taskPanel {
position: absolute;
bottom: 160px;
left: 20px;
width: 360px;
max-height: 500px;
background: linear-gradient(
135deg,
rgba(6, 12, 20, 0.96) 0%,
rgba(10, 25, 40, 0.94) 100%
);
backdrop-filter: blur(12px);
border: 1px solid rgba(0, 240, 255, 0.2);
border-radius: 8px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), 0 0 20px rgba(0, 240, 255, 0.1);
color: #fff;
z-index: 1001;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
display: flex;
flex-direction: column;
&.visible {
opacity: 1;
visibility: visible;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 14px;
background: rgba(0, 20, 40, 0.5);
border-bottom: 1px solid rgba(0, 240, 255, 0.15);
border-radius: 8px 8px 0 0;
cursor: move;
user-select: none;
flex-shrink: 0;
.title {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 600;
color: @cyan;
.deviceTag {
font-size: 10px;
font-weight: normal;
background: rgba(0, 240, 255, 0.15);
padding: 2px 6px;
border-radius: 3px;
color: rgba(255, 255, 255, 0.7);
}
}
.headerActions {
display: flex;
align-items: center;
gap: 6px;
}
.iconBtn, .closeBtn {
background: none;
border: none;
color: rgba(255, 255, 255, 0.6);
font-size: 13px;
cursor: pointer;
padding: 5px;
border-radius: 4px;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: rgba(255, 255, 255, 0.1);
color: @cyan;
}
}
.closeBtn:hover {
background: rgba(255, 77, 79, 0.2);
color: @neon-red;
}
}
.content {
flex: 1;
overflow: hidden;
display: flex;
flex-direction: column;
}
.tabs {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
:global {
.ant-tabs-nav {
margin: 0;
padding: 0 12px;
background: rgba(0, 0, 0, 0.2);
.ant-tabs-tab {
padding: 8px 12px;
color: rgba(255, 255, 255, 0.6);
font-size: 13px;
&:hover {
color: @cyan;
}
&.ant-tabs-tab-active .ant-tabs-tab-btn {
color: @cyan;
}
}
.ant-tabs-ink-bar {
background: @cyan;
}
}
.ant-tabs-content-holder {
flex: 1;
overflow: hidden;
}
.ant-tabs-content {
height: 100%;
}
.ant-tabs-tabpane {
height: 100%;
overflow: hidden;
}
}
}
.tabContent {
padding: 12px;
height: 100%;
overflow-y: auto;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.02);
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 240, 255, 0.2);
border-radius: 2px;
&:hover {
background: rgba(0, 240, 255, 0.3);
}
}
}
.section {
margin-bottom: 14px;
&:last-child {
margin-bottom: 0;
}
}
.sectionTitle {
font-size: 12px;
font-weight: 600;
margin-bottom: 8px;
color: rgba(255, 255, 255, 0.7);
padding-left: 8px;
border-left: 2px solid @cyan;
}
.infoGrid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
background: rgba(0, 0, 0, 0.2);
border-radius: 6px;
padding: 10px;
.infoItem {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
.label {
font-size: 10px;
color: rgba(255, 255, 255, 0.4);
}
.value {
font-size: 13px;
color: @cyan;
font-family: 'Consolas', monospace;
font-weight: 500;
}
}
}
.createBtn {
background: linear-gradient(135deg, rgba(0, 240, 255, 0.2), rgba(0, 100, 255, 0.2)) !important;
border: 1px solid rgba(0, 240, 255, 0.4) !important;
color: @cyan !important;
font-weight: 600;
height: 36px;
transition: all 0.3s;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 240, 255, 0.3), rgba(0, 100, 255, 0.3)) !important;
border-color: @cyan !important;
box-shadow: 0 0 15px rgba(0, 240, 255, 0.2);
}
&:disabled {
opacity: 0.5;
}
}
.taskList {
max-height: 180px;
overflow-y: auto;
background: rgba(0, 0, 0, 0.2);
border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.05);
&::-webkit-scrollbar {
width: 3px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 240, 255, 0.2);
border-radius: 2px;
}
}
.taskItem {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
cursor: pointer;
transition: all 0.2s;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
&:last-child {
border-bottom: none;
}
&:hover {
background: rgba(0, 240, 255, 0.05);
}
&.selected {
background: rgba(0, 240, 255, 0.1);
border-left: 3px solid @cyan;
}
.taskInfo {
flex: 1;
min-width: 0;
.taskName {
font-size: 12px;
font-weight: 500;
color: #fff;
margin-bottom: 3px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.taskMeta {
display: flex;
gap: 10px;
font-size: 10px;
color: rgba(255, 255, 255, 0.5);
.status {
padding: 1px 5px;
border-radius: 3px;
&.status0 {
background: rgba(255, 170, 0, 0.2);
color: @neon-orange;
}
&.status1 {
background: rgba(0, 240, 255, 0.2);
color: @cyan;
}
&.status2 {
background: rgba(0, 255, 136, 0.2);
color: @neon-green;
}
&.status3 {
background: rgba(255, 77, 79, 0.2);
color: @neon-red;
}
}
}
}
.taskActions {
display: flex;
gap: 4px;
margin-left: 8px;
}
.actionBtn {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.6);
width: 26px;
height: 26px;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
&:hover {
background: rgba(0, 240, 255, 0.1);
border-color: rgba(0, 240, 255, 0.3);
color: @cyan;
}
}
}
.loading {
padding: 20px;
text-align: center;
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
}
.emptyState {
padding: 20px 0;
:global {
.ant-empty-description {
color: rgba(255, 255, 255, 0.4);
font-size: 12px;
}
.ant-empty-image svg {
fill: rgba(255, 255, 255, 0.2);
}
}
}
.legend {
display: flex;
gap: 16px;
padding: 8px 10px;
background: rgba(0, 0, 0, 0.2);
border-radius: 6px;
.legendItem {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
color: rgba(255, 255, 255, 0.7);
.legendLine {
width: 20px;
height: 3px;
border-radius: 2px;
&.blue {
background: #1890ff;
box-shadow: 0 0 4px rgba(24, 144, 255, 0.5);
}
&.green {
background: #52c41a;
box-shadow: 0 0 4px rgba(82, 196, 26, 0.5);
}
}
.legendPoint {
width: 8px;
height: 8px;
border-radius: 50%;
background: @neon-red;
box-shadow: 0 0 4px rgba(255, 77, 79, 0.5);
}
}
}
.realtimeInfo {
padding: 10px 12px;
background: rgba(0, 0, 0, 0.3);
border-top: 1px solid rgba(0, 240, 255, 0.1);
flex-shrink: 0;
.realtimeTitle {
font-size: 11px;
font-weight: 600;
color: rgba(255, 255, 255, 0.7);
margin-bottom: 6px;
display: flex;
align-items: center;
gap: 5px;
.locateBtn {
margin-left: auto;
background: rgba(0, 240, 255, 0.15);
border: 1px solid rgba(0, 240, 255, 0.3);
color: @cyan;
width: 24px;
height: 24px;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
&:hover {
background: rgba(0, 240, 255, 0.3);
border-color: @cyan;
}
}
}
.coordsGrid {
display: flex;
gap: 12px;
font-size: 11px;
color: @cyan;
font-family: 'Consolas', monospace;
}
}
// Select 组件样式覆盖
:global {
.ant-select {
.ant-select-selector {
background: rgba(0, 0, 0, 0.3) !important;
border-color: rgba(0, 240, 255, 0.2) !important;
color: #fff !important;
height: 34px !important;
.ant-select-selection-placeholder {
color: rgba(255, 255, 255, 0.4);
}
.ant-select-selection-item {
color: #fff;
}
}
&:hover .ant-select-selector {
border-color: @cyan !important;
}
&.ant-select-focused .ant-select-selector {
border-color: @cyan !important;
box-shadow: 0 0 8px rgba(0, 240, 255, 0.2) !important;
}
.ant-select-arrow {
color: rgba(255, 255, 255, 0.5);
}
.ant-select-clear {
background: transparent;
color: rgba(255, 255, 255, 0.5);
&:hover {
color: @neon-red;
}
}
}
.ant-select-dropdown {
background: rgba(10, 20, 40, 0.98) !important;
border: 1px solid rgba(0, 240, 255, 0.2);
.ant-select-item {
color: rgba(255, 255, 255, 0.8);
&:hover {
background: rgba(0, 240, 255, 0.1);
}
&.ant-select-item-option-selected {
background: rgba(0, 240, 255, 0.2);
color: @cyan;
}
}
}
}
}
@@ -0,0 +1,777 @@
import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { Button, message, Tooltip, Empty, Image, Select, Tabs } from 'antd';
import {
CloseOutlined,
PlusOutlined,
EyeOutlined,
EnvironmentOutlined,
PictureOutlined,
ReloadOutlined,
FileTextOutlined,
SendOutlined,
UnorderedListOutlined,
AimOutlined,
} from '@ant-design/icons';
import { useDroneSSE } from '../hooks/useDroneSSE';
import { waylineRouteApi, WaylineRouteListItemVO, WaypointVO } from '@/services/waylineRoute';
import styles from './TaskPanel.less';
const { TabPane } = Tabs;
interface TaskPanelProps {
visible: boolean;
onClose: () => void;
device: any;
viewer?: any;
Cesium?: any;
}
// 任务数据结构(后端未实现,先定义好接口)
interface TaskItem {
taskId: string;
taskName: string;
routeId: string;
routeName: string;
deviceSn: string;
status: number; // 0-待执行 1-执行中 2-已完成 3-失败
statusDesc: string;
createTime: string;
images?: string[];
}
const TaskPanel: React.FC<TaskPanelProps> = ({
visible,
onClose,
device,
viewer,
Cesium,
}) => {
const deviceSn = device?.deviceSn;
// SSE hook
const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE();
// 航线相关状态
const [routeList, setRouteList] = useState<WaylineRouteListItemVO[]>([]);
const [selectedRouteId, setSelectedRouteId] = useState<string | null>(null);
const [waypoints, setWaypoints] = useState<WaypointVO[]>([]);
const [routeLoading, setRouteLoading] = useState(false);
// 任务相关状态
const [taskList, setTaskList] = useState<TaskItem[]>([]);
const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);
const [taskLoading, setTaskLoading] = useState(false);
const [imagePreviewVisible, setImagePreviewVisible] = useState(false);
const [previewImages, setPreviewImages] = useState<string[]>([]);
// Tab 状态
const [activeTab, setActiveTab] = useState<string>('route');
// 拖拽状态
const [position, setPosition] = useState({ x: 0, y: 0 });
const draggingRef = useRef(false);
const lastPosRef = useRef({ x: 0, y: 0 });
const rafRef = useRef<number | null>(null);
const pendingPosRef = useRef({ x: 0, y: 0 });
// 地图图层引用
const waylineEntityRef = useRef<any>(null);
const waypointEntitiesRef = useRef<any[]>([]);
const droneEntityRef = useRef<any>(null);
const flightTrackEntityRef = useRef<any>(null);
const trackPositionsRef = useRef<any[]>([]);
const hasFlownToDroneRef = useRef<boolean>(false); // 是否已经飞到过无人机位置
const lastUpdateTimeRef = useRef<number>(0); // 上次更新时间
const lastPositionRef = useRef<{ lon: number; lat: number; height: number } | null>(null); // 上次位置
// 实时位置 - 区分相对高度和海拔高度
const realtimePosition = useMemo(() => {
if (!droneData) return null;
return {
longitude: droneData.longitude,
latitude: droneData.latitude,
height: droneData.height, // 相对高度(相对于起飞点)
elevation: droneData.elevation, // 海拔高度
// 3D地图显示用的高度:直接使用相对高度 height
altitude: droneData.height,
heading: droneData.attitude_head,
timestamp: Date.now(),
};
}, [droneData]);
// 初始化
useEffect(() => {
if (visible && deviceSn) {
connectDroneSSE(deviceSn);
loadRoutesByDevice(deviceSn);
loadTasksByDevice(deviceSn);
return () => {
disconnectDroneSSE(deviceSn);
resetDroneData();
clearMapLayers();
};
} else {
setPosition({ x: 0, y: 0 });
trackPositionsRef.current = [];
hasFlownToDroneRef.current = false;
setSelectedRouteId(null);
setSelectedTaskId(null);
}
}, [visible, deviceSn]);
// 调试:监测 props 变化
useEffect(() => {
console.log('[TaskPanel] props变化:', {
visible,
hasViewer: !!viewer,
hasCesium: !!Cesium,
deviceSn,
});
}, [visible, viewer, Cesium, deviceSn]);
// 实时位置更新 - 绘制无人机和航迹(节流:1秒更新一次,或位置变化时更新)
useEffect(() => {
if (!visible || !viewer || !Cesium || !realtimePosition) return;
if (viewer.isDestroyed?.()) return;
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
const now = Date.now();
const currentPos = {
lon: realtimePosition.longitude,
lat: realtimePosition.latitude,
height: realtimePosition.height ?? 0,
};
// 检查是否需要更新:1秒内且位置没变化则跳过
const timeSinceLastUpdate = now - lastUpdateTimeRef.current;
const lastPos = lastPositionRef.current;
if (lastPos && timeSinceLastUpdate < 1000) {
// 检查位置是否有明显变化(经纬度变化超过0.00001度,约1米;高度变化超过0.5米)
const posChanged =
Math.abs(currentPos.lon - lastPos.lon) > 0.00001 ||
Math.abs(currentPos.lat - lastPos.lat) > 0.00001 ||
Math.abs(currentPos.height - lastPos.height) > 0.5;
if (!posChanged) {
return; // 位置没变化且不到1秒,跳过更新
}
}
// 更新时间和位置记录
lastUpdateTimeRef.current = now;
lastPositionRef.current = currentPos;
const displayHeight = realtimePosition.height ?? 50;
try {
const pos = Cesium.Cartesian3.fromDegrees(
realtimePosition.longitude,
realtimePosition.latitude,
displayHeight
);
const labelText = `无人机 H:${realtimePosition.height != null ? realtimePosition.height.toFixed(0) : '--'}m`;
// 更新或创建无人机entity
if (droneEntityRef.current) {
droneEntityRef.current.position = pos;
if (droneEntityRef.current.label) {
droneEntityRef.current.label.text = labelText;
}
} else {
droneEntityRef.current = viewer.entities.add({
name: '无人机实时位置',
position: pos,
point: {
pixelSize: 16,
color: Cesium.Color.RED,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 3,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: labelText,
font: '14px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -20),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
console.log('[TaskPanel] 创建无人机entity');
}
// 添加航迹点(只有位置变化才添加)
trackPositionsRef.current.push(pos);
// 绘制飞行轨迹
if (trackPositionsRef.current.length >= 2) {
if (flightTrackEntityRef.current) {
flightTrackEntityRef.current.polyline.positions = [...trackPositionsRef.current];
} else {
flightTrackEntityRef.current = viewer.entities.add({
name: '飞行轨迹',
polyline: {
positions: [...trackPositionsRef.current],
width: 4,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3,
color: Cesium.Color.LIME,
}),
clampToGround: false,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
console.log('[TaskPanel] 创建飞行轨迹entity');
}
}
// 强制渲染
viewer.scene.requestRender();
// 首次收到位置数据时,自动飞到无人机位置
if (!hasFlownToDroneRef.current && trackPositionsRef.current.length === 1) {
hasFlownToDroneRef.current = true;
flyToDrone();
}
} catch (error) {
console.error('[TaskPanel] 更新无人机位置出错:', error);
}
}, [realtimePosition, visible, viewer, Cesium]);
// 飞到无人机位置
const flyToDrone = useCallback(() => {
if (!viewer || !Cesium || !realtimePosition) {
message.warning('暂无无人机位置数据');
return;
}
if (!realtimePosition.longitude || !realtimePosition.latitude) {
message.warning('无人机位置数据无效');
return;
}
const droneHeight = realtimePosition.height ?? 50;
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
realtimePosition.longitude,
realtimePosition.latitude,
droneHeight + 100 // 视角高度比无人机高100米
),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90), // 垂直俯视
roll: 0,
},
duration: 1.5,
});
message.success('已飞到无人机位置');
}, [viewer, Cesium, realtimePosition]);
// 加载航线列表
const loadRoutesByDevice = useCallback(async (sn: string) => {
try {
setRouteLoading(true);
const res = await waylineRouteApi.getRouteListByDevice(sn);
if (res.resp_code === 0) {
setRouteList(res.data || []);
}
} catch (e) {
message.error('加载航线列表失败');
} finally {
setRouteLoading(false);
}
}, []);
// 加载任务列表(后端未实现,使用模拟数据)
const loadTasksByDevice = useCallback(async (sn: string) => {
try {
setTaskLoading(true);
// TODO: 调用后端接口 - waylineRouteApi.getTaskListByDevice(sn)
// 模拟数据
await new Promise(resolve => setTimeout(resolve, 500));
setTaskList([
// 暂无任务,等后端实现
]);
} catch (e) {
message.error('加载任务列表失败');
} finally {
setTaskLoading(false);
}
}, []);
// 加载航点并绘制
const loadWaypoints = useCallback(async (routeId: string) => {
try {
const res = await waylineRouteApi.getRouteWaypoints(routeId);
if (res.resp_code === 0 && res.data?.length) {
setWaypoints(res.data);
if (viewer && Cesium) {
drawWaylineOnMap(res.data);
}
}
} catch (e) {
message.error('加载航点失败');
}
}, [viewer, Cesium]);
// 绘制航线
const drawWaylineOnMap = useCallback((waypoints: WaypointVO[]) => {
if (!viewer || !Cesium || !waypoints.length) return;
clearWaylineEntities();
const positions = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height || 100)
);
// 计划航线(蓝色)
waylineEntityRef.current = viewer.entities.add({
name: '计划航线',
polyline: {
positions: positions,
width: 3,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.2,
color: Cesium.Color.fromCssColorString('#1890ff'),
}),
clampToGround: false,
},
});
// 航点标记 - 只标注关键航点(首尾和间隔点)避免重叠
const totalPoints = waypoints.length;
// 根据航点数量决定标注间隔:超过20个点时每5个标一个,超过50个每10个标一个
const labelInterval = totalPoints > 50 ? 10 : totalPoints > 20 ? 5 : totalPoints > 10 ? 3 : 1;
waypoints.forEach((wp, index) => {
const isFirst = index === 0;
const isLast = index === totalPoints - 1;
const isKeyPoint = isFirst || isLast || (index % labelInterval === 0);
// 航点统一用蓝色系,起点用深蓝,终点用紫色,中间用浅蓝
// 避免与无人机(红色)和飞行轨迹(绿色)混淆
const pointColor = isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff';
const entity = viewer.entities.add({
name: `航点${index + 1}`,
position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height || 100),
point: {
pixelSize: isKeyPoint ? 8 : 5, // 关键点稍大,普通点更小
color: Cesium.Color.fromCssColorString(pointColor),
outlineColor: Cesium.Color.WHITE,
outlineWidth: isKeyPoint ? 2 : 1,
},
label: isKeyPoint ? {
text: isFirst ? '起' : isLast ? '终' : `${index + 1}`,
font: '10px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -10),
scaleByDistance: new Cesium.NearFarScalar(100, 1.0, 5000, 0.5), // 远处缩小
} : undefined, // 非关键点不显示标签
});
waypointEntitiesRef.current.push(entity);
});
// 飞到航线
flyToWayline(waypoints);
}, [viewer, Cesium]);
// 飞到航线位置 - 垂直俯视整条航线
const flyToWayline = useCallback((waypoints: WaypointVO[]) => {
if (!viewer || !Cesium || !waypoints.length) return;
let minLon = Infinity, maxLon = -Infinity;
let minLat = Infinity, maxLat = -Infinity;
let maxHeight = 0;
waypoints.forEach(wp => {
minLon = Math.min(minLon, wp.longitude);
maxLon = Math.max(maxLon, wp.longitude);
minLat = Math.min(minLat, wp.latitude);
maxLat = Math.max(maxLat, wp.latitude);
maxHeight = Math.max(maxHeight, wp.height || 100);
});
const centerLon = (minLon + maxLon) / 2;
const centerLat = (minLat + maxLat) / 2;
// 计算航线范围的对角线距离(经纬度转换为大约的米数)
const lonSpan = maxLon - minLon;
const latSpan = maxLat - minLat;
// 1度经度约111km(在赤道),纬度方向约111km
const spanMeters = Math.sqrt(
Math.pow(lonSpan * 111000 * Math.cos(centerLat * Math.PI / 180), 2) +
Math.pow(latSpan * 111000, 2)
);
// 视角高度:航线范围的0.2倍 + 最高航点高度
// 更贴近航线
const viewHeight = Math.max(spanMeters * 0.2, 30) + maxHeight;
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, viewHeight),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90), // 垂直俯视,确保航迹在正下方
roll: 0,
},
duration: 1.5,
});
}, [viewer, Cesium]);
// 检查 viewer 是否有效
const isViewerValid = useCallback(() => {
return viewer && !viewer.isDestroyed?.();
}, [viewer]);
// 清除航线图层
const clearWaylineEntities = useCallback(() => {
if (!isViewerValid()) return;
if (waylineEntityRef.current) {
try {
viewer.entities.remove(waylineEntityRef.current);
} catch (e) {}
waylineEntityRef.current = null;
}
waypointEntitiesRef.current.forEach(entity => {
try {
viewer.entities.remove(entity);
} catch (e) {}
});
waypointEntitiesRef.current = [];
}, [viewer, isViewerValid]);
// 清除所有图层
const clearMapLayers = useCallback(() => {
if (!isViewerValid()) return;
clearWaylineEntities();
if (droneEntityRef.current) {
try {
viewer.entities.remove(droneEntityRef.current);
} catch (e) {}
droneEntityRef.current = null;
}
if (flightTrackEntityRef.current) {
try {
viewer.entities.remove(flightTrackEntityRef.current);
} catch (e) {}
flightTrackEntityRef.current = null;
}
trackPositionsRef.current = [];
}, [viewer, isViewerValid, clearWaylineEntities]);
// 选择航线
const handleSelectRoute = useCallback((routeId: string) => {
setSelectedRouteId(routeId);
loadWaypoints(routeId);
}, [loadWaypoints]);
// 创建任务
const handleCreateTask = useCallback(async () => {
if (!selectedRouteId) {
message.warning('请先选择一条航线');
return;
}
const selectedRoute = routeList.find(r => r.routeId === selectedRouteId);
if (!selectedRoute) return;
// TODO: 调用后端接口创建任务
// await waylineRouteApi.createTask({
// routeId: selectedRouteId,
// routeName: selectedRoute.routeName,
// deviceSn: deviceSn,
// });
message.info('创建任务功能待后端实现');
}, [selectedRouteId, routeList, deviceSn]);
// 查看任务图片
const handleViewTaskImages = useCallback(async (task: TaskItem) => {
// TODO: 调用后端接口获取任务图片
// const res = await waylineRouteApi.getTaskImages(task.taskId);
// setPreviewImages(res.data || []);
// 模拟数据
setPreviewImages([
'https://via.placeholder.com/800x600?text=Task+Image+1',
'https://via.placeholder.com/800x600?text=Task+Image+2',
]);
setImagePreviewVisible(true);
}, []);
// 刷新
const handleRefresh = useCallback(() => {
if (deviceSn) {
loadRoutesByDevice(deviceSn);
loadTasksByDevice(deviceSn);
message.success('刷新成功');
}
}, [deviceSn, loadRoutesByDevice, loadTasksByDevice]);
// 关闭面板时,主动断开SSE连接
const handleClose = useCallback(() => {
// 1. 断开无人机SSE连接(会调用后端接口取消订阅)
if (deviceSn) {
disconnectDroneSSE(deviceSn);
}
// 2. 重置无人机数据
resetDroneData();
// 3. 清除地图图层
clearMapLayers();
// 4. 调用父组件的关闭回调
onClose();
}, [deviceSn, disconnectDroneSSE, resetDroneData, clearMapLayers, onClose]);
// 拖拽
const handleMouseDown = (e: React.MouseEvent) => {
e.preventDefault();
draggingRef.current = true;
lastPosRef.current = { x: e.clientX, y: e.clientY };
pendingPosRef.current = { ...position };
document.body.style.userSelect = 'none';
document.body.style.cursor = 'grabbing';
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
const handleMouseMove = useCallback((e: MouseEvent) => {
if (!draggingRef.current) return;
const dx = e.clientX - lastPosRef.current.x;
const dy = e.clientY - lastPosRef.current.y;
lastPosRef.current = { x: e.clientX, y: e.clientY };
pendingPosRef.current = {
x: pendingPosRef.current.x + dx,
y: pendingPosRef.current.y + dy
};
if (rafRef.current) cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => {
setPosition({ ...pendingPosRef.current });
});
}, []);
const handleMouseUp = useCallback(() => {
draggingRef.current = false;
document.body.style.userSelect = '';
document.body.style.cursor = '';
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
}, [handleMouseMove]);
const selectedRoute = routeList.find(r => r.routeId === selectedRouteId);
return (
<div
className={`${styles.taskPanel} ${visible ? styles.visible : ''}`}
style={{ transform: visible ? `translate(${position.x}px, ${position.y}px)` : undefined }}
>
{/* 标题栏 */}
<div className={styles.header} onMouseDown={handleMouseDown}>
<div className={styles.title}>
<FileTextOutlined />
<span>任务管理</span>
{deviceSn && <span className={styles.deviceTag}>{deviceSn}</span>}
</div>
<div className={styles.headerActions}>
<Tooltip title="刷新">
<button className={styles.iconBtn} onClick={handleRefresh}>
<ReloadOutlined />
</button>
</Tooltip>
<button className={styles.closeBtn} onClick={handleClose}>
<CloseOutlined />
</button>
</div>
</div>
{/* 内容区 */}
<div className={styles.content}>
<Tabs activeKey={activeTab} onChange={setActiveTab} className={styles.tabs}>
{/* 航线 Tab */}
<TabPane tab={<span><EnvironmentOutlined /> 航线</span>} key="route">
<div className={styles.tabContent}>
{/* 航线选择 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>选择航线</div>
<Select
placeholder="请选择航线"
style={{ width: '100%' }}
value={selectedRouteId}
onChange={handleSelectRoute}
loading={routeLoading}
allowClear
onClear={() => {
setSelectedRouteId(null);
clearWaylineEntities();
}}
>
{routeList.map(route => (
<Select.Option key={route.routeId} value={route.routeId}>
{route.routeName} ({route.waypointCount}个航点)
</Select.Option>
))}
</Select>
</div>
{/* 航线详情 */}
{selectedRoute && (
<div className={styles.section}>
<div className={styles.sectionTitle}>航线详情</div>
<div className={styles.infoGrid}>
<div className={styles.infoItem}>
<span className={styles.label}>航点数</span>
<span className={styles.value}>{selectedRoute.waypointCount}</span>
</div>
<div className={styles.infoItem}>
<span className={styles.label}>总距离</span>
<span className={styles.value}>{(selectedRoute.totalDistance / 1000).toFixed(2)} km</span>
</div>
<div className={styles.infoItem}>
<span className={styles.label}>预计时长</span>
<span className={styles.value}>{Math.ceil(selectedRoute.totalDuration / 60)} 分钟</span>
</div>
</div>
</div>
)}
{/* 创建任务按钮 */}
<div className={styles.section}>
<Button
type="primary"
icon={<PlusOutlined />}
block
onClick={handleCreateTask}
disabled={!selectedRouteId}
className={styles.createBtn}
>
基于此航线创建任务
</Button>
</div>
{/* 图例 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>图例</div>
<div className={styles.legend}>
<div className={styles.legendItem}>
<span className={`${styles.legendLine} ${styles.blue}`}></span>
<span>计划航线</span>
</div>
<div className={styles.legendItem}>
<span className={`${styles.legendLine} ${styles.green}`}></span>
<span>飞行轨迹</span>
</div>
<div className={styles.legendItem}>
<span className={styles.legendPoint}></span>
<span>无人机</span>
</div>
</div>
</div>
</div>
</TabPane>
{/* 任务 Tab */}
<TabPane tab={<span><UnorderedListOutlined /> 任务</span>} key="task">
<div className={styles.tabContent}>
{/* 任务列表 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>任务列表</div>
<div className={styles.taskList}>
{taskLoading ? (
<div className={styles.loading}>加载中...</div>
) : taskList.length === 0 ? (
<Empty
description="暂无任务,请先创建"
image={Empty.PRESENTED_IMAGE_SIMPLE}
className={styles.emptyState}
/>
) : (
taskList.map(task => (
<div
key={task.taskId}
className={`${styles.taskItem} ${selectedTaskId === task.taskId ? styles.selected : ''}`}
onClick={() => setSelectedTaskId(task.taskId)}
>
<div className={styles.taskInfo}>
<div className={styles.taskName}>{task.taskName}</div>
<div className={styles.taskMeta}>
<span className={`${styles.status} ${styles[`status${task.status}`]}`}>
{task.statusDesc}
</span>
<span>{task.createTime}</span>
</div>
</div>
<div className={styles.taskActions}>
<Tooltip title="查看图片">
<button
className={styles.actionBtn}
onClick={(e) => {
e.stopPropagation();
handleViewTaskImages(task);
}}
>
<PictureOutlined />
</button>
</Tooltip>
</div>
</div>
))
)}
</div>
</div>
</div>
</TabPane>
</Tabs>
{/* 实时位置 */}
{realtimePosition && realtimePosition.longitude && (
<div className={styles.realtimeInfo}>
<div className={styles.realtimeTitle}>
<EnvironmentOutlined /> 无人机实时位置
<Tooltip title="飞到无人机位置">
<button className={styles.locateBtn} onClick={flyToDrone}>
<AimOutlined />
</button>
</Tooltip>
</div>
<div className={styles.coordsGrid}>
<span>经度: {realtimePosition.longitude?.toFixed(6)}</span>
<span>纬度: {realtimePosition.latitude?.toFixed(6)}</span>
</div>
<div className={styles.coordsGrid} style={{ marginTop: 4 }}>
<span>相对高度: {realtimePosition.height != null ? `${realtimePosition.height.toFixed(1)}m` : '--'}</span>
<span>海拔高度: {realtimePosition.elevation != null ? `${realtimePosition.elevation.toFixed(1)}m` : '--'}</span>
</div>
</div>
)}
</div>
{/* 图片预览 */}
<Image.PreviewGroup
preview={{
visible: imagePreviewVisible,
onVisibleChange: (vis) => setImagePreviewVisible(vis),
}}
>
{previewImages.map((src, index) => (
<Image key={index} src={src} style={{ display: 'none' }} />
))}
</Image.PreviewGroup>
</div>
);
};
export default TaskPanel;
@@ -108,22 +108,41 @@ export function useDeviceSSE(): UseDeviceSSEResult {
const maxReconnectAttempts = 10; const maxReconnectAttempts = 10;
const shouldReconnectRef = useRef<boolean>(true); const shouldReconnectRef = useRef<boolean>(true);
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用 // 核心断开逻辑 - 使用 fetch DELETE 请求(正常关闭时调用)
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => { const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
if (!deviceSn || !token) return; if (!deviceSn || !token) return;
// 尝试使用 fetch keepalive const deleteUrl = `/api-device/sse/device-status/${deviceSn}`;
fetch(`/api-device/sse/device-status/${deviceSn}`, {
// 使用 fetch DELETE 请求(带 Authorization header)
fetch(deleteUrl, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': sessionId, 'X-Client-Session-Id': sessionId,
}, },
keepalive: true, keepalive: true,
}).catch(err => console.error('Disconnect fetch failed:', err)); }).then(() => {
console.log('[DeviceSSE] DELETE 断开请求成功:', deviceSn);
}).catch((e) => {
console.warn('[DeviceSSE] DELETE 断开请求失败:', e);
});
};
// 备用方案:如果支持 Beacon 且后端允许 POST 处理断开 (通常 API 设计为 DELETE,Beacon 不适用,故仅作备注) // beforeunload 专用断开逻辑(浏览器刷新/关闭时用 sendBeacon)
// navigator.sendBeacon(...) 仅支持 POST const performBeaconDisconnect = (deviceSn: string, sessionId: string) => {
if (!deviceSn) return;
const beaconUrl = `/api-device/sse/device-status/${deviceSn}/disconnect`;
if (navigator.sendBeacon) {
const blob = new Blob(
[JSON.stringify({ sessionId })],
{ type: 'application/json' }
);
navigator.sendBeacon(beaconUrl, blob);
console.log('[DeviceSSE] sendBeacon 断开请求已发送:', deviceSn);
}
}; };
// 断开SSE连接 // 断开SSE连接
@@ -323,12 +342,12 @@ export function useDeviceSSE(): UseDeviceSSEResult {
doConnect(deviceSn); doConnect(deviceSn);
}, [disconnectSSE, doConnect]); }, [disconnectSSE, doConnect]);
// 监听浏览器刷新/关闭事件 (beforeunload) // 监听浏览器刷新/关闭事件 (beforeunload) - 使用 sendBeacon
useEffect(() => { useEffect(() => {
const handleBeforeUnload = () => { const handleBeforeUnload = () => {
if (currentDeviceSnRef.current) { if (currentDeviceSnRef.current) {
const token = sessionStorage.getItem('access_token'); // 浏览器刷新/关闭时用 sendBeacon(不需要 token,后端需要配置允许匿名访问)
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token); performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current);
} }
}; };
@@ -108,19 +108,41 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
const maxReconnectAttempts = 10; const maxReconnectAttempts = 10;
const shouldReconnectRef = useRef<boolean>(true); // 是否应该自动重连 const shouldReconnectRef = useRef<boolean>(true); // 是否应该自动重连
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用 // 核心断开逻辑 - 使用 fetch DELETE 请求(正常关闭时调用)
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => { const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
if (!deviceSn || !token) return; if (!deviceSn || !token) return;
// 尝试使用 fetch keepalive const deleteUrl = `/api-device/sse/drone-telemetry/${deviceSn}`;
fetch(`/api-device/sse/drone-telemetry/${deviceSn}`, {
// 使用 fetch DELETE 请求(带 Authorization header)
fetch(deleteUrl, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': sessionId, 'X-Client-Session-Id': sessionId,
}, },
keepalive: true, keepalive: true,
}).catch(() => {}); }).then(() => {
console.log('[DroneSSE] DELETE 断开请求成功:', deviceSn);
}).catch((e) => {
console.warn('[DroneSSE] DELETE 断开请求失败:', e);
});
};
// beforeunload 专用断开逻辑(浏览器刷新/关闭时用 sendBeacon)
const performBeaconDisconnect = (deviceSn: string, sessionId: string) => {
if (!deviceSn) return;
const beaconUrl = `/api-device/sse/drone-telemetry/${deviceSn}/disconnect`;
if (navigator.sendBeacon) {
const blob = new Blob(
[JSON.stringify({ sessionId })],
{ type: 'application/json' }
);
navigator.sendBeacon(beaconUrl, blob);
console.log('[DroneSSE] sendBeacon 断开请求已发送:', deviceSn);
}
}; };
// 断开无人机SSE连接 // 断开无人机SSE连接
@@ -350,7 +372,23 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
dataReceivedRef.current = false; dataReceivedRef.current = false;
}, []); }, []);
// 组件卸载时自动断开连接 // 监听浏览器刷新/关闭事件 (beforeunload) - 使用 sendBeacon
useEffect(() => {
const handleBeforeUnload = () => {
if (currentDeviceSnRef.current) {
// 浏览器刷新/关闭时用 sendBeacon(不需要 token,后端需要配置允许匿名访问)
performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current);
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
// 组件卸载时自动断开连接 (React Unmount)
useEffect(() => { useEffect(() => {
return () => { return () => {
// 清理重连定时器 // 清理重连定时器
@@ -359,11 +397,17 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
reconnectTimerRef.current = null; reconnectTimerRef.current = null;
} }
shouldReconnectRef.current = false; shouldReconnectRef.current = false;
// 在组件卸载时,也尝试发送断开请求
if (currentDeviceSnRef.current) { if (currentDeviceSnRef.current) {
disconnectDroneSSE(currentDeviceSnRef.current); const token = sessionStorage.getItem('access_token');
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
} }
}; };
}, [disconnectDroneSSE]); }, []);
return { return {
// 状态 // 状态
@@ -3,6 +3,7 @@ import { message, Button, Tooltip } from 'antd';
import { AppstoreOutlined } from '@ant-design/icons'; import { AppstoreOutlined } from '@ant-design/icons';
import RightPanel from './3d/BottomPanel/RightPanel'; import RightPanel from './3d/BottomPanel/RightPanel';
import LeftControlPanel from './3d/BottomPanel/LeftControlPanel'; import LeftControlPanel from './3d/BottomPanel/LeftControlPanel';
import TaskPanel from './3d/BottomPanel/TaskPanel';
import TilesetPanel from './3d/TilesetPanel'; import TilesetPanel from './3d/TilesetPanel';
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader'; import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
import { getModelsByTourismId, convertToTilesetConfig } from '@/services/threeDModel'; import { getModelsByTourismId, convertToTilesetConfig } from '@/services/threeDModel';
@@ -32,6 +33,10 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const [controlDevice, setControlDevice] = useState<any>(null); const [controlDevice, setControlDevice] = useState<any>(null);
const [controlRealtimeData, setControlRealtimeData] = useState<any>(null); const [controlRealtimeData, setControlRealtimeData] = useState<any>(null);
// 任务管理面板状态
const [taskPanelVisible, setTaskPanelVisible] = useState(false);
const [taskPanelDevice, setTaskPanelDevice] = useState<any>(null);
// 3D Tiles 模型管理 // 3D Tiles 模型管理
const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false); const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false);
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的所有模型配置 const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的所有模型配置
@@ -50,6 +55,8 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 相机飞到景区 // 相机飞到景区
const flyToTourism = useCallback((tourism: any) => { const flyToTourism = useCallback((tourism: any) => {
if (!viewerRef.current || !Cesium) return; if (!viewerRef.current || !Cesium) return;
// 检查 viewer 是否已销毁
if (viewerRef.current.isDestroyed?.()) return;
const lon = parseFloat(tourism.longitude); const lon = parseFloat(tourism.longitude);
const lat = parseFloat(tourism.latitude); const lat = parseFloat(tourism.latitude);
@@ -70,6 +77,8 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 相机飞回全球视角 // 相机飞回全球视角
const flyToGlobal = useCallback(() => { const flyToGlobal = useCallback(() => {
if (!viewerRef.current || !Cesium) return; if (!viewerRef.current || !Cesium) return;
// 检查 viewer 是否已销毁
if (viewerRef.current.isDestroyed?.()) return;
viewerRef.current.camera.flyTo({ viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000), destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000),
@@ -279,6 +288,8 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 如果有模型会自动飞到模型位置,没有模型才飞到景区位置 // 如果有模型会自动飞到模型位置,没有模型才飞到景区位置
if (tourism.id) { if (tourism.id) {
loadTourismModels(tourism.id).then((hasModel) => { loadTourismModels(tourism.id).then((hasModel) => {
// 异步回调时检查 viewer 是否还存在
if (!viewerRef.current || viewerRef.current.isDestroyed?.()) return;
if (!hasModel) { if (!hasModel) {
flyToTourism(tourism); flyToTourism(tourism);
} }
@@ -302,6 +313,12 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
setLeftPanelVisible(true); setLeftPanelVisible(true);
}, []); }, []);
// 处理从右侧面板点击"任务管理"
const handleOpenTaskPanel = useCallback((device: any) => {
setTaskPanelDevice(device);
setTaskPanelVisible(true);
}, []);
// 获取设备的视频流地址(从设备数据中获取) // 获取设备的视频流地址(从设备数据中获取)
const getVideoStreamUrl = useCallback((device: any): string | undefined => { const getVideoStreamUrl = useCallback((device: any): string | undefined => {
// 从设备配置获取视频流地址 // 从设备配置获取视频流地址
@@ -672,6 +689,18 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
tourism={selectedTourism} tourism={selectedTourism}
onClose={handleRightPanelClose} onClose={handleRightPanelClose}
onControlClick={handleOpenControl} onControlClick={handleOpenControl}
onTaskPanelOpen={handleOpenTaskPanel}
viewer={viewerRef.current}
Cesium={Cesium}
/>
{/* 任务管理面板 - 左下角独立渲染 */}
<TaskPanel
visible={taskPanelVisible}
onClose={() => setTaskPanelVisible(false)}
device={taskPanelDevice}
viewer={viewerRef.current}
Cesium={Cesium}
/> />
</div> </div>
); );
+28 -10
View File
@@ -5,12 +5,32 @@
// SRS 服务器配置 // SRS 服务器配置
const SRS_CONFIG = { const SRS_CONFIG = {
// 开发环境通过代理访问,生产环境直接访问 // 所有环境都通过代理访问,避免跨域问题
baseUrl: process.env.NODE_ENV === 'development' ? '' : 'http://220.205.16.27:8024', // 开发环境: webpack devServer 代理
// 测试/生产环境: nginx 代理
baseUrl: '',
// 登录密码 // 登录密码
password: 'a6949674ed817fa3', password: 'a6949674ed817fa3',
}; };
// WebRTC ICE 服务器配置(用于 NAT 穿透)
// 必须与 SRS 服务器配置的 STUN/TURN 一致
const ICE_SERVERS: RTCConfiguration = {
iceServers: [
// 自建 STUN 服务器
{ urls: 'stun:220.205.16.27:3478' },
// 自建 TURN 服务器(用于复杂 NAT 环境)
{
urls: 'turn:220.205.16.27:3478?transport=udp',
username: 'webrtc',
credential: 'GoFly@2024',
},
// 备用 Google STUN(可选)
{ urls: 'stun:stun.l.google.com:19302' },
],
iceCandidatePoolSize: 10,
};
// 存储 token // 存储 token
let srsToken: string | null = null; let srsToken: string | null = null;
let tokenExpireTime: number = 0; let tokenExpireTime: number = 0;
@@ -113,8 +133,8 @@ export const srsApi = {
const url = srsApi.buildWhepUrl(streamId, options?.app); const url = srsApi.buildWhepUrl(streamId, options?.app);
// 创建 RTCPeerConnection // 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透)
const pc = new RTCPeerConnection(); const pc = new RTCPeerConnection(ICE_SERVERS);
const stream = new MediaStream(); const stream = new MediaStream();
// 设置接收音视频轨道 // 设置接收音视频轨道
@@ -183,16 +203,14 @@ export const srsApi = {
try { try {
// 解析 URL,提取路径部分通过代理访问(避免跨域) // 解析 URL,提取路径部分通过代理访问(避免跨域)
const urlObj = new URL(whepUrl); const urlObj = new URL(whepUrl);
// 开发环境使用代理路径,生产环境使用完整 URL // 所有环境都使用代理路径,避免跨域问题
const actualUrl = process.env.NODE_ENV === 'development' const actualUrl = `${urlObj.pathname}${urlObj.search}`;
? `${urlObj.pathname}${urlObj.search}` // 只使用路径和查询参数,通过代理访问
: whepUrl;
// 确保已登录 // 确保已登录
const token = await srsApi.getToken(); const token = await srsApi.getToken();
// 创建 RTCPeerConnection // 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透)
const pc = new RTCPeerConnection(); const pc = new RTCPeerConnection(ICE_SERVERS);
const stream = new MediaStream(); const stream = new MediaStream();
// 设置接收音视频轨道 // 设置接收音视频轨道
@@ -0,0 +1,194 @@
import { request } from 'umi';
// 航线任务列表项
export interface WaylineRouteListItemVO {
routeId: string;
routeName: string;
fileWaylineId: string;
deviceSn: string;
deviceName: string;
parseStatus: number;
parseStatusDesc?: string;
waypointCount: number;
totalDistance: number;
totalDuration: number;
createTime: string;
}
// 航点数据
export interface WaypointVO {
index: number;
longitude: number;
latitude: number;
height: number;
speed?: number;
headingAngle?: number;
actions?: WaypointActionVO[];
}
// 轨迹点数据
export interface TrackPointVO {
lng: number;
lat: number;
alt?: number;
height?: number;
speed?: number;
heading?: number;
batteryPercent?: number;
time?: string;
deviationDistance?: number;
isDeviation?: boolean;
}
// 航点动作数据
export interface WaypointActionVO {
actionGroupId?: number;
actionIndex?: number;
actionType?: string;
actionTypeDesc?: string;
actionParams?: Record<string, any>;
triggerType?: string;
triggerTypeDesc?: string;
delayTime?: number;
payloadPositionIndex?: number;
hoverTime?: number;
aircraftHeading?: number;
gimbalPitchRotateAngle?: number;
gimbalYawRotateAngle?: number;
focalLength?: number;
megaphoneFilePath?: string;
}
// 创建航线任务参数
export interface CreateRouteParams {
routeName: string;
fileWaylineId: string;
deviceSn: string;
deviceName?: string;
remark?: string;
}
// 航线任务详情
export interface WaylineRouteDetailVO {
routeId: string;
routeName: string;
fileWaylineId: string;
deviceSn: string;
deviceName: string;
parseStatus: number;
parseStatusDesc?: string;
waypointCount: number;
totalDistance: number;
totalDuration: number;
waypoints?: WaypointVO[];
}
// 飞行轨迹数据
export interface FlightTrackData {
deviceSn: string;
jobId?: string;
routeId?: string;
trackPoints: TrackPointVO[];
totalPoints: number;
duration: number;
startTime?: string;
endTime?: string;
}
// 航线任务详情(完整版)
export interface RouteDetailVO {
routeInfo: WaylineRouteListItemVO;
waypoints: WaypointVO[];
actions: WaypointActionVO[];
totalWaypoints: number;
totalActions: number;
totalDistance: number;
totalDuration: number;
}
export const waylineRouteApi = {
// ★ 创建航线任务(关联航迹文件和设备)
createRoute: (params: CreateRouteParams) =>
request('/api-device/device/route/create', { method: 'POST', data: params }),
// ★ 核心接口:根据设备SN获取绑定的航线任务列表(任务管理页面使用)
getRouteListByDevice: (deviceSn: string) =>
request(`/api-device/device/route/listByDevice/${deviceSn}`) as Promise<{ resp_code: number; data: WaylineRouteListItemVO[] }>,
// 获取航线任务详情(含航点)
getRouteDetails: (routeId: string) =>
request(`/api-device/device/route/detail/${routeId}`) as Promise<{ resp_code: number; data: WaylineRouteDetailVO }>,
// 获取航点列表(3D地图绑制航线使用)
getRouteWaypoints: (routeId: string) =>
request(`/api-device/device/route/waypoints/${routeId}`) as Promise<{ resp_code: number; data: WaypointVO[] }>,
// 解析航线任务
parseRoute: (routeId: string) =>
request(`/api-device/device/route/parse/${routeId}`, { method: 'POST' }),
// 批量解析航线任务
batchParseRoutes: (routeIds: string[]) =>
request('/api-device/device/route/parse/batch', { method: 'POST', data: routeIds }),
// 获取飞行轨迹
getFlightTrack: (
deviceSn: string,
params?: {
jobId?: string;
routeId?: string;
startTime?: string;
endTime?: string;
limit?: number;
}
) =>
request(`/api-device/device/drone/track/${deviceSn}`, { params }) as Promise<{ resp_code: number; data: FlightTrackData }>,
// 获取最新轨迹点
getLatestTrackPoint: (deviceSn: string) =>
request(`/api-device/device/drone/track/latest/${deviceSn}`) as Promise<{ resp_code: number; data: TrackPointVO }>,
// 删除历史轨迹
deleteHistoryTracks: (deviceSn: string, beforeTime: string) =>
request(`/api-device/device/drone/track/history/${deviceSn}`, {
method: 'DELETE',
params: { beforeTime },
}),
// 统计轨迹点数量
countTrackPoints: (
deviceSn: string,
params?: {
jobId?: string;
routeId?: string;
startTime?: string;
endTime?: string;
}
) =>
request(`/api-device/device/drone/track/count/${deviceSn}`, { params }) as Promise<{ resp_code: number; data: number }>,
// 获取无人机设备列表(航线管理表单中选择设备使用)
getDroneDeviceList: () =>
request('/api-device/device/drone/list') as Promise<{ resp_code: number; data: Array<{ sn: string; deviceName: string }> }>,
// 获取航迹文件列表(创建航线任务时选择航迹文件使用)
getWaylineFileList: (params?: any) =>
request('/api-device/device/wayline', { params }) as Promise<{ resp_code: number; data: Array<{ waylineId: string; name: string }> }>,
// 根据航迹文件ID获取航线任务列表
getRouteListByFileWaylineId: (fileWaylineId: string) =>
request(`/api-device/device/route/listByFileWaylineId/${fileWaylineId}`) as Promise<{ resp_code: number; data: WaylineRouteListItemVO[] }>,
// 获取航线任务详情(含航点和动作)
getRouteDetail: (routeId: string) =>
request(`/api-device/device/route/detail/${routeId}`) as Promise<{ resp_code: number; data: RouteDetailVO }>,
// 绑定航迹文件到设备并解析航线
bindWaylineToDevice: (params: {
deviceSn: string;
waylineId: string;
waylineName: string;
workspaceId?: string;
}) =>
request('/api-device/device/route/bindWaylineToDevice', { method: 'POST', data: params }),
};