Files
gofly-platform-services/zlt-business/device-center/doc/无人机航线管理与轨迹显示实现文档.md
T

1965 lines
71 KiB
Markdown
Raw Normal View History

# 无人机航线管理与轨迹显示实现文档
## 文档信息
| 项目 | 内容 |
|------|------------|
| 版本 | 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
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2"
xmlns:wpml="http://www.dji.com/wpmz/1.0.6">
<Document>
<!-- 任务配置 -->
<wpml:missionConfig>
<wpml:flyToWaylineMode>safely</wpml:flyToWaylineMode>
<wpml:finishAction>goHome</wpml:finishAction>
<wpml:takeOffSecurityHeight>20</wpml:takeOffSecurityHeight>
<wpml:globalRTHHeight>100</wpml:globalRTHHeight>
<wpml:droneInfo>...</wpml:droneInfo>
<wpml:payloadInfo>...</wpml:payloadInfo>
</wpml:missionConfig>
<Folder>
<wpml:templateType>waypoint</wpml:templateType>
<wpml:autoFlightSpeed>0.3</wpml:autoFlightSpeed>
<!-- 航点列表 -->
<Placemark>
<Point>
<coordinates>110.124939717,25.760780235</coordinates>
</Point>
<wpml:index>0</wpml:index>
<wpml:height>6.117</wpml:height>
<wpml:waypointSpeed>0.3</wpml:waypointSpeed>
<wpml:gimbalPitchAngle>-36.73</wpml:gimbalPitchAngle>
<!-- 动作组 -->
<wpml:actionGroup>
<wpml:action>
<wpml:actionActuatorFunc>takePhoto</wpml:actionActuatorFunc>
</wpml:action>
</wpml:actionGroup>
</Placemark>
</Folder>
</Document>
</kml>
```
### 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<String, byte[]> 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 操作区修改
{/* 操作区 */}
<div className={styles.actions}>
<button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}>
<VideoCameraOutlined /> 进入操控台
</button>
<button
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0}
onClick={handleTakeoff}
>
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞
</button>
{/* 新增: 任务管理按钮 */}
<button onClick={() => onTaskClick(selectedDevice, realtimeData)}>
<AimOutlined /> 任务管理
</button>
</div>
```
**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<any>(null);
// 处理任务管理按钮点击
const handleTaskClick = (device: any, realtimeData: any) => {
setTaskDevice(device);
setTaskPanelVisible(true);
};
// 渲染
<RightPanel
// ... 其他props
onTaskClick={handleTaskClick}
/>
{/* 任务管理面板 - 可拖拽浮动组件 */}
<TaskPanel
visible={taskPanelVisible}
device={taskDevice}
onClose={() => 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<TaskPanelProps> = ({ 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中新增设备选择
<ProFormSelect
name="deviceSn"
label="绑定设备"
placeholder="请选择要绑定的无人机设备"
request={async () => {
// 调用接口获取无人机设备列表
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<WaylineLayerProps> = ({
viewer,
Cesium,
waypoints,
color = '#1890ff',
showWaypoints = true,
}) => {
const polylineRef = useRef<any>(null);
const waypointEntitiesRef = useRef<any[]>([]);
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<FlightTrackLayerProps> = ({
viewer,
Cesium,
trackPoints,
realtimePoint,
color = '#52c41a',
}) => {
const polylineRef = useRef<any>(null);
const positionsRef = useRef<any[]>([]);
// 添加实时轨迹点
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<TaskPanelProps> = ({
visible,
onClose,
device,
viewer,
Cesium,
}) => {
const deviceSn = device?.deviceSn;
// 复用 SSE hook 获取实时位置数据
const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE();
// 状态
const [routeList, setRouteList] = useState<WaylineRouteListItemVO[]>([]);
const [selectedRoute, setSelectedRoute] = useState<string | null>(null);
const [waypoints, setWaypoints] = useState<WaypointVO[]>([]);
const [trackPoints, setTrackPoints] = useState<TrackPointVO[]>([]);
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<number | null>(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 (
<div
className={`${styles.taskPanel} ${visible ? styles.visible : ''}`}
style={{ transform: visible ? `translate(${position.x}px, ${position.y}px)` : undefined }}
>
{/* 标题栏 - 可拖拽 */}
<div className={styles.header} onMouseDown={handleMouseDown}>
<div className={styles.title}>
<AimOutlined />
<span>任务管理</span>
<span className={styles.deviceSn}>{deviceSn}</span>
</div>
<button className={styles.closeBtn} onClick={onClose}>
<CloseOutlined />
</button>
</div>
{/* 内容区 */}
<div className={styles.content}>
{/* 航线选择 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>
<EnvironmentOutlined /> 航线选择
</div>
<Select
placeholder="请选择航线任务"
style={{ width: '100%' }}
value={selectedRoute}
onChange={(value) => setSelectedRoute(value)}
loading={loading}
allowClear
options={routeList.map(item => ({
label: `${item.routeName} (${item.waypointCount}个航点)`,
value: item.routeId,
}))}
/>
{routeList.length === 0 && !loading && (
<div className={styles.emptyTip}>
该设备暂无绑定航线任务
</div>
)}
</div>
{/* 轨迹控制 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>轨迹控制</div>
<Space direction="vertical" style={{ width: '100%' }}>
{!isTracking ? (
<Button
type="primary"
icon={<PlayCircleOutlined />}
block
onClick={startTracking}
>
开始跟踪
</Button>
) : (
<Button
danger
icon={<StopOutlined />}
block
onClick={stopTracking}
>
停止跟踪
</Button>
)}
</Space>
</div>
{/* 实时位置显示 */}
{realtimePosition && (
<div className={styles.section}>
<div className={styles.sectionTitle}>实时位置</div>
<div className={styles.coordsDisplay}>
<span>经度: {realtimePosition.longitude?.toFixed(6)}</span>
<span>纬度: {realtimePosition.latitude?.toFixed(6)}</span>
<span>高度: {realtimePosition.altitude?.toFixed(1)}m</span>
</div>
</div>
)}
{/* 图例 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>图例</div>
<div className={styles.legend}>
<div className={styles.legendItem}>
<span className={`${styles.legendLine} ${styles.blue}`}></span>
<span>计划航线</span>
</div>
<div className={styles.legendItem}>
<span className={`${styles.legendLine} ${styles.green}`}></span>
<span>实际轨迹</span>
</div>
</div>
</div>
</div>
</div>
);
};
export default TaskPanel;
```
### 7.6 API服务封装
```typescript
// src/services/waylineRoute.ts
import { request } from 'umi';
// 航线任务列表项
export interface WaylineRouteListItemVO {
routeId: string;
routeName: string;
fileWaylineId: string;
deviceSn: string;
deviceName: string;
parseStatus: number;
waypointCount: number;
totalDistance: number;
totalDuration: number;
createTime: string;
}
// 航点数据
export interface WaypointVO {
index: number;
longitude: number;
latitude: number;
height: number;
speed?: number;
headingAngle?: number;
}
// 轨迹点数据
export interface TrackPointVO {
longitude: number;
latitude: number;
altitude?: number;
height?: number;
speed?: number;
heading?: number;
timestamp: number;
}
// 创建航线任务参数
export interface CreateRouteParams {
routeName: string;
fileWaylineId: string;
deviceSn: string;
remark?: string;
}
export const waylineRouteApi = {
// ★ 创建航线任务(关联航迹文件和设备)
createRoute: (params: CreateRouteParams) =>
request('/api/device/route/create', { method: 'POST', data: params }),
// ★ 核心接口:根据设备SN获取绑定的航线任务列表(任务管理页面使用)
getRouteListByDevice: (deviceSn: string) =>
request<{ resp_code: number; datas: WaylineRouteListItemVO[] }>(`/api/device/route/listByDevice/${deviceSn}`),
// 获取航线任务详情(含航点)
getRouteDetail: (routeId: string) =>
request(`/api/device/route/detail/${routeId}`),
// 获取航点列表(3D地图绑制航线使用)
getRouteWaypoints: (routeId: string) =>
request<{ resp_code: number; datas: WaypointVO[] }>(`/api/device/route/waypoints/${routeId}`),
// 解析航线任务
parseRoute: (routeId: string) =>
request(`/api/device/route/parse/${routeId}`, { method: 'POST' }),
// 批量解析航线任务
batchParseRoutes: (routeIds: string[]) =>
request('/api/device/route/parse/batch', { method: 'POST', data: { routeIds } }),
// 获取飞行轨迹
getFlightTrack: (deviceSn: string, params?: { jobId?: string; routeId?: string; startTime?: string; endTime?: string }) =>
request<{ resp_code: number; datas: { trackPoints: TrackPointVO[] } }>(`/api/device/drone/track/${deviceSn}`, { params }),
// 获取无人机设备列表(航线管理表单中选择设备使用)
getDroneDeviceList: () =>
request<{ resp_code: number; datas: Array<{ sn: string; deviceName: string }> }>('/api/device/drone/list'),
// 获取航迹文件列表(创建航线任务时选择航迹文件使用)
getWaylineFileList: (params?: any) =>
request<{ resp_code: number; datas: Array<{ waylineId: string; name: string }> }>('/api/device/wayline', { params }),
};
```
---
## 八、轨迹偏离检测
### 8.1 偏离计算算法
```java
/**
* 计算点到航线的最短距离
* 使用点到线段距离算法
*/
public class TrackDeviationCalculator {
// 偏离阈值(米)
private static final double DEVIATION_THRESHOLD = 10.0;
/**
* 计算当前位置与计划航线的偏离距离
*/
public double calculateDeviation(
double currentLng, double currentLat, double currentAlt,
List<WaypointVO> waypoints
) {
if (waypoints == null || waypoints.size() < 2) {
return 0;
}
double minDistance = Double.MAX_VALUE;
// 遍历所有航段,计算点到线段的最短距离
for (int i = 0; i < waypoints.size() - 1; i++) {
WaypointVO p1 = waypoints.get(i);
WaypointVO p2 = waypoints.get(i + 1);
double distance = pointToSegmentDistance(
currentLng, currentLat, currentAlt,
p1.getLongitude(), p1.getLatitude(), p1.getHeight(),
p2.getLongitude(), p2.getLatitude(), p2.getHeight()
);
minDistance = Math.min(minDistance, distance);
}
return minDistance;
}
/**
* 判断是否偏离航线
*/
public boolean isDeviated(double deviationDistance) {
return deviationDistance > DEVIATION_THRESHOLD;
}
/**
* 计算点到三维线段的距离
* 使用Haversine公式计算地球表面距离
*/
private double pointToSegmentDistance(
double px, double py, double pz,
double x1, double y1, double z1,
double x2, double y2, double z2
) {
// 简化:计算点到线段的水平距离 + 高度差
// 实际应用中可使用更精确的三维距离算法
// 线段向量
double dx = x2 - x1;
double dy = y2 - y1;
// 线段长度的平方
double segmentLengthSquared = dx * dx + dy * dy;
if (segmentLengthSquared == 0) {
// 线段退化为点
return haversineDistance(px, py, x1, y1);
}
// 计算投影参数t
double t = Math.max(0, Math.min(1,
((px - x1) * dx + (py - y1) * dy) / segmentLengthSquared
));
// 投影点坐标
double projX = x1 + t * dx;
double projY = y1 + t * dy;
double projZ = z1 + t * (z2 - z1);
// 计算水平距离
double horizontalDist = haversineDistance(px, py, projX, projY);
// 计算高度差
double verticalDist = Math.abs(pz - projZ);
// 三维距离
return Math.sqrt(horizontalDist * horizontalDist + verticalDist * verticalDist);
}
/**
* Haversine公式计算两点间的地球表面距离(米)
*/
private double haversineDistance(double lng1, double lat1, double lng2, double lat2) {
final double R = 6371000; // 地球半径(米)
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
}
```
### 8.2 偏离报警推送
```java
/**
* 偏离报警推送
*/
@Component
public class DeviationAlarmHandler {
@Autowired
private SseEmitterManager sseManager;
@Autowired
private IWaylineWaypointService waypointService;
/**
* 检查并推送偏离报警
*/
public void checkAndAlarm(String deviceSn, String waylineId,
double lng, double lat, double alt) {
// 获取航点数据
List<WaypointVO> waypoints = waypointService.getByWaylineId(waylineId);
// 计算偏离距离
TrackDeviationCalculator calculator = new TrackDeviationCalculator();
double deviation = calculator.calculateDeviation(lng, lat, alt, waypoints);
// 判断是否偏离
if (calculator.isDeviated(deviation)) {
// 构建报警消息
DeviationAlarmMessage alarm = new DeviationAlarmMessage();
alarm.setDeviceSn(deviceSn);
alarm.setWaylineId(waylineId);
alarm.setCurrentPosition(new double[]{lng, lat, alt});
alarm.setDeviationDistance(deviation);
alarm.setAlarmTime(new Date());
alarm.setLevel(deviation > 20 ? "HIGH" : "MEDIUM");
// 推送报警
sseManager.broadcast("DEVIATION_ALARM", alarm);
// 记录日志
log.warn("无人机偏离航线报警: deviceSn={}, waylineId={}, 偏离距离={}m",
deviceSn, waylineId, deviation);
}
}
}
```
---
## 九、实施计划
### 9.1 开发阶段划分
| 阶段 | 任务 | 优先级 | 预计工作量 |
|------|------|--------|-----------|
| **P0-基础设施** | 数据库表结构创建 | 高 | 0.5天 |
| **P0-基础设施** | 实体类、Mapper、Service基础代码生成 | 高 | 0.5天 |
| **P1-核心功能** | KMZ文件解析服务开发 | 高 | 2天 |
| **P1-核心功能** | 航线解析接口 & 绑定设备接口 | 高 | 1天 |
| **P1-核心功能** | 航点查询接口 | 高 | 0.5天 |
| **P2-轨迹功能** | 飞行轨迹记录逻辑 | 高 | 1天 |
| **P2-轨迹功能** | 轨迹查询接口 | 高 | 0.5天 |
| **P3-前端展示** | 3D任务管理页面框架 | 高 | 1天 |
| **P3-前端展示** | Cesium航线图层组件 | 高 | 1.5天 |
| **P3-前端展示** | Cesium轨迹图层组件 | 高 | 1天 |
| **P3-前端展示** | 实时轨迹WebSocket集成 | 高 | 1天 |
| **P4-增强功能** | 轨迹偏离检测 | 中 | 1天 |
| **P4-增强功能** | 偏离报警推送 | 中 | 0.5天 |
| **P5-优化测试** | 接口测试 | 中 | 1天 |
| **P5-优化测试** | 前端联调测试 | 中 | 1天 |
**总计: 约14天**
### 9.2 里程碑
| 里程碑 | 完成标准 | 目标日期 |
|--------|----------|----------|
| M1 | 数据库表创建完成,基础代码生成 | D+1 |
| M2 | KMZ解析功能可用,能解析示例文件 | D+4 |
| M3 | 后端接口全部完成,Postman测试通过 | D+7 |
| M4 | 前端页面可展示航线和轨迹 | D+11 |
| M5 | 功能联调完成,偏离检测可用 | D+14 |
---
## 十、风险与注意事项
### 10.1 技术风险
| 风险 | 影响 | 应对措施 |
|------|------|----------|
| KMZ文件格式变化 | 解析失败 | 做好版本兼容,记录解析错误 |
| 大量轨迹数据存储 | 数据库性能下降 | 定期归档,按时间分表 |
| WebSocket连接不稳定 | 实时轨迹断断续续 | 断线重连机制,本地缓存 |
| Cesium渲染性能 | 大量航点时卡顿 | 航点聚合,简化渲染 |
### 10.2 注意事项
1. **坐标系统一**: 大疆使用WGS84坐标系,Cesium默认也是WGS84,无需转换
2. **高度处理**: 注意区分相对高度(height)和海拔高度(elevation/altitude)
3. **数据安全**: 航线数据属于敏感信息,需做好租户隔离
4. **并发控制**: 解析大量航线时使用线程池,避免资源耗尽
5. **轨迹采样**: 实时轨迹可适当降采样(如每秒1次),减少数据量
---
## 十一、附录
### 附录A: 动作类型参数说明
| 动作类型 | 参数字段 | 说明 |
|----------|----------|------|
| takePhoto | payloadPositionIndex | 相机位置索引 |
| startRecord | payloadPositionIndex | 相机位置索引 |
| stopRecord | payloadPositionIndex | 相机位置索引 |
| hover | hoverTime | 悬停时间(秒) |
| zoom | focalLength | 焦距(mm) |
| gimbalRotate | gimbalPitchRotateAngle | 俯仰角(度) |
| rotateYaw | aircraftHeading | 机头朝向(度) |
| megaphone | megaphoneOperateFilePath | 音频文件路径 |
### 附录B: 参考资料
- [大疆WPML航线文件格式标准](https://developer.dji.com/doc/cloud-api-tutorial/cn/api-reference/dji-wpml/overview.html)
- [Cesium官方文档](https://cesium.com/learn/cesiumjs/ref-doc/)
- [Java解析KMZ文件示例](https://blog.csdn.net/qq_45745523/article/details/143750078)