diff --git a/WebSocket订阅机制审计报告.md b/WebSocket订阅机制审计报告.md new file mode 100644 index 00000000..8f92fc2c --- /dev/null +++ b/WebSocket订阅机制审计报告.md @@ -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\ | 全局订阅状态,跨实例共享 | +| **WebSocket订阅** | JetLinksWebSocketClient | `subscribedTopics` (Set\) | 本地已订阅主题列表 | +| **设备订阅计数** | JetLinksWebSocketClient | `deviceSubscriptionCounts` (Map\) | 本地设备订阅计数 | +| **本地引用计数** | SseEmitterManager | `deviceRefCount` (Map\) | 本地设备引用计数(快速查询) | + +### 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 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 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的主题管理逻辑 diff --git a/zlt-business/device-center/doc/无人机航线管理与轨迹显示实现文档.md b/zlt-business/device-center/doc/无人机航线管理与轨迹显示实现文档.md new file mode 100644 index 00000000..c2dbc783 --- /dev/null +++ b/zlt-business/device-center/doc/无人机航线管理与轨迹显示实现文档.md @@ -0,0 +1,1964 @@ +# 无人机航线管理与轨迹显示实现文档 + +## 文档信息 + +| 项目 | 内容 | +|------|------------| +| 版本 | v1.0 | +| 作者 | dzc | +| 日期 | 2025-12-17 | +| 状态 | 设计阶段 | + +--- + +## 一、需求概述 + +### 1.1 业务背景 + +在景区无人机巡检场景中,需要实现以下核心功能: +1. **航线轨迹展示**:在3D地图上根据大疆航线文件中的经纬度显示预设航线轨迹 +2. **实时飞行轨迹**:无人机起飞后,根据实时上报的经纬度显示飞行轨迹 +3. **轨迹对比**:通过不同颜色区分计划航线和实际轨迹,确保无人机按照预定航线飞行 + +### 1.2 现状分析 + +| 模块 | 现状 | 问题 | +|------|------|------| +| 航线管理 | 已有`wayline_file`表存储航迹文件元数据 | 仅存储文件引用,未解析航点数据 | +| 设备管理 | 已有`manage_device`表管理无人机设备 | 航线与设备无绑定关系 | +| 实时数据 | 已有WebSocket推送无人机位置 | 未存储历史轨迹数据 | +| 3D地图 | 已有Cesium地图组件 | 未实现航线轨迹绑定功能 | + +### 1.3 目标 + +- 解析大疆KMZ航迹文件,结构化存储航点和动作数据 +- 建立航线与设备的绑定关系 +- 在3D地图上展示计划航线和实时轨迹 +- 记录无人机飞行历史轨迹,支持轨迹回放 + +--- + +## 二、大疆KMZ文件格式分析 + +### 2.1 文件结构 + +``` +*.kmz (ZIP压缩包) +└── wpmz/ + ├── template.kml # 模板文件(航线业务配置) + ├── waylines.wpml # 执行文件(飞行执行细节) + └── res/ # 资源文件夹 + └── audio/ # 喊话音频文件 +``` + +### 2.2 template.kml 关键元素 + +```xml + + + + + + safely + goHome + 20 + 100 + ... + ... + + + + waypoint + 0.3 + + + + + 110.124939717,25.760780235 + + 0 + 6.117 + 0.3 + -36.73 + + + + + takePhoto + + + + + + +``` + +### 2.3 关键数据提取 + +| 数据类型 | XML路径 | 说明 | +|----------|---------|------| +| 经度 | `Placemark/Point/coordinates` | 格式: `经度,纬度` | +| 纬度 | `Placemark/Point/coordinates` | 格式: `经度,纬度` | +| 航点序号 | `wpml:index` | 从0开始 | +| 相对高度 | `wpml:height` | 相对起飞点高度(m) | +| 执行高度 | `wpml:executeHeight` | waylines.wpml中 | +| 飞行速度 | `wpml:waypointSpeed` | m/s | +| 航向角 | `wpml:waypointHeadingAngle` | 度 | +| 云台俯仰角 | `wpml:gimbalPitchAngle` | 度 | +| 动作类型 | `wpml:actionActuatorFunc` | takePhoto/startRecord等 | + +--- + +## 三、系统架构设计 + +### 3.1 页面入口与用户流程 + +**核心流程说明:** +- 任务管理不是独立页面,而是3D地图界面中的可拖拽浮动组件 +- 从 RightPanel 设备详情点击"任务管理"按钮打开 TaskPanel 组件 +- 根据设备SN查询该设备绑定的航线列表 +- 无人机实时经纬度已通过 SSE (`useDroneSSE` hook) 获取到,复用即可 + +``` +用户操作流程: +┌─────────────┐ ┌─────────────┐ ┌─────────────────────────────────┐ +│ 地图仪表盘 │ ──> │ 点击景区 │ ──> │ RightPanel (设备详情面板) │ +│ (首页) │ │ (3D地图) │ │ ├─ 进入操控台 → LeftControlPanel │ +└─────────────┘ └─────────────┘ │ ├─ 一键起飞 │ + │ └─ 任务管理 → TaskPanel (新增) │ + └─────────────────────────────────┘ + │ + │ 传递参数: device对象 + ▼ + ┌─────────────────────────────────┐ + │ TaskPanel (可拖拽浮动组件) │ + │ 类似 LeftControlPanel 的设计 │ + │ ────────────────────────────── │ + │ 1. 根据deviceSn查询绑定的航线 │ + │ 2. 航线下拉列表供用户选择 │ + │ 3. 选择航线 → 地图显示航迹 │ + │ 4. 开始跟踪 → 显示实时轨迹 │ + │ 5. 复用useDroneSSE获取实时位置 │ + └─────────────────────────────────┘ +``` + +**现有代码位置:** +``` +src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/ +├── LeftControlPanel.tsx # 已有: 无人机操控面板 (已通过SSE获取实时经纬度) +├── RightPanel.tsx # 已有: 设备详情面板 (需新增"任务管理"按钮) +└── TaskPanel.tsx # 新建: 任务管理面板 (可拖拽,复用SSE数据) +``` + +### 3.2 整体架构 + +``` +┌─────────────────────────────────────────────────────────────────────────┐ +│ 前端层 (React + Cesium + SSE) │ +├─────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────────┐ ┌──────────────────────────────────────────┐ │ +│ │ 航线管理页面 │ │ 3D地图界面 (mapDashboard) │ │ +│ │ (新增/编辑时 │ │ ├─ CesiumContainer (Cesium地图容器) │ │ +│ │ 选择绑定设备) │ │ │ ├─ 计划航线(蓝色) │ │ +│ └──────────────────┘ │ │ ├─ 实际轨迹(绿色) │ │ +│ │ │ ├─ 航点标记(序号) │ │ +│ │ │ └─ 无人机位置 │ │ +│ │ │ │ │ +│ │ ├─ RightPanel (设备详情面板) │ │ +│ │ │ └─ "任务管理"按钮 (新增) │ │ +│ │ │ │ │ +│ │ ├─ LeftControlPanel (已有-无人机控制) │ │ +│ │ │ └─ useDroneSSE (已实现实时位置获取) │ │ +│ │ │ │ │ +│ │ └─ TaskPanel (新建-任务管理浮动组件) │ │ +│ │ ├─ 复用 useDroneSSE 获取实时位置 │ │ +│ │ ├─ 航线选择器 │ │ +│ │ └─ 实时轨迹跟踪 │ │ +│ └──────────────────────────────────────────┘ │ +│ │ +└────────────────────────────────┬────────────────────────────────────────┘ + │ HTTP/WebSocket + ▼ +┌─────────────────────────────────────────────────────────────────────────┐ +│ 后端层 (device-center) │ +├─────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌────────────────────┐ ┌────────────────────┐ │ +│ │ WaylineController │ │ DroneTrackController│ │ +│ │ - 航线CRUD │ │ - 轨迹查询 │ │ +│ │ - 解析航线 │ │ - 轨迹统计 │ │ +│ │ - 绑定设备 │ └────────────────────┘ │ +│ └────────────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌────────────────────┐ ┌────────────────────┐ │ +│ │ WaylineParseService│ │ DroneTrackService │ │ +│ │ - 解析KMZ文件 │ │ - 记录飞行位置 │ │ +│ │ - 提取航点数据 │ │ - 查询历史轨迹 │ │ +│ │ - 提取动作数据 │ │ - 轨迹偏离检测 │ │ +│ └────────────────────┘ └────────────────────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────────────────────────────────────────────────────────┐ │ +│ │ WebSocket消息处理 │ │ +│ │ DeviceMessageHandler - 接收无人机OSD数据,提取位置信息 │ │ +│ └─────────────────────────────────────────────────────────────────┘ │ +│ │ +└────────────────────────────────┬────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────┐ +│ 数据层 (MySQL) │ +├─────────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ +│ │ wayline_file │ │wayline_waypoint│ │ wayline_action │ │ +│ │ (航线文件) │──│ (航点) │──│ (动作) │ │ +│ └───────────────┘ └───────────────┘ └───────────────┘ │ +│ │ │ +│ │ ┌───────────────────┐ │ +│ └──────────│ drone_flight_track │ │ +│ │ (飞行轨迹) │ │ +│ └───────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────┘ +``` + +### 3.2 数据流转 + +``` + KMZ文件上传 + │ + ▼ + ┌─────────────────────┐ + │ 文件存储 (MinIO) │ + └─────────────────────┘ + │ + ▼ + ┌─────────────────────┐ + │ 异步解析KMZ文件 │ + │ - 解压ZIP │ + │ - 解析XML │ + │ - 提取航点/动作 │ + └─────────────────────┘ + │ + ┌──────────────┼──────────────┐ + ▼ ▼ ▼ + ┌──────────┐ ┌──────────┐ ┌──────────┐ + │wayline_ │ │wayline_ │ │wayline_ │ + │file │ │waypoint │ │action │ + └──────────┘ └──────────┘ └──────────┘ + │ + │ 绑定设备SN + ▼ + ┌──────────────────────────────────────┐ + │ 前端3D地图展示 │ + │ ├─ 查询航点数据 → 绘制计划航线 │ + │ └─ WebSocket接收 → 绘制实际轨迹 │ + └──────────────────────────────────────┘ +``` + +--- + +## 四、数据库设计 + +### 4.1 设计思路 + +**表职责分离:** +- `wayline_file`(现有):航迹文件元数据表,只存储KMZ文件引用,**不做修改** +- `wayline_route`(新建):航线任务表,关联航迹文件和设备,存储解析后的统计信息 +- `wayline_waypoint`(新建):航点表,存储解析后的航点数据 +- `wayline_action`(新建):航点动作表,存储航点的动作数据 +- `drone_flight_track`(新建):飞行轨迹表,存储实时飞行轨迹 + +**关联关系:** +``` +wayline_file (航迹文件) + │ + │ 1:N (一个航迹文件可被多个航线任务使用) + ▼ +wayline_route (航线任务) ─────> manage_device (设备) + │ + │ 1:N + ▼ +wayline_waypoint (航点) + │ + │ 1:N + ▼ +wayline_action (动作) +``` + +### 4.2 表结构设计 + +#### 4.2.1 航线任务表 (wayline_route) - 新建 + +```sql +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='航线任务表'; +``` + +**字段说明:** +| 字段 | 说明 | +|------|------| +| route_id | 航线任务唯一ID,用于关联航点表 | +| file_wayline_id | 关联 `wayline_file.wayline_id`,如 `10df53e4b9114a87904fb010bc46922b` | +| device_sn | 绑定的无人机设备SN | +| parse_status | 解析状态,解析成功后航点数据才可用 | + +#### 4.2.2 航点表 (wayline_waypoint) - 新建 + +```sql +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='航线航点表'; +``` + +#### 4.2.3 航点动作表 (wayline_action) - 新建 + +```sql +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.2.4 飞行轨迹表 (drone_flight_track) - 新建 + +```sql +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='无人机飞行轨迹表'; +``` + +### 4.3 动作类型枚举 + +| 动作类型 | 英文标识 | 说明 | +|----------|----------|------| +| 拍照 | takePhoto | 单次拍照 | +| 开始录像 | startRecord | 开始录制视频 | +| 停止录像 | stopRecord | 停止录制视频 | +| 悬停 | hover | 悬停等待(hoverTime秒) | +| 变焦 | zoom | 相机变焦(focalLength) | +| 云台旋转 | gimbalRotate | 云台角度调整 | +| 飞机旋转 | rotateYaw | 机头朝向调整 | +| 喊话器 | megaphone | 播放音频 | +| 对焦 | focus | 相机对焦 | +| 云台均匀旋转 | gimbalEvenlyRotate | 航段间云台平滑旋转 | + +### 4.4 ER图 + +``` +┌─────────────────┐ +│ wayline_file │ (现有表,不修改) +│ (航迹文件表) │ +├─────────────────┤ +│ wayline_id (PK) │──┐ +│ name │ │ +│ file_url │ │ +│ ... │ │ +└─────────────────┘ │ + │ 1:N + ▼ +┌─────────────────────────┐ ┌─────────────────┐ +│ wayline_route │ │ manage_device │ +│ (航线任务表) │ │ (设备表) │ +├─────────────────────────┤ ├─────────────────┤ +│ id │ │ sn (PK) │ +│ route_id (PK) │ │ device_name │ +│ route_name │ │ ... │ +│ file_wayline_id (FK) ───┘ └─────────────────┘ +│ device_sn (FK) ─────────────────────────┘ +│ parse_status │ +│ waypoint_count │ +│ total_distance │ +│ ... │ +└─────────────────────────┘ + │ + │ 1:N + ▼ +┌─────────────────────────┐ ┌─────────────────┐ +│ wayline_waypoint │ │ wayline_action │ +│ (航点表) │ │ (动作表) │ +├─────────────────────────┤ ├─────────────────┤ +│ id │ │ id │ +│ route_id (FK) │──┐ │ waypoint_id(FK) │ +│ waypoint_index │ │ │ route_id (FK) │ +│ longitude │ └───>│ action_type │ +│ latitude │ │ action_params │ +│ height │ │ ... │ +│ speed │ └─────────────────┘ +│ ... │ +└─────────────────────────┘ + │ + │ 关联 + ▼ +┌─────────────────────────┐ +│ drone_flight_track │ +│ (飞行轨迹表) │ +├─────────────────────────┤ +│ id │ +│ device_sn │ +│ route_id (FK) │ +│ longitude │ +│ latitude │ +│ record_time │ +│ ... │ +└─────────────────────────┘ +``` + +### 4.5 业务场景示例 + +**场景:创建航线任务并绑定设备** + +```sql +-- 1. 假设已有航迹文件记录 +-- wayline_file.wayline_id = '10df53e4b9114a87904fb010bc46922b' + +-- 2. 创建航线任务,关联航迹文件和设备 +INSERT INTO wayline_route (route_id, route_name, file_wayline_id, device_sn, device_name) +VALUES ( + UUID(), -- 新的航线任务ID + '平安寨巡检航线-无人机A', -- 航线任务名称 + '10df53e4b9114a87904fb010bc46922b', -- 关联航迹文件 + '1ZNBJ1D00C00GH', -- 绑定设备SN + '巡检无人机A' -- 设备名称 +); + +-- 3. 解析航迹文件,存储航点数据到 wayline_waypoint +-- 4. 解析动作数据,存储到 wayline_action +-- 5. 更新 wayline_route 的解析状态和统计信息 +``` + +**场景:同一航迹文件绑定多个设备** + +```sql +-- 航迹文件可被多个航线任务使用 +-- 航线任务1:绑定无人机A +INSERT INTO wayline_route (route_id, route_name, file_wayline_id, device_sn) +VALUES (UUID(), '平安寨巡检-无人机A', '10df53e4b9114a87904fb010bc46922b', '1ZNBJ1D00C00GH'); + +-- 航线任务2:绑定无人机B(使用相同航迹文件) +INSERT INTO wayline_route (route_id, route_name, file_wayline_id, device_sn) +VALUES (UUID(), '平安寨巡检-无人机B', '10df53e4b9114a87904fb010bc46922b', '1ZNBJ2E00D00HI'); +``` + +--- + +## 五、后端接口设计 + +### 5.1 航线任务管理接口 (WaylineRouteController) + +#### 5.1.1 创建航线任务 + +``` +POST /route/create +``` + +**请求体:** +```json +{ + "routeName": "平安寨巡检航线-无人机A", + "fileWaylineId": "10df53e4b9114a87904fb010bc46922b", + "deviceSn": "1ZNBJ1D00C00GH", + "remark": "日常巡检任务" +} +``` + +**响应示例:** +```json +{ + "resp_code": 0, + "resp_msg": "创建成功", + "datas": { + "routeId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "routeName": "平安寨巡检航线-无人机A", + "parseStatus": 0 + } +} +``` + +**说明:** 创建航线任务时,选择已上传的航迹文件(fileWaylineId)和要绑定的设备(deviceSn)。 + +--- + +#### 5.1.2 根据设备SN查询绑定的航线任务列表 + +``` +GET /route/listByDevice/{deviceSn} +``` + +**请求参数:** +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| deviceSn | String | 是 | 设备SN | + +**响应示例:** +```json +{ + "resp_code": 0, + "resp_msg": "success", + "datas": [ + { + "routeId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "routeName": "平安寨巡检航线1", + "fileWaylineId": "10df53e4b9114a87904fb010bc46922b", + "parseStatus": 2, + "waypointCount": 8, + "totalDistance": 52.79, + "totalDuration": 114.7, + "createTime": "2025-12-17 10:00:00" + }, + { + "routeId": "b2c3d4e5-f6a7-8901-bcde-f12345678901", + "routeName": "平安寨巡检航线2", + "fileWaylineId": "20ef64f5c0225b98015fc121cd57033c", + "parseStatus": 2, + "waypointCount": 12, + "totalDistance": 120.5, + "totalDuration": 240.0, + "createTime": "2025-12-16 15:30:00" + } + ] +} +``` + +**说明:** 该接口用于3D任务管理页面,根据当前设备SN查询已绑定的航线任务列表。 + +--- + +#### 5.1.3 解析航线任务 + +``` +POST /route/parse/{routeId} +``` + +**请求参数:** +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| routeId | String | 是 | 航线任务ID | + +**响应示例:** +```json +{ + "resp_code": 0, + "resp_msg": "解析成功", + "datas": { + "routeId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "waypointCount": 8, + "actionCount": 45, + "totalDistance": 52.79, + "totalDuration": 114.7 + } +} +``` + +**说明:** 解析航线任务时,会根据关联的 `fileWaylineId` 下载并解析KMZ文件,提取航点和动作数据存入数据库。 + +--- + +#### 5.1.4 批量解析航线任务 + +``` +POST /route/parse/batch +``` + +**请求体:** +```json +{ + "routeIds": ["a1b2c3d4...", "b2c3d4e5...", "c3d4e5f6..."] +} +``` + +--- + +#### 5.1.5 获取航线任务详情(含航点) + +``` +GET /route/detail/{routeId} +``` + +**响应示例:** +```json +{ + "resp_code": 0, + "datas": { + "routeId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "routeName": "平安寨巡检航线", + "fileWaylineId": "10df53e4b9114a87904fb010bc46922b", + "deviceSn": "1ZNBJ1D00C00GH", + "deviceName": "巡检无人机A", + "parseStatus": 2, + "waypointCount": 8, + "totalDistance": 52.79, + "waypoints": [ + { + "index": 0, + "longitude": 110.124939717, + "latitude": 25.760780235, + "height": 6.117, + "speed": 0.3, + "headingAngle": -108.6, + "actions": [ + {"type": "rotateYaw", "params": {"heading": -108.354}}, + {"type": "takePhoto", "params": {}} + ] + } + ] + } +} +``` + +--- + +#### 5.1.6 获取航线航点列表(轻量-用于地图绑制) + +``` +GET /route/waypoints/{routeId} +``` + +**响应示例:** +```json +{ + "resp_code": 0, + "datas": [ + {"index": 0, "lng": 110.124939717, "lat": 25.760780235, "height": 6.117}, + {"index": 1, "lng": 110.124939768, "lat": 25.760780392, "height": 2.9}, + {"index": 2, "lng": 110.124939651, "lat": 25.760780383, "height": 5.51} + ] +} +``` + +### 5.2 飞行轨迹接口 + +#### 5.2.1 获取飞行轨迹 + +``` +GET /drone/track/{deviceSn} +``` + +**请求参数:** +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| deviceSn | String | 是 | 设备SN | +| jobId | String | 否 | 任务ID | +| startTime | DateTime | 否 | 开始时间 | +| endTime | DateTime | 否 | 结束时间 | + +**响应示例:** +```json +{ + "resp_code": 0, + "datas": { + "deviceSn": "1ZNBJ1D00C00GH", + "trackPoints": [ + {"lng": 110.124939, "lat": 25.760780, "alt": 936.5, "time": "2025-12-17 10:30:00"}, + {"lng": 110.124940, "lat": 25.760785, "alt": 935.2, "time": "2025-12-17 10:30:01"} + ], + "totalPoints": 1200, + "duration": 120 + } +} +``` + +#### 5.2.2 获取实时轨迹(SSE) + +**说明:** 实时轨迹已通过 SSE 实现,无需额外开发后端接口。 + +**前端实现位置:** +- Hook: `src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts` +- 使用示例: `LeftControlPanel.tsx` 中已使用此 hook 获取实时经纬度 + +**数据字段:** +```typescript +// useDroneSSE 返回的 droneData 包含以下位置信息: +{ + longitude: number, // 经度 + latitude: number, // 纬度 + elevation: number, // 海拔高度(m) + height: number, // 相对高度(m) + attitude_head: number, // 航向角(度) + horizontal_speed: number, // 水平速度(m/s) + vertical_speed: number, // 垂直速度(m/s) + // ... 其他字段 +} +``` + +**复用方式:** +```tsx +// TaskPanel.tsx 中复用 +import { useDroneSSE } from '../hooks/useDroneSSE'; + +const { droneData, connectDroneSSE, disconnectDroneSSE } = useDroneSSE(); + +// droneData.longitude, droneData.latitude 即为实时经纬度 +``` + +### 5.3 接口汇总 + +| 接口 | 方法 | 路径 | 说明 | +|------|------|------|------| +| **创建航线任务** | POST | /route/create | **创建航线任务(关联航迹文件和设备)** | +| **设备航线列表** | GET | /route/listByDevice/{deviceSn} | **根据设备SN查询绑定的航线任务(任务管理页面核心接口)** | +| 解析航线任务 | POST | /route/parse/{routeId} | 解析单条航线任务 | +| 批量解析 | POST | /route/parse/batch | 批量解析航线任务 | +| 航线任务详情 | GET | /route/detail/{routeId} | 获取完整航线任务数据(含航点) | +| 航点列表 | GET | /route/waypoints/{routeId} | 获取航点坐标(3D地图绑制航线) | +| 飞行轨迹 | GET | /drone/track/{deviceSn} | 获取历史轨迹 | + + +## 六、后端实现设计 + +### 6.1 核心类设计 + +#### 6.1.1 实体类 + +``` +com.central.device.model +├── WaylineFile.java # 航迹文件(已存在,不修改) +├── WaylineRoute.java # 航线任务实体(新建) +├── WaylineWaypoint.java # 航点实体(新建) +├── WaylineAction.java # 航点动作实体(新建) +└── DroneFlightTrack.java # 飞行轨迹实体(新建) + +com.central.device.model.vo +├── WaylineRouteVO.java # 航线任务VO +├── WaylineRouteDetailVO.java # 航线任务详情VO(含航点) +├── WaypointVO.java # 航点VO +├── WaypointActionVO.java # 动作VO +└── FlightTrackVO.java # 飞行轨迹VO + +com.central.device.model.dto +├── WaylineRouteCreateDTO.java # 创建航线任务DTO +├── WaylineParseDTO.java # 解析结果DTO +└── TrackQueryDTO.java # 轨迹查询DTO +``` + +#### 6.1.2 服务类 + +``` +com.central.device.service +├── IWaylineRouteService.java # 航线任务服务接口 +├── IWaylineParseService.java # 航线解析服务接口 +├── IWaylineWaypointService.java # 航点服务接口 +├── IWaylineActionService.java # 动作服务接口 +└── IDroneFlightTrackService.java # 飞行轨迹服务接口 + +com.central.device.service.impl +├── WaylineRouteServiceImpl.java +├── WaylineParseServiceImpl.java +├── WaylineWaypointServiceImpl.java +├── WaylineActionServiceImpl.java +└── DroneFlightTrackServiceImpl.java +``` + +#### 6.1.3 解析器类 + +``` +com.central.device.parser +├── KmzFileParser.java # KMZ文件解析器 +├── TemplateKmlParser.java # template.kml解析器 +├── WaylinesWpmlParser.java # waylines.wpml解析器 +└── model/ + ├── KmzParseResult.java # 解析结果 + ├── MissionConfig.java # 任务配置 + ├── WaypointData.java # 航点数据 + └── ActionData.java # 动作数据 +``` + +### 6.2 KMZ解析流程 + +```java +/** + * KMZ文件解析流程 + * 根据routeId找到关联的fileWaylineId,下载并解析KMZ文件 + */ +@Service +@Slf4j +public class WaylineParseServiceImpl implements IWaylineParseService { + + @Autowired + private IWaylineRouteService routeService; + + @Autowired + private IWaylineFileService waylineFileService; + + @Async("waylineParseExecutor") + public void parseRouteAsync(String routeId) { + try { + // 1. 获取航线任务信息 + WaylineRoute route = routeService.getByRouteId(routeId); + if (route == null) { + throw new RuntimeException("航线任务不存在: " + routeId); + } + + // 2. 更新状态为解析中 + routeService.updateParseStatus(routeId, ParseStatus.PARSING); + + // 3. 根据fileWaylineId获取航迹文件URL + WaylineFile waylineFile = waylineFileService.getByWaylineId(route.getFileWaylineId()); + byte[] kmzBytes = downloadKmzFile(waylineFile.getFileUrl()); + + // 4. 解压KMZ(ZIP)文件 + Map files = unzipKmz(kmzBytes); + + // 5. 解析template.kml + byte[] templateKml = files.get("wpmz/template.kml"); + KmzParseResult result = parseTemplateKml(templateKml); + + // 6. 解析waylines.wpml补充执行数据 + byte[] waylinesWpml = files.get("wpmz/waylines.wpml"); + enrichWithWpmlData(result, waylinesWpml); + + // 7. 保存航点数据(关联routeId) + saveWaypoints(routeId, result.getWaypoints()); + + // 8. 保存动作数据(关联routeId) + saveActions(routeId, result.getActions()); + + // 9. 更新航线任务统计信息 + routeService.updateRouteStats(routeId, result); + + // 10. 更新状态为已解析 + routeService.updateParseStatus(routeId, ParseStatus.PARSED); + + } catch (Exception e) { + log.error("解析航线任务失败: routeId={}", routeId, e); + routeService.updateParseStatus(routeId, ParseStatus.FAILED, e.getMessage()); + } + } +} +``` + +### 6.3 实时轨迹记录 + +```java +/** + * 在DeviceMessageHandler中增加轨迹记录逻辑 + */ +@Component +public class DeviceMessageHandler { + + @Autowired + private IDroneFlightTrackService trackService; + + /** + * 处理无人机OSD数据 + */ + public void handleDroneOsdMessage(String deviceSn, JSONObject osdData) { + // 1. 更新实时数据缓存(现有逻辑) + updateRealtimeData(deviceSn, osdData); + + // 2. 记录飞行轨迹(新增) + if (isFlying(osdData)) { + DroneFlightTrack track = buildTrackFromOsd(deviceSn, osdData); + trackService.recordTrackPoint(track); + } + + // 3. 推送到前端(现有逻辑) + pushToFrontend(deviceSn, osdData); + } + + private DroneFlightTrack buildTrackFromOsd(String deviceSn, JSONObject osdData) { + DroneFlightTrack track = new DroneFlightTrack(); + track.setDeviceSn(deviceSn); + track.setLongitude(osdData.getDouble("longitude")); + track.setLatitude(osdData.getDouble("latitude")); + track.setAltitude(osdData.getDouble("elevation")); + track.setHeight(osdData.getDouble("height")); + track.setHorizontalSpeed(osdData.getDouble("horizontal_speed")); + track.setHeading(osdData.getDouble("attitude_head")); + track.setRecordTime(new Date()); + // 关联当前任务 + track.setJobId(getCurrentJobId(deviceSn)); + track.setRouteId(getCurrentRouteId(deviceSn)); + return track; + } +} +``` + +--- + +## 七、前端实现设计 + +### 7.1 页面结构 + +任务管理不是一个独立页面,而是3D地图界面中的一个可拖拽浮动组件,类似于现有的 `LeftControlPanel.tsx`(无人机控制面板)。 + +``` +src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/ +├── LeftControlPanel.tsx # 已有: 无人机控制面板(可拖拽) +├── LeftControlPanel.less # 已有: 控制面板样式 +├── RightPanel.tsx # 已有: 设备列表面板 ← 新增"任务管理"按钮 +├── RightPanel.less # 已有: 右侧面板样式 +├── TaskPanel.tsx # 新建: 任务管理面板(可拖拽,类似LeftControlPanel) +├── TaskPanel.less # 新建: 任务管理面板样式 +└── components/ + ├── WaylineSelector.tsx # 新建: 航线选择器(根据deviceSn查询) + ├── TrackLegend.tsx # 新建: 轨迹图例 + ├── WaylineLayer.tsx # 新建: 计划航线图层(Cesium) + └── FlightTrackLayer.tsx # 新建: 飞行轨迹图层(Cesium) +``` + +**设计说明:** +- `TaskPanel.tsx` 是一个可拖拽的浮动组件,参考 `LeftControlPanel.tsx` 的实现方式 +- 从 `RightPanel.tsx` 的设备详情中点击"任务管理"按钮进入 +- 无人机实时经纬度已经在 `LeftControlPanel.tsx` 中通过 SSE (`useDroneSSE` hook) 获取到了 +- 任务管理面板可以复用 `useDroneSSE` 获取的实时位置数据来显示飞行轨迹 + +### 7.2 页面入口与参数传递 + +**入口位置:RightPanel.tsx 设备详情页面** + +在 `RightPanel.tsx` 的操作区新增"任务管理"按钮: + +```tsx +// RightPanel.tsx 操作区修改 +{/* 操作区 */} +
+ + + {/* 新增: 任务管理按钮 */} + +
+``` + +**RightPanel Props 新增:** + +```tsx +interface RightPanelProps { + visible: boolean; + tourism: any; + onClose: () => void; + onControlClick: (device: any, realtimeData: any) => void; + onTaskClick: (device: any, realtimeData: any) => void; // 新增: 任务管理点击回调 +} +``` + +**父组件处理:** + +```tsx +// 在3D地图容器组件中 +const [taskPanelVisible, setTaskPanelVisible] = useState(false); +const [taskDevice, setTaskDevice] = useState(null); + +// 处理任务管理按钮点击 +const handleTaskClick = (device: any, realtimeData: any) => { + setTaskDevice(device); + setTaskPanelVisible(true); +}; + +// 渲染 + + +{/* 任务管理面板 - 可拖拽浮动组件 */} + setTaskPanelVisible(false)} +/> +``` + +### 7.3 实时经纬度数据来源 + +**重要说明:** 无人机实时经纬度数据已经在 `LeftControlPanel.tsx` 中通过 SSE 获取到了,无需重新获取。 + +**数据获取方式(参考 LeftControlPanel.tsx):** + +```tsx +// LeftControlPanel.tsx 中的实现 +import { useDroneSSE } from '../hooks/useDroneSSE'; + +const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE(); + +// 实时位置数据在 droneData 中 +const flightData = useMemo(() => { + const data = droneData || rawDroneData; + return { + // ... 其他数据 + lat: Number(data?.latitude ?? 0).toFixed(6), // 实时纬度 + lng: Number(data?.longitude ?? 0).toFixed(6), // 实时经度 + alt: Number(data?.height ?? data?.elevation ?? 0).toFixed(1), // 实时高度 + }; +}, [droneData, rawDroneData]); +``` + +**TaskPanel 复用 SSE 数据:** + +```tsx +// TaskPanel.tsx 中复用相同的 hook +import { useDroneSSE } from '../hooks/useDroneSSE'; + +const TaskPanel: React.FC = ({ visible, device, onClose }) => { + const deviceSn = device?.deviceSn; + const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE(); + + // 连接 SSE 获取实时数据 + useEffect(() => { + if (visible && deviceSn) { + connectDroneSSE(deviceSn); + return () => { + disconnectDroneSSE(deviceSn); + resetDroneData(); + }; + } + }, [visible, deviceSn]); + + // 实时位置用于绘制飞行轨迹 + const realtimePosition = useMemo(() => ({ + longitude: droneData?.longitude, + latitude: droneData?.latitude, + altitude: droneData?.elevation || droneData?.height, + }), [droneData]); + + // ... 其他逻辑 +}; +``` + +### 7.4 航线管理表单修改(WaylineForm.tsx) + +**新增设备选择字段:** + +```tsx +// 在现有WaylineForm.tsx中新增设备选择 + { + // 调用接口获取无人机设备列表 + const res = await deviceApi.getDroneDeviceList(); + return res.datas?.map((item: any) => ({ + label: `${item.deviceName} (${item.sn})`, + value: item.sn, + })) || []; + }} + rules={[{ required: false, message: '请选择绑定设备' }]} + width="md" + fieldProps={{ + showSearch: true, + allowClear: true, + }} +/> +``` + +### 7.5 核心组件实现 + +#### 7.5.1 航线图层 (WaylineLayer.tsx) + +```tsx +import React, { useEffect, useRef } from 'react'; + +interface WaylineLayerProps { + viewer: any; // Cesium Viewer实例 + Cesium: any; // Cesium库 + waypoints: WaypointVO[]; // 航点数据 + color?: string; // 航线颜色 + showWaypoints?: boolean; // 是否显示航点标记 +} + +const WaylineLayer: React.FC = ({ + viewer, + Cesium, + waypoints, + color = '#1890ff', + showWaypoints = true, +}) => { + const polylineRef = useRef(null); + const waypointEntitiesRef = useRef([]); + + useEffect(() => { + if (!viewer || !Cesium || !waypoints?.length) return; + + // 清除旧的航线 + cleanup(); + + // 构建航点坐标数组 + const positions = waypoints.map(wp => + Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height || 0) + ); + + // 绘制航线(Polyline) + polylineRef.current = viewer.entities.add({ + polyline: { + positions: positions, + width: 3, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.2, + color: Cesium.Color.fromCssColorString(color), + }), + clampToGround: false, + }, + }); + + // 绘制航点标记 + if (showWaypoints) { + waypoints.forEach((wp, index) => { + const entity = viewer.entities.add({ + position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height || 0), + point: { + pixelSize: 12, + color: Cesium.Color.fromCssColorString(color), + outlineColor: Cesium.Color.WHITE, + outlineWidth: 2, + }, + label: { + text: `${index}`, + font: '12px 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, -15), + }, + }); + waypointEntitiesRef.current.push(entity); + }); + } + + return () => cleanup(); + }, [viewer, Cesium, waypoints, color, showWaypoints]); + + const cleanup = () => { + if (polylineRef.current) { + viewer.entities.remove(polylineRef.current); + polylineRef.current = null; + } + waypointEntitiesRef.current.forEach(entity => { + viewer.entities.remove(entity); + }); + waypointEntitiesRef.current = []; + }; + + return null; +}; + +export default WaylineLayer; +``` + +#### 7.5.2 飞行轨迹图层 (FlightTrackLayer.tsx) + +```tsx +import React, { useEffect, useRef, useCallback } from 'react'; + +interface FlightTrackLayerProps { + viewer: any; + Cesium: any; + trackPoints: TrackPointVO[]; // 历史轨迹点 + realtimePoint?: TrackPointVO; // 实时位置点 + color?: string; +} + +const FlightTrackLayer: React.FC = ({ + viewer, + Cesium, + trackPoints, + realtimePoint, + color = '#52c41a', +}) => { + const polylineRef = useRef(null); + const positionsRef = useRef([]); + + // 添加实时轨迹点 + const addTrackPoint = useCallback((point: TrackPointVO) => { + if (!viewer || !Cesium) return; + + const position = Cesium.Cartesian3.fromDegrees( + point.longitude, + point.latitude, + point.altitude || 0 + ); + positionsRef.current.push(position); + + // 更新或创建航线 + if (polylineRef.current) { + polylineRef.current.polyline.positions = positionsRef.current; + } else { + polylineRef.current = viewer.entities.add({ + polyline: { + positions: new Cesium.CallbackProperty(() => positionsRef.current, false), + width: 3, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.3, + color: Cesium.Color.fromCssColorString(color), + }), + }, + }); + } + }, [viewer, Cesium, color]); + + // 初始化历史轨迹 + useEffect(() => { + if (!viewer || !Cesium || !trackPoints?.length) return; + + positionsRef.current = trackPoints.map(tp => + Cesium.Cartesian3.fromDegrees(tp.longitude, tp.latitude, tp.altitude || 0) + ); + + polylineRef.current = viewer.entities.add({ + polyline: { + positions: positionsRef.current, + width: 3, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.3, + color: Cesium.Color.fromCssColorString(color), + }), + }, + }); + + return () => { + if (polylineRef.current) { + viewer.entities.remove(polylineRef.current); + } + }; + }, [viewer, Cesium, trackPoints, color]); + + // 处理实时位置更新 + useEffect(() => { + if (realtimePoint) { + addTrackPoint(realtimePoint); + } + }, [realtimePoint, addTrackPoint]); + + return null; +}; + +export default FlightTrackLayer; +``` + +#### 7.5.3 任务管理面板 (TaskPanel.tsx) + +**核心逻辑说明:** +1. 从 RightPanel 点击"任务管理"按钮进入,传递 device 对象 +2. 面板为可拖拽浮动组件,参考 `LeftControlPanel.tsx` 的实现方式 +3. 根据 deviceSn 查询该设备绑定的航线列表 +4. 复用 `useDroneSSE` hook 获取实时经纬度数据 +5. 用户选择航线后,在3D地图上显示航迹 +6. 支持开始/停止实时轨迹跟踪 + +```tsx +import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react'; +import { Select, Button, message, Space, Tooltip } from 'antd'; +import { + CloseOutlined, + PlayCircleOutlined, + StopOutlined, + ReloadOutlined, + AimOutlined, + EnvironmentOutlined, +} from '@ant-design/icons'; +import { useDroneSSE } from '../hooks/useDroneSSE'; +import { waylineRouteApi, WaylineRouteListItemVO, WaypointVO, TrackPointVO } from '@/services/waylineRoute'; +import styles from './TaskPanel.less'; + +interface TaskPanelProps { + visible: boolean; + onClose: () => void; + device: any; + viewer?: any; // Cesium Viewer 实例 + Cesium?: any; // Cesium 库 +} + +const TaskPanel: React.FC = ({ + visible, + onClose, + device, + viewer, + Cesium, +}) => { + const deviceSn = device?.deviceSn; + + // 复用 SSE hook 获取实时位置数据 + const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE(); + + // 状态 + const [routeList, setRouteList] = useState([]); + const [selectedRoute, setSelectedRoute] = useState(null); + const [waypoints, setWaypoints] = useState([]); + const [trackPoints, setTrackPoints] = useState([]); + const [isTracking, setIsTracking] = useState(false); + const [loading, setLoading] = useState(false); + + // 拖拽状态(参考 LeftControlPanel.tsx) + const [position, setPosition] = useState({ x: 0, y: 0 }); + const draggingRef = useRef(false); + const lastPosRef = useRef({ x: 0, y: 0 }); + const rafRef = useRef(null); + const pendingPosRef = useRef({ x: 0, y: 0 }); + + // 从 SSE 数据中提取实时位置 + const realtimePosition = useMemo(() => { + if (!droneData) return null; + return { + longitude: droneData.longitude, + latitude: droneData.latitude, + altitude: droneData.elevation || droneData.height, + heading: droneData.attitude_head, + timestamp: Date.now(), + }; + }, [droneData]); + + // 连接 SSE 获取实时数据 + useEffect(() => { + if (visible && deviceSn) { + connectDroneSSE(deviceSn); + loadRoutesByDevice(deviceSn); + return () => { + disconnectDroneSSE(deviceSn); + resetDroneData(); + }; + } else { + setPosition({ x: 0, y: 0 }); + } + }, [visible, deviceSn]); + + // 根据设备SN加载绑定的航线任务列表 + const loadRoutesByDevice = useCallback(async (sn: string) => { + try { + setLoading(true); + const res = await waylineRouteApi.getRouteListByDevice(sn); + if (res.resp_code === 0) { + setRouteList(res.datas || []); + } + } catch (e) { + message.error('加载航线任务列表失败'); + } finally { + setLoading(false); + } + }, []); + + // 加载航点数据 + const loadWaypoints = useCallback(async (routeId: string) => { + try { + const res = await waylineRouteApi.getRouteWaypoints(routeId); + if (res.resp_code === 0) { + setWaypoints(res.datas || []); + message.success('航线加载成功'); + // 在 Cesium 地图上显示航线 + if (viewer && Cesium) { + drawWaylineOnMap(res.datas || []); + } + } + } catch (e) { + message.error('加载航点数据失败'); + } + }, [viewer, Cesium]); + + // 在地图上绘制航线 + const drawWaylineOnMap = useCallback((waypoints: WaypointVO[]) => { + if (!viewer || !Cesium || !waypoints.length) return; + // 绘制逻辑参考 WaylineLayer.tsx + // ... + }, [viewer, Cesium]); + + // 开始实时跟踪(使用 SSE 数据) + const startTracking = useCallback(() => { + if (!deviceSn) return; + setIsTracking(true); + setTrackPoints([]); + message.success('开始实时跟踪'); + }, [deviceSn]); + + // 停止跟踪 + const stopTracking = useCallback(() => { + setIsTracking(false); + message.info('已停止跟踪'); + }, []); + + // 当实时位置更新时,添加到轨迹点 + useEffect(() => { + if (isTracking && realtimePosition) { + setTrackPoints(prev => [...prev, realtimePosition as TrackPointVO]); + } + }, [isTracking, realtimePosition]); + + // 航线任务变更时加载航点 + useEffect(() => { + if (selectedRoute) { + loadWaypoints(selectedRoute); + } else { + setWaypoints([]); + } + }, [selectedRoute, loadWaypoints]); + + // 拖拽处理(参考 LeftControlPanel.tsx) + 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]); + + return ( +
+ {/* 标题栏 - 可拖拽 */} +
+
+ + 任务管理 + {deviceSn} +
+ +
+ + {/* 内容区 */} +
+ {/* 航线选择 */} +
+
+ 航线选择 +
+ + SELECT * FROM drone_flight_track + WHERE 1=1 + + AND device_sn = #{deviceSn} + + + AND job_id = #{jobId} + + + AND route_id = #{routeId} + + + AND record_time >= #{startTime} + + + AND record_time <= #{endTime} + + ORDER BY record_time ASC + + LIMIT #{limit} + + + + + + + + + DELETE FROM drone_flight_track + WHERE device_sn = #{deviceSn} + AND record_time < #{beforeTime} + + + + + + + + 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 + + ( + #{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() + ) + + + + + + DELETE FROM drone_flight_track + WHERE route_id = #{routeId} + + + \ No newline at end of file diff --git a/zlt-business/device-center/src/main/resources/mapper/WaylineActionMapper.xml b/zlt-business/device-center/src/main/resources/mapper/WaylineActionMapper.xml new file mode 100644 index 00000000..728ec9cf --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/WaylineActionMapper.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + DELETE FROM wayline_action + WHERE route_id = #{routeId} + + + + + INSERT INTO wayline_action ( + waypoint_id, route_id, action_group_id, action_index, + action_type, action_params, trigger_type, tenant_id, create_time + ) VALUES + + ( + #{item.waypointId}, #{item.routeId}, #{item.actionGroupId}, #{item.actionIndex}, + #{item.actionType}, #{item.actionParams}, #{item.triggerType}, #{item.tenantId}, NOW() + ) + + + + + + + \ No newline at end of file diff --git a/zlt-business/device-center/src/main/resources/mapper/WaylineRouteMapper.xml b/zlt-business/device-center/src/main/resources/mapper/WaylineRouteMapper.xml new file mode 100644 index 00000000..5d5b689c --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/WaylineRouteMapper.xml @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UPDATE wayline_route + SET parse_status = #{parseStatus}, + update_time = NOW() + WHERE route_id = #{routeId} + + + + + UPDATE wayline_route + SET parse_status = #{parseStatus}, + parse_error = #{parseError}, + update_time = NOW() + WHERE route_id = #{routeId} + + + + + 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} + + + + + + + + DELETE FROM wayline_route + WHERE device_sn = #{deviceSn} + AND file_wayline_id = #{waylineId} + + + \ No newline at end of file diff --git a/zlt-business/device-center/src/main/resources/mapper/WaylineWaypointMapper.xml b/zlt-business/device-center/src/main/resources/mapper/WaylineWaypointMapper.xml new file mode 100644 index 00000000..eda6df1e --- /dev/null +++ b/zlt-business/device-center/src/main/resources/mapper/WaylineWaypointMapper.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + DELETE FROM wayline_waypoint + WHERE route_id = #{routeId} + + + + + 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 + + ( + #{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() + ) + + + + + + + \ No newline at end of file diff --git a/zlt-business/device-center/src/main/resources/sql/wayline_tables.sql b/zlt-business/device-center/src/main/resources/sql/wayline_tables.sql new file mode 100644 index 00000000..91714748 --- /dev/null +++ b/zlt-business/device-center/src/main/resources/sql/wayline_tables.sql @@ -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', '{}'); \ No newline at end of file diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java index e4ca8a80..f89b7870 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java @@ -89,7 +89,7 @@ public class TourismController { @GetMapping("/{tourismId}/devices") public Result getTourismDevices(@PathVariable("tourismId") Long tourismId) { try { - var devices = tourismService.getDevicesByTourismId(tourismId); + List> devices = tourismService.getDevicesByTourismId(tourismId); return Result.succeed(devices, "获取景区设备列表成功"); } catch (Exception e) { log.error("获取景区设备列表失败", e); diff --git a/zlt-web/react-web-next/config/proxy.ts b/zlt-web/react-web-next/config/proxy.ts index 97cc1df4..d886c6ea 100644 --- a/zlt-web/react-web-next/config/proxy.ts +++ b/zlt-web/react-web-next/config/proxy.ts @@ -4,8 +4,6 @@ * - 生产环境由网关/容器转发,此文件不生效 */ 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流媒体服务器地址 const SRS_SERVER = process.env.SRS_SERVER || 'http://220.205.16.27:8024'; diff --git a/zlt-web/react-web-next/dist.zip b/zlt-web/react-web-next/dist.zip index 8a053484..f8b0f8f8 100644 Binary files a/zlt-web/react-web-next/dist.zip and b/zlt-web/react-web-next/dist.zip differ diff --git a/zlt-web/react-web-next/src/pages/device/Wayline/components/BindDeviceModal.tsx b/zlt-web/react-web-next/src/pages/device/Wayline/components/BindDeviceModal.tsx new file mode 100644 index 00000000..d9a1d2fb --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/Wayline/components/BindDeviceModal.tsx @@ -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 = ({ + visible, + onVisibleChange, + wayline, + onSuccess +}) => { + const [form] = Form.useForm(); + const [deviceList, setDeviceList] = useState([]); + 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 ( + +
+ + {wayline?.name} + + + + {wayline?.waylineId} + + + + + + + {deviceList.length === 0 && !loading && ( +
+ 暂无可用设备 +
+ )} +
+
+ ); +}; + +export default BindDeviceModal; \ No newline at end of file diff --git a/zlt-web/react-web-next/src/pages/device/Wayline/components/WaylineDetailModal.tsx b/zlt-web/react-web-next/src/pages/device/Wayline/components/WaylineDetailModal.tsx new file mode 100644 index 00000000..6142f8ab --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/Wayline/components/WaylineDetailModal.tsx @@ -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 = ({ + visible, + onVisibleChange, + wayline +}) => { + const [loading, setLoading] = useState(false); + const [routeDetail, setRouteDetail] = useState(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) => ( + + {value ? '是' : '否'} + + ), + }, + ]; + + // 动作表格列定义 + 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 = { + 'fly': 'blue', + 'rotate': 'green', + 'gimbal': 'orange', + 'camera': 'purple', + 'hover': 'cyan', + }; + return {text}; + }, + }, + { + title: '触发类型', + dataIndex: 'triggerType', + width: 100, + render: (text: string) => { + const colors: Record = { + 'trigger': 'red', + 'time': 'green', + 'distance': 'blue', + }; + return {text}; + }, + }, + { + title: '延迟时间(ms)', + dataIndex: 'delayTime', + width: 100, + align: 'center', + }, + { + title: '悬停时间(s)', + dataIndex: 'hoverTime', + width: 100, + align: 'center', + }, + { + title: '航向角(°)', + dataIndex: 'aircraftHeading', + width: 80, + align: 'center', + }, + ]; + + return ( + onVisibleChange(false)} + footer={null} + width={1000} + style={{ top: 20 }} + > + + {routeDetail ? ( +
+ {/* 基本信息 */} + + + + {routeDetail.routeInfo?.routeName} + + + + {routeDetail.totalWaypoints}个 + + + + {routeDetail.totalActions}个 + + + + {routeDetail.totalDistance?.toFixed(2)}米 + + + + {routeDetail.totalDuration?.toFixed(2)}秒 + + + + {routeDetail.routeInfo?.parseStatusDesc} + + + + + + {/* 航点和动作详情 */} + + + + 航点列表 ({routeDetail.waypoints?.length || 0}) + + } + key="waypoints" + > + + + + + + 动作列表 ({routeDetail.actions?.length || 0}) + + } + key="actions" + > +
`${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
无参数
; + } + return ( +
+ {Object.entries(record.actionParams).map(([key, value]) => ( + + {key}: + {String(value)} + + ))} +
+ ); + }, + rowExpandable: (record) => record.actionParams && Object.keys(record.actionParams).length > 0, + }} + /> + + + + ) : ( +
+ 暂无数据或该航迹文件尚未绑定设备 +
+ )} + + + ); +}; + +export default WaylineDetailModal; \ No newline at end of file diff --git a/zlt-web/react-web-next/src/pages/device/Wayline/components/WaylineTable.tsx b/zlt-web/react-web-next/src/pages/device/Wayline/components/WaylineTable.tsx index 8f9ae2a9..fd71c4bf 100644 --- a/zlt-web/react-web-next/src/pages/device/Wayline/components/WaylineTable.tsx +++ b/zlt-web/react-web-next/src/pages/device/Wayline/components/WaylineTable.tsx @@ -3,7 +3,7 @@ import type { ActionType } from '@ant-design/pro-components'; import { ProTable } from '@ant-design/pro-components'; import type { ProColumns } from '@ant-design/pro-components'; 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 { downloadByUrl } from '@/utils/download'; @@ -15,9 +15,11 @@ interface WaylineTableProps { params?: Record; onEdit?: (record: any) => void; onDelete?: (record: any) => void; + onBindDevice?: (record: any) => void; + onViewDetail?: (record: any) => void; } -const WaylineTable = forwardRef(({ params, onEdit, onDelete }, ref) => { +const WaylineTable = forwardRef(({ params, onEdit, onDelete, onBindDevice, onViewDetail }, ref) => { const actionRef = useRef(); useImperativeHandle(ref, () => ({ reload: () => actionRef.current?.reload() })); @@ -80,6 +82,12 @@ const WaylineTable = forwardRef(({ params, o handleDownload(record)} title="下载航线文件"> 下载 + onBindDevice?.(record)} title="绑定设备"> + 绑定设备 + + onViewDetail?.(record)} title="查看详情"> + 详情 + onDelete?.(record)}>删除 ) diff --git a/zlt-web/react-web-next/src/pages/device/Wayline/index.tsx b/zlt-web/react-web-next/src/pages/device/Wayline/index.tsx index bf71d67b..7e5aeb0c 100644 --- a/zlt-web/react-web-next/src/pages/device/Wayline/index.tsx +++ b/zlt-web/react-web-next/src/pages/device/Wayline/index.tsx @@ -5,6 +5,8 @@ import { PlusOutlined } from '@ant-design/icons'; import { deviceApi } from '@/services/device'; import WaylineTable, { WaylineTableRef } from './components/WaylineTable'; import WaylineForm, { WaylineFormValues } from './components/WaylineForm'; +import BindDeviceModal from './components/BindDeviceModal'; +import WaylineDetailModal from './components/WaylineDetailModal'; import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui'; const WaylinePage: React.FC = () => { @@ -13,6 +15,10 @@ const WaylinePage: React.FC = () => { const [createOpen, setCreateOpen] = useState(false); const [editOpen, setEditOpen] = useState(false); const [current, setCurrent] = useState(null); + const [bindDeviceOpen, setBindDeviceOpen] = useState(false); + const [selectedWayline, setSelectedWayline] = useState(null); + const [detailOpen, setDetailOpen] = useState(false); + const [detailWayline, setDetailWayline] = useState(null); const add = async (values: WaylineFormValues) => { 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 ( { params={query} onEdit={(r) => { setCurrent(r); setEditOpen(true); }} onDelete={(r) => del(r)} + onBindDevice={handleBindDevice} + onViewDetail={handleViewDetail} /> + + { + tableRef.current?.reload(); + }} + /> + + ); }; diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx index b66cece8..6aba03b6 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx @@ -525,6 +525,23 @@ const LeftControlPanel: React.FC = ({ } }, [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 = () => { if (videoSize === 'normal') { @@ -665,7 +682,7 @@ const LeftControlPanel: React.FC = ({ {flightData.vol}V - diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.less b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.less index 313b2484..07cd1a03 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.less +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.less @@ -12,7 +12,7 @@ top: 64px; right: 0; bottom: 0; - width: 420px; // 稍微加宽一点 + width: 360px; // 减小宽度避免滚动条 background: linear-gradient( 135deg, rgba(6, 12, 20, 0.98) 0%, @@ -225,6 +225,50 @@ border-left: 2px solid @cyan; text-transform: uppercase; 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 { @@ -256,30 +300,41 @@ } .actions { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 12px; - margin-top: 32px; + display: flex; + flex-direction: column; + gap: 10px; + margin-top: 24px; + + .actionRow { + display: flex; + gap: 10px; + + button { + flex: 1; + } + } button { - padding: 12px; + padding: 10px 12px; background: rgba(0, 240, 255, 0.1); border: 1px solid rgba(0, 240, 255, 0.3); color: @cyan; font-weight: 600; + font-size: 13px; cursor: pointer; transition: all 0.3s; display: flex; align-items: center; justify-content: center; - gap: 8px; - + gap: 6px; + white-space: nowrap; + &:hover:not(:disabled) { background: 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); } &.primary { @@ -289,6 +344,16 @@ text-shadow: none; &: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); + } + } } } } diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx index f3be9208..7a169a47 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx @@ -10,6 +10,8 @@ import { DashboardOutlined, SignalFilled, LoadingOutlined, + AimOutlined, + UnorderedListOutlined, } from '@ant-design/icons'; import { deviceApi } from '@/services/device'; import { ordersApi } from '@/services/orders'; @@ -23,13 +25,19 @@ interface RightPanelProps { tourism: any; onClose: () => void; onControlClick: (device: any, realtimeData: any) => void; + onTaskPanelOpen?: (device: any) => void; // 打开任务管理面板回调 + viewer?: any; // Cesium Viewer 实例 + Cesium?: any; // Cesium 库 } const RightPanel: React.FC = ({ visible, tourism, onClose, - onControlClick + onControlClick, + onTaskPanelOpen, + viewer, + Cesium }) => { const [deviceList, setDeviceList] = useState([]); const [selectedDeviceSn, setSelectedDeviceSn] = useState(''); @@ -81,6 +89,16 @@ const RightPanel: React.FC = ({ if (deviceSn !== selectedDeviceSn) setSelectedDeviceSn(deviceSn); }; + // 关闭面板时,主动断开SSE连接 + const handleClose = () => { + // 先断开SSE连接 + if (selectedDeviceSn) { + disconnectSSE(selectedDeviceSn); + } + // 然后调用父组件的关闭回调 + onClose(); + }; + const selectedDevice = deviceList.find((d) => d.deviceSn === selectedDeviceSn); const dockData = realtimeData?.rawData?.dockData; const battery = realtimeData?.battery ?? 0; @@ -192,7 +210,7 @@ const RightPanel: React.FC = ({
{deviceList.length} DEVICES ONLINE
- + @@ -235,8 +253,17 @@ const RightPanel: React.FC = ({ {/* Block A: 机库信息 */}
-
机库信息 / DOCK INFO
- +
+ 机库信息 / DOCK INFO + +
+ {/* 状态卡片 */}
@@ -273,15 +300,14 @@ const RightPanel: React.FC = ({ {/* 操作区 */}
- - +
+ + +
@@ -337,6 +363,7 @@ const RightPanel: React.FC = ({ )}
+
); }; diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.less b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.less new file mode 100644 index 00000000..d288a266 --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.less @@ -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; + } + } + } + } +} diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.tsx new file mode 100644 index 00000000..620fb8bc --- /dev/null +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.tsx @@ -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 = ({ + visible, + onClose, + device, + viewer, + Cesium, +}) => { + const deviceSn = device?.deviceSn; + + // SSE hook + const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE(); + + // 航线相关状态 + const [routeList, setRouteList] = useState([]); + const [selectedRouteId, setSelectedRouteId] = useState(null); + const [waypoints, setWaypoints] = useState([]); + const [routeLoading, setRouteLoading] = useState(false); + + // 任务相关状态 + const [taskList, setTaskList] = useState([]); + const [selectedTaskId, setSelectedTaskId] = useState(null); + const [taskLoading, setTaskLoading] = useState(false); + const [imagePreviewVisible, setImagePreviewVisible] = useState(false); + const [previewImages, setPreviewImages] = useState([]); + + // Tab 状态 + const [activeTab, setActiveTab] = useState('route'); + + // 拖拽状态 + const [position, setPosition] = useState({ x: 0, y: 0 }); + const draggingRef = useRef(false); + const lastPosRef = useRef({ x: 0, y: 0 }); + const rafRef = useRef(null); + const pendingPosRef = useRef({ x: 0, y: 0 }); + + // 地图图层引用 + const waylineEntityRef = useRef(null); + const waypointEntitiesRef = useRef([]); + const droneEntityRef = useRef(null); + const flightTrackEntityRef = useRef(null); + const trackPositionsRef = useRef([]); + const hasFlownToDroneRef = useRef(false); // 是否已经飞到过无人机位置 + const lastUpdateTimeRef = useRef(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 ( +
+ {/* 标题栏 */} +
+
+ + 任务管理 + {deviceSn && {deviceSn}} +
+
+ + + + +
+
+ + {/* 内容区 */} +
+ + {/* 航线 Tab */} + 航线} key="route"> +
+ {/* 航线选择 */} +
+
选择航线
+ +
+ + {/* 航线详情 */} + {selectedRoute && ( +
+
航线详情
+
+
+ 航点数 + {selectedRoute.waypointCount} +
+
+ 总距离 + {(selectedRoute.totalDistance / 1000).toFixed(2)} km +
+
+ 预计时长 + {Math.ceil(selectedRoute.totalDuration / 60)} 分钟 +
+
+
+ )} + + {/* 创建任务按钮 */} +
+ +
+ + {/* 图例 */} +
+
图例
+
+
+ + 计划航线 +
+
+ + 飞行轨迹 +
+
+ + 无人机 +
+
+
+
+
+ + {/* 任务 Tab */} + 任务} key="task"> +
+ {/* 任务列表 */} +
+
任务列表
+
+ {taskLoading ? ( +
加载中...
+ ) : taskList.length === 0 ? ( + + ) : ( + taskList.map(task => ( +
setSelectedTaskId(task.taskId)} + > +
+
{task.taskName}
+
+ + {task.statusDesc} + + {task.createTime} +
+
+
+ + + +
+
+ )) + )} +
+
+
+
+
+ + {/* 实时位置 */} + {realtimePosition && realtimePosition.longitude && ( +
+
+ 无人机实时位置 + + + +
+
+ 经度: {realtimePosition.longitude?.toFixed(6)} + 纬度: {realtimePosition.latitude?.toFixed(6)} +
+
+ 相对高度: {realtimePosition.height != null ? `${realtimePosition.height.toFixed(1)}m` : '--'} + 海拔高度: {realtimePosition.elevation != null ? `${realtimePosition.elevation.toFixed(1)}m` : '--'} +
+
+ )} +
+ + {/* 图片预览 */} + setImagePreviewVisible(vis), + }} + > + {previewImages.map((src, index) => ( + + ))} + +
+ ); +}; + +export default TaskPanel; diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts index 866e840c..76729d79 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts @@ -108,22 +108,41 @@ export function useDeviceSSE(): UseDeviceSSEResult { const maxReconnectAttempts = 10; const shouldReconnectRef = useRef(true); - // 核心断开逻辑,提取为纯函数以便在不同生命周期调用 + // 核心断开逻辑 - 使用 fetch DELETE 请求(正常关闭时调用) const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => { if (!deviceSn || !token) return; - // 尝试使用 fetch keepalive - fetch(`/api-device/sse/device-status/${deviceSn}`, { + const deleteUrl = `/api-device/sse/device-status/${deviceSn}`; + + // 使用 fetch DELETE 请求(带 Authorization header) + fetch(deleteUrl, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}`, 'X-Client-Session-Id': sessionId, }, 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 不适用,故仅作备注) - // navigator.sendBeacon(...) 仅支持 POST + // beforeunload 专用断开逻辑(浏览器刷新/关闭时用 sendBeacon) + 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连接 @@ -323,12 +342,12 @@ export function useDeviceSSE(): UseDeviceSSEResult { doConnect(deviceSn); }, [disconnectSSE, doConnect]); - // 监听浏览器刷新/关闭事件 (beforeunload) + // 监听浏览器刷新/关闭事件 (beforeunload) - 使用 sendBeacon useEffect(() => { const handleBeforeUnload = () => { if (currentDeviceSnRef.current) { - const token = sessionStorage.getItem('access_token'); - performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token); + // 浏览器刷新/关闭时用 sendBeacon(不需要 token,后端需要配置允许匿名访问) + performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current); } }; diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts index f406890b..3371f46b 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts @@ -108,19 +108,41 @@ export const useDroneSSE = (): UseDroneSSEReturn => { const maxReconnectAttempts = 10; const shouldReconnectRef = useRef(true); // 是否应该自动重连 - // 核心断开逻辑,提取为纯函数以便在不同生命周期调用 + // 核心断开逻辑 - 使用 fetch DELETE 请求(正常关闭时调用) const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => { if (!deviceSn || !token) return; - // 尝试使用 fetch keepalive - fetch(`/api-device/sse/drone-telemetry/${deviceSn}`, { + const deleteUrl = `/api-device/sse/drone-telemetry/${deviceSn}`; + + // 使用 fetch DELETE 请求(带 Authorization header) + fetch(deleteUrl, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}`, 'X-Client-Session-Id': sessionId, }, 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连接 @@ -350,7 +372,23 @@ export const useDroneSSE = (): UseDroneSSEReturn => { 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(() => { return () => { // 清理重连定时器 @@ -359,11 +397,17 @@ export const useDroneSSE = (): UseDroneSSEReturn => { reconnectTimerRef.current = null; } shouldReconnectRef.current = false; + + // 在组件卸载时,也尝试发送断开请求 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 { // 状态 diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx index 4eb8668f..6f2c5aef 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx @@ -3,6 +3,7 @@ import { message, Button, Tooltip } from 'antd'; import { AppstoreOutlined } from '@ant-design/icons'; import RightPanel from './3d/BottomPanel/RightPanel'; import LeftControlPanel from './3d/BottomPanel/LeftControlPanel'; +import TaskPanel from './3d/BottomPanel/TaskPanel'; import TilesetPanel from './3d/TilesetPanel'; import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader'; import { getModelsByTourismId, convertToTilesetConfig } from '@/services/threeDModel'; @@ -32,6 +33,10 @@ const CesiumContainer: React.FC = (props) => { const [controlDevice, setControlDevice] = useState(null); const [controlRealtimeData, setControlRealtimeData] = useState(null); + // 任务管理面板状态 + const [taskPanelVisible, setTaskPanelVisible] = useState(false); + const [taskPanelDevice, setTaskPanelDevice] = useState(null); + // 3D Tiles 模型管理 const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false); const [currentTourismModels, setCurrentTourismModels] = useState([]); // 当前景区的所有模型配置 @@ -50,6 +55,8 @@ const CesiumContainer: React.FC = (props) => { // 相机飞到景区 const flyToTourism = useCallback((tourism: any) => { if (!viewerRef.current || !Cesium) return; + // 检查 viewer 是否已销毁 + if (viewerRef.current.isDestroyed?.()) return; const lon = parseFloat(tourism.longitude); const lat = parseFloat(tourism.latitude); @@ -70,6 +77,8 @@ const CesiumContainer: React.FC = (props) => { // 相机飞回全球视角 const flyToGlobal = useCallback(() => { if (!viewerRef.current || !Cesium) return; + // 检查 viewer 是否已销毁 + if (viewerRef.current.isDestroyed?.()) return; viewerRef.current.camera.flyTo({ destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000), @@ -279,6 +288,8 @@ const CesiumContainer: React.FC = (props) => { // 如果有模型会自动飞到模型位置,没有模型才飞到景区位置 if (tourism.id) { loadTourismModels(tourism.id).then((hasModel) => { + // 异步回调时检查 viewer 是否还存在 + if (!viewerRef.current || viewerRef.current.isDestroyed?.()) return; if (!hasModel) { flyToTourism(tourism); } @@ -302,6 +313,12 @@ const CesiumContainer: React.FC = (props) => { setLeftPanelVisible(true); }, []); + // 处理从右侧面板点击"任务管理" + const handleOpenTaskPanel = useCallback((device: any) => { + setTaskPanelDevice(device); + setTaskPanelVisible(true); + }, []); + // 获取设备的视频流地址(从设备数据中获取) const getVideoStreamUrl = useCallback((device: any): string | undefined => { // 从设备配置获取视频流地址 @@ -672,6 +689,18 @@ const CesiumContainer: React.FC = (props) => { tourism={selectedTourism} onClose={handleRightPanelClose} onControlClick={handleOpenControl} + onTaskPanelOpen={handleOpenTaskPanel} + viewer={viewerRef.current} + Cesium={Cesium} + /> + + {/* 任务管理面板 - 左下角独立渲染 */} + setTaskPanelVisible(false)} + device={taskPanelDevice} + viewer={viewerRef.current} + Cesium={Cesium} /> ); diff --git a/zlt-web/react-web-next/src/services/srs.ts b/zlt-web/react-web-next/src/services/srs.ts index 279e88bb..202979fd 100644 --- a/zlt-web/react-web-next/src/services/srs.ts +++ b/zlt-web/react-web-next/src/services/srs.ts @@ -5,12 +5,32 @@ // SRS 服务器配置 const SRS_CONFIG = { - // 开发环境通过代理访问,生产环境直接访问 - baseUrl: process.env.NODE_ENV === 'development' ? '' : 'http://220.205.16.27:8024', + // 所有环境都通过代理访问,避免跨域问题 + // 开发环境: webpack devServer 代理 + // 测试/生产环境: nginx 代理 + baseUrl: '', // 登录密码 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 let srsToken: string | null = null; let tokenExpireTime: number = 0; @@ -113,8 +133,8 @@ export const srsApi = { const url = srsApi.buildWhepUrl(streamId, options?.app); - // 创建 RTCPeerConnection - const pc = new RTCPeerConnection(); + // 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透) + const pc = new RTCPeerConnection(ICE_SERVERS); const stream = new MediaStream(); // 设置接收音视频轨道 @@ -183,16 +203,14 @@ export const srsApi = { try { // 解析 URL,提取路径部分通过代理访问(避免跨域) const urlObj = new URL(whepUrl); - // 开发环境使用代理路径,生产环境使用完整 URL - const actualUrl = process.env.NODE_ENV === 'development' - ? `${urlObj.pathname}${urlObj.search}` // 只使用路径和查询参数,通过代理访问 - : whepUrl; + // 所有环境都使用代理路径,避免跨域问题 + const actualUrl = `${urlObj.pathname}${urlObj.search}`; // 确保已登录 const token = await srsApi.getToken(); - // 创建 RTCPeerConnection - const pc = new RTCPeerConnection(); + // 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透) + const pc = new RTCPeerConnection(ICE_SERVERS); const stream = new MediaStream(); // 设置接收音视频轨道 diff --git a/zlt-web/react-web-next/src/services/waylineRoute.ts b/zlt-web/react-web-next/src/services/waylineRoute.ts new file mode 100644 index 00000000..06a07c1b --- /dev/null +++ b/zlt-web/react-web-next/src/services/waylineRoute.ts @@ -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; + 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 }), +};