fix:支付宝支付退款以及消息通知

This commit is contained in:
2026-07-27 18:57:36 +08:00
parent ca41fe080c
commit 9087a3c291
46 changed files with 3772 additions and 141 deletions
@@ -28,6 +28,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
/**
@@ -275,6 +276,87 @@ public class DeviceCommandController {
}
}
/**
* 指点飞行 - 首次飞向目标点
* 创建 fly_to_point 会话,flyToId = missionCode
*/
@Operation(summary = "无人机指点飞行 - 飞向目标")
@PostMapping("/flyToPoint")
public Result<String> flyToPoint(@RequestBody FlyToPointRequest request) {
log.info("收到指点飞行(首次)命令: device={}, flyToId={}, target=({}, {}, {})",
request.getDeviceSn(), request.getFlyToId(),
request.getLatitude(), request.getLongitude(), request.getHeight());
try {
JSONObject params = new JSONObject();
params.put("fly_to_id", request.getFlyToId());
params.put("latitude", request.getLatitude());
params.put("longitude", request.getLongitude());
params.put("height", request.getHeight() != null ? request.getHeight() : 100f);
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 12f);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"fly_to_point",
params
);
return Result.succeed(commandId, "指点飞行命令已发送");
} catch (Exception e) {
log.error("发送指点飞行命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 指点飞行 - 更新目标点(连续指点)
* 打断当前飞行,立即转向新目标;设备协议不含 fly_to_id,仅传 max_speed + points
*/
@Operation(summary = "无人机指点飞行 - 更新目标点")
@PostMapping("/flyToPointUpdate")
public Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequest request) {
log.info("收到指点飞行(更新)命令: device={}, target=({}, {}, {})",
request.getDeviceSn(), request.getLatitude(), request.getLongitude(), request.getHeight());
try {
JSONObject params = new JSONObject();
params.put("latitude", request.getLatitude());
params.put("longitude", request.getLongitude());
params.put("height", request.getHeight() != null ? request.getHeight() : 100f);
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 12f);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"fly_to_point_update",
params
);
return Result.succeed(commandId, "目标更新命令已发送");
} catch (Exception e) {
log.error("发送目标更新命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 指点飞行 - 停止指点飞行
*/
@Operation(summary = "无人机指点飞行 - 停止")
@PostMapping("/flyToPointStop")
public Result<String> flyToPointStop(@RequestParam String deviceSn) {
log.info("收到停止指点飞行命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"fly_to_point_stop",
new JSONObject()
);
return Result.succeed(commandId, "停止指点飞行命令已发送");
} catch (Exception e) {
log.error("发送停止指点飞行命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 开始录像
*/
@@ -425,6 +507,57 @@ public class DeviceCommandController {
}
}
/**
* 切换直播镜头(如切换到变焦镜头)
*/
@Operation(summary = "切换直播镜头")
@PostMapping("/liveLensChange")
public Result<String> liveLensChange(@RequestBody Map<String, Object> request) {
String deviceSn = (String) request.get("deviceSn");
String videoType = (String) request.get("videoType");
log.info("切换直播镜头: device={}, videoType={}", deviceSn, videoType);
try {
JSONObject params = new JSONObject();
params.put("video_type", videoType != null ? videoType : "zoom");
String commandId = commandManager.sendCommand(deviceSn, "live_lens_change", params);
return Result.succeed(commandId, "镜头切换命令已发送");
} catch (Exception e) {
log.error("切换镜头失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 设置变焦倍数
*/
@Operation(summary = "设置变焦倍数")
@PostMapping("/cameraFocalLengthSet")
public Result<String> cameraFocalLengthSet(@RequestBody Map<String, Object> request) {
String deviceSn = (String) request.get("deviceSn");
Double zoomFactor = request.get("zoomFactor") != null ?
Double.parseDouble(request.get("zoomFactor").toString()) : 2.0;
// 范围限制 2~200
zoomFactor = Math.max(2, Math.min(200, zoomFactor));
log.info("设置变焦: device={}, zoomFactor={}", deviceSn, zoomFactor);
try {
JSONObject params = new JSONObject();
params.put("camera_type", "zoom");
params.put("zoom_factor", zoomFactor);
String commandId = commandManager.sendCommand(deviceSn, "camera_focal_length_set", params);
return Result.succeed(commandId, "变焦命令已发送");
} catch (Exception e) {
log.error("设置变焦失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 执行航线任务
* 参考writeProperties逻辑,用于航线任务执行(不包含订单业务逻辑和幂等性检查)
@@ -646,6 +779,43 @@ public class DeviceCommandController {
private Boolean locked;
}
/**
* 指点飞行(首次飞向目标)请求参数
*/
@Data
public static class FlyToPointRequest {
/** 设备SN */
private String deviceSn;
/** 飞行会话ID(= missionCode) */
private String flyToId;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高(前端计算:Cartographic.height + 用户飞行高度) */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
/**
* 指点飞行更新目标(连续指点)请求参数
* 注意:设备协议不含 fly_to_id,仅传 max_speed + points
*/
@Data
public static class FlyToPointUpdateRequest {
/** 设备SN */
private String deviceSn;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高 */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
@Data
public static class CommandStatusDTO {
private String commandId;
@@ -10,7 +10,7 @@ public enum ControlEnum {
TAKEOFF_TO_POINT("takeoff_to_point"),
FLY_TO_POINT("fly_to_point"),
FLY_TO_POINT_STOP("fly_to_point_stop"),
FLY_TO_POINT_UPDATE("fly_to_point_stop"),
FLY_TO_POINT_UPDATE("fly_to_point_update"),
FLIGHTTASK_PAUSE("flighttask_pause"),
FLIGHTTASK_PREPARE ("flighttask_prepare"),
FLIGHTTASK_RECOVERY("flighttask_recovery"),
@@ -88,5 +88,20 @@ public class ControlMessageConstant {
}
public final static String LIVE_LENS_CHANGE = "{\n" +
"\t\"data\": {\n" +
"\t\t\"video_type\": video_type\n" +
"\t},\n" +
"\t\"method\": \"live_lens_change\"\n" +
"}";
public final static String CAMERA_FOCAL_LENGTH_SET = "{\n" +
"\t\"data\": {\n" +
"\t\t\"camera_type\": camera_type,\n" +
"\t\t\"zoom_factor\": zoom_factor\n" +
"\t},\n" +
"\t\"method\": \"camera_focal_length_set\"\n" +
"}";
}
@@ -147,7 +147,8 @@ public class DeviceCommandManager {
parameter.put("properties", properties);
JSONObject headers = new JSONObject();
headers.put("async", false);
// 指点飞行的下发、更新和停止均由设备异步执行,其余命令维持原有同步应答语义。
headers.put("async", requiresAsyncHeader(command.getCommandType()));
parameter.put("headers", headers);
// 构造完整消息
@@ -267,6 +268,43 @@ public class DeviceCommandManager {
data.put("locked", params.getBooleanValue("locked"));
break;
case "live_lens_change":
// 切换直播镜头
data.put("video_type", params.getString("video_type"));
break;
case "camera_focal_length_set":
// 设置变焦倍数
data.put("camera_type", params.getString("camera_type"));
data.put("zoom_factor", params.getDoubleValue("zoom_factor"));
break;
case "fly_to_point":
// 首次飞向目标点(生成 fly_to_id 会话)
data.put("fly_to_id", params.getString("fly_to_id"));
data.put("max_speed", params.getFloatValue("max_speed"));
// points 数组
JSONObject pointFirst = new JSONObject();
pointFirst.put("height", params.getFloatValue("height"));
pointFirst.put("latitude", params.getDoubleValue("latitude"));
pointFirst.put("longitude", params.getDoubleValue("longitude"));
data.put("points", new JSONObject[]{pointFirst});
break;
case "fly_to_point_update":
// 更新目标点(设备协议无 fly_to_id,仅 max_speed + points)
data.put("max_speed", params.getFloatValue("max_speed"));
JSONObject pointUpdate = new JSONObject();
pointUpdate.put("height", params.getFloatValue("height"));
pointUpdate.put("latitude", params.getDoubleValue("latitude"));
pointUpdate.put("longitude", params.getDoubleValue("longitude"));
data.put("points", new JSONObject[]{pointUpdate});
break;
case "fly_to_point_stop":
// 停止指点飞行 - 无参数
break;
default:
// 其他命令,直接使用 params 作为 data
data = params;
@@ -275,8 +313,8 @@ public class DeviceCommandManager {
properties.put("method", method);
// 一键起飞命令需要 data.data 的嵌套结构,其他命令直接使用 data
if ("takeoff_to_point".equals(method)) {
// 设备协议要求任务型飞行命令使用 data.data 嵌套结构。
if (requiresNestedDataWrapper(method)) {
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
@@ -287,6 +325,18 @@ public class DeviceCommandManager {
return properties;
}
private boolean requiresNestedDataWrapper(String method) {
return "takeoff_to_point".equals(method)
|| "fly_to_point".equals(method)
|| "fly_to_point_update".equals(method);
}
private boolean requiresAsyncHeader(String method) {
return "fly_to_point".equals(method)
|| "fly_to_point_update".equals(method)
|| "fly_to_point_stop".equals(method);
}
/**
* 加入队列
*/
@@ -399,11 +449,120 @@ public class DeviceCommandManager {
}, delay, TimeUnit.MILLISECONDS);
}
/**
* 同步等待的命令 Future 缓存: commandId -> CompletableFuture
*/
private final ConcurrentHashMap<String, CompletableFuture<CommandResult>> syncFutures = new ConcurrentHashMap<>();
/**
* 发送命令并同步等待设备响应
* 实现要点:先生成 commandId → 注册 Future → 再发送命令(避免设备快速响应时 Future 未注册的竞态)
*
* @param deviceSn 设备SN
* @param commandType 命令类型
* @param params 命令参数
* @param timeoutMs 超时时间(毫秒)
* @return 命令结果
*/
public CommandResult sendCommandSync(String deviceSn, String commandType, JSONObject params, long timeoutMs) {
// 1. 先生成 commandId
String commandId = UUID.randomUUID().toString();
// 2. 创建 Future 并注册(必须在发送命令之前)
CompletableFuture<CommandResult> future = new CompletableFuture<>();
syncFutures.put(commandId, future);
// 3. 创建命令对象并发送
DeviceCommand command = DeviceCommand.builder()
.commandId(commandId)
.deviceSn(deviceSn)
.commandType(commandType)
.params(params != null ? params : new JSONObject())
.status(CommandStatus.PENDING)
.createTime(System.currentTimeMillis())
.sendTime(0)
.expireTime(System.currentTimeMillis() + timeoutMs)
.retryCount(0)
.maxRetry(0)
.build();
log.info("创建同步命令: commandId={}, device={}, type={}, timeout={}ms",
commandId, deviceSn, commandType, timeoutMs);
try {
// 4. 检查并发送
if (!jetLinksWebSocketClient.isConnected()) {
jetLinksWebSocketClient.connect();
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
Thread.sleep(100);
waitCount++;
}
}
if (jetLinksWebSocketClient.isConnected()) {
sendCommandImmediately(command);
} else {
syncFutures.remove(commandId);
return CommandResult.failed("WebSocket 未连接");
}
// 5. 阻塞等待结果
CommandResult result = future.get(timeoutMs, TimeUnit.MILLISECONDS);
log.info("同步命令完成: commandId={}, success={}", commandId, result.isSuccess());
return result;
} catch (TimeoutException e) {
log.error("同步命令超时: commandId={}, device={}, type={}, timeout={}ms",
commandId, deviceSn, commandType, timeoutMs);
syncFutures.remove(commandId);
return CommandResult.timeout("命令执行超时");
} catch (Exception e) {
log.error("同步命令异常: commandId={}, error={}", commandId, e.getMessage());
syncFutures.remove(commandId);
return CommandResult.failed("命令执行异常: " + e.getMessage());
}
}
/**
* 命令结果 DTO
*/
@lombok.Data
@lombok.AllArgsConstructor
public static class CommandResult {
private boolean success;
private String message;
private String commandId;
public static CommandResult success(String commandId) {
return new CommandResult(true, "执行成功", commandId);
}
public static CommandResult failed(String message) {
return new CommandResult(false, message, null);
}
public static CommandResult timeout(String message) {
return new CommandResult(false, message, null);
}
}
/**
* 接收设备命令响应
*/
public void handleCommandResponse(String commandId, boolean success, String message) {
DeviceCommand command = pendingCommands.remove(commandId);
// 同步等待的 Future 回调
CompletableFuture<CommandResult> syncFuture = syncFutures.remove(commandId);
if (syncFuture != null) {
if (success) {
syncFuture.complete(CommandResult.success(commandId));
} else {
syncFuture.complete(CommandResult.failed(message != null ? message : "设备执行失败"));
}
}
if (command == null) {
log.warn("收到未知命令响应: commandId={}", commandId);
return;
@@ -453,6 +612,11 @@ public class DeviceCommandManager {
command.setStatus(CommandStatus.TIMEOUT);
log.warn("命令响应超时: commandId={}, device={}",
command.getCommandId(), command.getDeviceSn());
// 同步 Future 超时回调
CompletableFuture<CommandResult> syncFuture = syncFutures.remove(command.getCommandId());
if (syncFuture != null) {
syncFuture.complete(CommandResult.timeout("命令响应超时"));
}
pendingTimeoutCount.incrementAndGet();
return true;
}
@@ -0,0 +1,770 @@
# JetLinks WebSocket 对接方案 — 迁移指南
> 目标读者:把这套 JetLinks 平台对接方案迁移到新 Spring Boot 项目的开发者。
> 覆盖范围:WebSocket 长连接 + 主题订阅 + 命令下发 + 分布式引用计数 + 消息解析全流程。
---
## 一、方案能力
- **单节点单连接**:全局共享一条 WebSocket,所有设备走主题订阅模式。
- **懒加载**:项目启动不连接,首次订阅或首次发命令时才建立连接;全部取消后自动断开。
- **分布式安全**:多实例通过 Redis 引用计数决定首/末订阅者,跨实例互不干扰。
- **自动重连 + Token 自刷新**:指数退避重连;`authError` 触发 Token 刷新后再重连;重连后基于 Redis 状态挑选真实需要的主题。
- **命令队列**:断线时命令进队列,重连后按顺序重发;支持指数退避重试、超时清理、异步 response 回调。
- **多产品线兼容**:默认适配大疆机场(AutoDock3),改主题模板即可支持其他产品。
---
## 二、整体架构
```
┌────────────────────────────────────────────────────────┐
│ 业务入口(SSE / REST / MQ 消费者 …) │
└────────────────────────┬───────────────────────────────┘
↓
┌────────────────────────────────────────────────────────┐
│ SubscriptionPoolService(Redis 引用计数,分布式共享) │
│ device:sub:{sn}:{topicType} → Set<sessionId> │
│ device:sub:session:{sessionId} → Set<sn:topicType> │
└────────────────────────┬───────────────────────────────┘
首/末订阅者触发或取消
↓
┌────────────────────────────────────────────────────────┐
│ DeviceSubscriptionManager(业务侧订阅编排) │
└────────────────────────┬───────────────────────────────┘
↓
┌────────────────────────────────────────────────────────┐
│ JetLinksWebSocketClient(全局单例长连接) │
│ - subscribedTopics / topicSubscriptionIds │
│ - deviceSubscriptionCounts │
│ - 心跳 / 重连 / 认证过期 → 刷新Token │
└────────┬──────────────────────────────┬────────────────┘
↓ ↓
┌──────────────────┐ ┌──────────────────────┐
│ TokenManager │ │ DeviceMessageHandler │
│ OAuth2 + 缓存 │ │ 解析 / 缓存 / 推送 │
└──────────────────┘ └──────────┬───────────┘
↓
┌──────────────────────┐
│ DeviceCommandManager │
│ 命令队列 / 重试 / 超时 │
└──────────────────────┘
可选:IsolatedWebSocketClient —— 一次性抓取场景独立短连接
```
---
## 三、依赖与配置
### 3.1 Maven 依赖
```xml
<!-- Spring 基础 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- OAuth2 Token 获取 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<!-- JSON 处理 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.53</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
```
Spring Boot 3.x 使用 `jakarta.annotation.*`;Spring Boot 2.x 需改为 `javax.annotation.*`。
### 3.2 application.yml
```yaml
device:
websocket:
oauth2:
token-url: http://<jetlinks-host>:8848/oauth2/token
client-id: <your-client-id>
client-secret: <your-client-secret>
connection:
base-url: ws://<jetlinks-host>:8848/device
connect-timeout: 10000
read-timeout: 60000
heartbeat:
enabled: true
interval: 30000
reconnect:
enabled: true
max-attempts: 10
initial-delay: 2000
max-delay: 60000
multiplier: 2
subscribe:
batch-size: 50
batch-interval: 500
on-demand: true
timeout:
offline-threshold: 60000
check-interval: 10000
command:
default-timeout: 60000
max-retry: 3
retry-delay-base: 1000
queue-max-size: 100
cleanup-interval: 10000
spring:
redis:
host: <redis-host>
port: 6379
password: <optional>
```
### 3.3 启动类
```java
@SpringBootApplication
@EnableScheduling // 命令过期清理需要
public class YourApp { ... }
```
---
## 四、文件清单(14 个 Java 文件)
放到你的项目里,保留同名包结构;`com.central.device.websocket` 可整体改成你项目的包名。
```
websocket/
├── config/
│ └── WebSocketProperties.java
├── client/
│ ├── JetLinksWebSocketClient.java ★ 核心
│ └── IsolatedWebSocketClient.java (可选)
├── manager/
│ ├── TokenManager.java
│ ├── SubscriptionPoolService.java
│ ├── DeviceSubscriptionManager.java ★ 需按新项目改造
│ └── DeviceCommandManager.java
├── handler/
│ └── DeviceMessageHandler.java ★ 需按新项目改造
└── model/
├── SubscriptionTopic.java ★ 需按产品线改
├── SubscriptionMessage.java
├── DeviceCommand.java
├── CommandStatus.java
├── DeviceRealtimeData.java
├── DroneRealtimeData.java
├── GpsData.java
└── message/
├── PropertyReportMessage.java
├── DeviceStateEventMessage.java
└── MsgAlarmEventMessage.java
```
---
## 五、协议参考(JetLinks 侧)
### 5.1 主题订阅报文
```json
// 订阅
{"type":"sub","topic":"/device/AutoDock3/{sn}/message/event/fire_alarm","parameter":{},"id":"sub-xxx"}
// 取消订阅 (id 必须与订阅时相同)
{"type":"unsub","topic":"/device/AutoDock3/{sn}/message/event/fire_alarm","parameter":{},"id":"sub-xxx"}
// 心跳
{"type":"ping","timestamp":1700000000000}
// 服务端回复
{"type":"pong"}
// 认证过期
{"type":"authError","message":"..."}
```
### 5.2 命令下发报文
```json
{
"type": "sub",
"topic": "/device-message-sender/AutoDock3/{sn}",
"parameter": {
"messageType": "WRITE_PROPERTY",
"properties": {
"method": "takeoff_to_point",
"data": { "data": { /* 指令参数 */ } }
},
"headers": { "async": false }
},
"id": "request-id-xxx"
}
```
### 5.3 主题列表(大疆机场默认)
| 主题模板 | 说明 |
|---------|------|
| `/device/AutoDock3/{sn}/online` | 设备上线 |
| `/device/AutoDock3/{sn}/offline` | 设备离线 |
| `/device/AutoDock3/{sn}/message/property/report` | 属性上报 |
| `/device/AutoDock3/{sn}/message/event/fire_alarm` | **设备状态事件**(非火警,是机库/无人机综合状态) |
| `/device/AutoDock3/{sn}/message/event/msg_alarm` | 无人机遥测数据 |
| `/device-message-sender/AutoDock3/{sn}` | 命令下发 / 命令响应 |
新项目若接不同产品线,改 `SubscriptionTopic` 里的模板段(例如 `D-Dock2`、`ship`)或用 `subscribeRawTopic()` 传入完整 topic。
### 5.4 大疆 DRC 指令集
按 `method` 分类,`DeviceCommandManager.buildCommandProperties()` 已按指令组装好参数:
| method | 参数 | 说明 |
|--------|------|------|
| `takeoff_to_point` | 经纬度、目标高度、返航高度等 | 一键起飞(注意 `data.data` 嵌套) |
| `return_home` / `return_home_cancel` | 无 | 一键返航 / 取消返航 |
| `flighttask_pause` / `flighttask_recovery` | 无 | 航线暂停 / 恢复 |
| `drc_mode_enter` | 无 | 进入指令飞行模式 |
| `stick_control` | roll/pitch/throttle/yaw (624~1424) | DRC 杆量控制,5-10Hz 下发 |
| `camera_screen_drag` | pitch_speed / yaw_speed / locked | 云台拖动 |
| `camera_mode_switch` | camera_mode (0拍照/1录像/2低光/3全景) | 切相机模式 |
| `camera_photo_take` | 无 | 拍照 |
| `camera_recording_start` / `camera_recording_stop` | 无 | 录像开始 / 结束 |
---
## 六、关键设计要点(迁移时必须理解)
### 6.1 懒加载 + 自动断开
```java
// JetLinksWebSocketClient.subscribeDevice()
if (!isConnected()) {
connect(); // 首次触发连接
// 最多等 5 秒
while (!isConnected() && waitCount < 50) { Thread.sleep(100); waitCount++; }
}
// ...
// unsubscribeDevice() 末尾
if (subscribedTopics.isEmpty()) {
deviceSubscriptionCounts.clear();
closeConnection(); // 全部取消 → 主动断开
}
```
`closeConnection()` 会置 `isAutoClose=true`,`afterConnectionClosed()` 里跳过重连。
### 6.2 订阅 ID 一致性(重要)
订阅和取消订阅必须携带同一个 `id`,否则 JetLinks 无法定位该订阅。用 `topicSubscriptionIds` 保存 `topic → id` 的映射:
```java
String subscriptionId = "sub-" + deviceSn + "-" + topic + "-" + UUID.randomUUID().toString().substring(0, 8);
topicSubscriptionIds.put(topic, subscriptionId);
// 发订阅报文...
// 取消时:
String subscriptionId = topicSubscriptionIds.remove(topic);
// 发取消订阅报文,携带相同 id
```
### 6.3 Redis 双向索引 + 引用计数
```
device:sub:{sn}:{topicType} → Set<sessionId> # 按设备主题反查订阅者
device:sub:session:{sessionId} → Set<sn:topicType> # 按 session 快速清理
```
- `addSubscription()` → SADD 到两个 Set,返回是否是**首次订阅者**(`isFirst`),只有 true 才向 WebSocket 发订阅报文。
- `removeSubscription()` → SREM,返回是否是**最后一个订阅者**(`isLast`),只有 true 才发取消订阅报文。
- 24h TTL 兜底 + 60s 一次孤儿清理(活跃 sessionId 集合 vs Redis 中的 session)。
**分布式必备**。单机也建议用同一套代码,切换到嵌入式 Redis 或删掉分布式逻辑都可以。
### 6.4 消息路由
```
handleTextMessage()
├── type=pong → 忽略
├── type=authError → 刷 Token + 重连
├── topic 含 /device-message-sender/ → 命令响应 → DeviceCommandManager
└── 其他 → handleSubscriptionResult()
├── /online → markDeviceOnline
├── /offline → markDeviceOffline
├── /message/property/report → handlePropertyReport
├── /message/event/fire_alarm → handleDeviceStateEvent
└── /message/event/msg_alarm → handleMsgAlarmEvent
```
从 topic 提取 deviceSn 的规则:`/device/{productType}/{sn}/...` 或 `/device-message-sender/{productType}/{sn}` 的第 4 段。
### 6.5 fire_alarm 三段合并(大疆机场特性)
`fire_alarm` 会循环推送三种结构的数据:
| 类型 | 识别字段 | 内容 |
|-----|---------|------|
| 0 - 飞行任务 | `wireless_link` / `sdr` / `tilt_angle` / `flighttask_step_code` | 图传状态 |
| 1 - 机库综合 | `drone_charge_state` / `sub_device` / `environment_temperature` | 环境+子设备 |
| 2 - 机库状态 | `drone_battery_maintenance_info` / `electric_supply_voltage` | 供电+电池 |
`DeviceMessageHandler.deviceDataCache[sn] = JSONObject[3]`,按 `identifyDataType()` 归位;**三种齐全**才 `deepMerge()` 并向下游推送,避免半截数据。
### 6.6 心跳 & 重连
- 心跳:默认 30s,发 `{"type":"ping","timestamp":...}`。
- 重连:指数退避,`delay = min(initialDelay × multiplier^attempts, maxDelay)`。
- 重连成功后 `resubscribeAll()`:**基于 Redis 池状态**决定订阅哪些主题(避免恢复已取消的死订阅):
```java
if (subscriptionPoolService.hasSubscribers(sn, TopicType.FIRE_ALARM)) topics.add(EVENT_FIRE_ALARM);
if (subscriptionPoolService.hasSubscribers(sn, TopicType.MSG_ALARM)) topics.add(EVENT_MSG_ALARM);
if (hasFireAlarm || hasMsgAlarm || hasOnline) topics.add(ONLINE);
if (hasFireAlarm || hasMsgAlarm || hasOffline) topics.add(OFFLINE);
```
### 6.7 Token 生命周期
- OAuth2 `client_credentials` 模式,`expires_in - 60s` 判过期。
- 3 次重试;重试全部失败时,如果旧 token 距离真实过期还有 60s 缓冲,允许降级返回旧 token。
- 收到 `authError` 时刷新 Token → 关连接 → 触发重连。
### 6.8 命令下发流程
```
sendCommand(sn, method, params)
↓
未连接?→ connect() + 最多等 5s
↓
连接成功 → sendCommandImmediately()
↓ (放入 pendingCommands 等待响应)
连接失败 → addToQueue()(每设备独立队列,上限 100)
↓
【收到响应】/device-message-sender/... → handleCommandResponse(commandId, success, msg)
【WS 重连】 → onWebSocketReconnected() → 按队列顺序重发(每条间隔 100ms)
【超时】@Scheduled 每 10s 扫描 → 队列过期 EXPIRED / pendingCommands 超时 TIMEOUT
【发送异常】retryCommand() 指数退避重试 (delay = 2^retryCount × base)
```
### 6.9 抑制无效日志
- `subscribedTopics.contains(topic)` 过滤已取消订阅但延迟到达的消息。
- `recentlyUnsubscribedDevices` 5s 宽限期,避免 unsubscribe 瞬间刷 warn。
---
## 七、迁移改造清单
### 7.1 必须适配的 4 处
**1. 产品类型(`SubscriptionTopic.java`)**
```java
// 默认全是 AutoDock3,改成你的产品:
ONLINE("/device/AutoDock3/{deviceSn}/online"),
// →
ONLINE("/device/YourProduct/{deviceSn}/online"),
```
**2. 命令 topic 前缀(`DeviceCommandManager.sendCommandImmediately`)**
```java
message.put("topic", "/device-message-sender/AutoDock3/" + command.getDeviceSn());
// → 改成你的产品
```
**3. 业务耦合点(`DeviceSubscriptionManager`)**
原代码依赖 `IAgeDeviceService`(景区设备表)和 `DeviceMessageHandler.addDevice(sn, scenicId, tenantId)`。迁移时二选一:
- 保留景区级订阅:用你项目的设备 Service 替换 `IAgeDeviceService`。
- 只要单设备订阅:删掉 `subscribeForScenic` / `unsubscribeForScenic` / 景区缓存,只保留下面这个方法:
```java
public void subscribeDevice(String deviceSn, String tenantId) {
messageHandler.addDevice(deviceSn, 0L, tenantId);
jetLinksWebSocketClient.subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE, SubscriptionTopic.EVENT_FIRE_ALARM);
}
public void unsubscribeDevice(String deviceSn) {
// ⚠️ 不要取消 EVENT_MSG_ALARM,那是操控台单独管理的
jetLinksWebSocketClient.unsubscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE, SubscriptionTopic.EVENT_FIRE_ALARM);
messageHandler.removeDevice(deviceSn);
}
```
**4. 下游推送(`DeviceMessageHandler.pushDeviceDataUpdate`)**
原代码通过反射调用 `sseEmitterManager.sendDeviceDataUpdate(sn, data)` / `sendDroneDataUpdate(sn, data)`。新项目:
- 若继续用 SSE:实现同名方法,或直接把反射调用改成强类型调用。
- 换成 WebFlux Sink / MQ / 直接落库:改 `pushDeviceDataUpdate()` 和 `handleMsgAlarmEvent()` 里对应位置。
`DeviceAlarmDataService` 是把 fire_alarm / msg_alarm 快照写 Redis 的服务,可选实现。
### 7.2 依赖注入接线(有循环依赖)
`JetLinksWebSocketClient` ↔ `DeviceCommandManager` ↔ `SubscriptionPoolService` 三者有环,用 setter 打破。**必须**在启动后完成以下接线,否则重连时无法基于 Redis 状态恢复订阅、命令响应无法回调:
```java
// DeviceCommandManager 的 @PostConstruct 里已做:
jetLinksWebSocketClient.setCommandManager(this);
// 你需要显式做:
@Component
class WebSocketWiring {
@Autowired JetLinksWebSocketClient client;
@Autowired SubscriptionPoolService pool;
@Autowired DeviceMessageHandler handler;
@Autowired(required = false) YourSseManager sse;
@PostConstruct
void wire() {
client.setSubscriptionPoolService(pool);
if (sse != null) handler.setSseEmitterManager(sse);
}
}
```
### 7.3 已知问题(迁移前顺手修)
原项目审计报告发现的 P0 问题(详见 `WebSocket订阅机制审计报告.md`),新项目建议直接按修复版写:
**问题 A:机库 SSE 断开时按主题分别判断 `isLast`,不要 `&&` 合并**
```java
// 错误写法:
if (isLastFireAlarm && isLastOnline && isLastOffline) {
deviceSubscriptionManager.unsubscribeDevice(deviceSn); // 混合场景永远进不来
}
// 正确写法:
if (isLastFireAlarm) {
jetLinksWebSocketClient.unsubscribeDevice(sn, SubscriptionTopic.EVENT_FIRE_ALARM);
}
if (isLastOnline && isLastOffline
&& !subscriptionPoolService.hasSubscribers(sn, TopicType.MSG_ALARM)) {
jetLinksWebSocketClient.unsubscribeDevice(sn, SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
}
```
**问题 B:`unsubscribeDevice()` 不要连 `EVENT_MSG_ALARM` 一起取消**
`msg_alarm` 属于操控台生命周期,应由 `unsubscribeDroneTelemetry()` 单独管理。
---
## 八、上手示例
### 8.1 基础订阅 / 取消订阅(业务代码)
```java
@RestController
@RequestMapping("/device")
public class DeviceController {
@Autowired JetLinksWebSocketClient wsClient;
@Autowired SubscriptionPoolService pool;
@Autowired DeviceSubscriptionManager subMgr;
@PostMapping("/monitor/{sn}")
public Result<?> startMonitor(@PathVariable String sn,
@RequestParam String sessionId,
@RequestParam String tenantId) {
// 引用计数:只有首次订阅者才真正下发订阅报文
boolean isFirst = pool.addSubscription(sessionId, sn, TopicType.FIRE_ALARM)
| pool.addSubscription(sessionId, sn, TopicType.ONLINE)
| pool.addSubscription(sessionId, sn, TopicType.OFFLINE);
if (isFirst) subMgr.subscribeDevice(sn, tenantId);
return Result.ok();
}
@DeleteMapping("/monitor/{sn}")
public Result<?> stopMonitor(@PathVariable String sn,
@RequestParam String sessionId) {
boolean isLastFireAlarm = pool.removeSubscription(sessionId, sn, TopicType.FIRE_ALARM);
boolean isLastOnline = pool.removeSubscription(sessionId, sn, TopicType.ONLINE);
boolean isLastOffline = pool.removeSubscription(sessionId, sn, TopicType.OFFLINE);
if (isLastFireAlarm) {
wsClient.unsubscribeDevice(sn, SubscriptionTopic.EVENT_FIRE_ALARM);
}
if (isLastOnline && isLastOffline
&& !pool.hasSubscribers(sn, TopicType.MSG_ALARM)) {
wsClient.unsubscribeDevice(sn, SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
}
return Result.ok();
}
}
```
### 8.2 下发命令
```java
@Autowired DeviceCommandManager cmdMgr;
// 一键起飞
JSONObject params = new JSONObject();
params.put("target_latitude", 31.2120679);
params.put("target_longitude", 110.86967);
params.put("target_height", 322.63797);
params.put("security_takeoff_height", 50);
params.put("rth_mode", 1);
params.put("rth_altitude", 50);
params.put("rc_lost_action", 2);
params.put("commander_mode_lost_action", 1);
params.put("commander_flight_mode", 1);
params.put("commander_flight_height", 50);
params.put("flight_id", UUID.randomUUID().toString());
params.put("max_speed", 5);
params.put("flight_safety_advance_check", 0);
String commandId = cmdMgr.sendCommand(deviceSn, "takeoff_to_point", params);
// 拍照
cmdMgr.sendCommand(deviceSn, "camera_photo_take", new JSONObject());
// 查询状态
CommandStatus status = cmdMgr.getCommandStatus(commandId);
```
### 8.3 SSE + 断开清理
前端刷新/关闭页面时用 `navigator.sendBeacon()` 触发后端清理;后端定时(60s)扫描活跃 session 列表,用 `SubscriptionPoolService.cleanupOrphanSessions(activeIds)` 清理孤儿。
---
## 八点五、两种命令下发方式(WebSocket vs REST)
命令下发有两条路径可选,可以按场景混用:
| 维度 | WebSocket 通道(本方案) | JetLinks REST API |
|------|-----------------------|-------------------|
| 实现类 | `DeviceCommandManager` | 直接 HTTP 调用 JetLinks |
| 触发点 | 长连接已建立时最快 | 无需长连接,任何时候都能发 |
| 响应机制 | 异步,通过 `/device-message-sender/...` 主题回调 `handleCommandResponse()` | 同步,HTTP 返回体即结果 |
| 断线容错 | 有队列 + 重连后重发 | 请求当场失败,需业务方重试 |
| 状态查询 | `commandManager.getCommandStatus(commandId)` | 无状态跟踪,靠 HTTP 响应 |
| 高频指令(DRC 杆量 5-10Hz) | ✅ 更合适 | ❌ 每次都建 HTTP 连接,太重 |
| 一次性长任务(航线下发) | ⚪ 可用 | ✅ 更合适,直接拿结果 |
### 8.5.1 WebSocket 通道 — HTTP 接口封装
`DeviceCommandController` 是 `DeviceCommandManager` 的 HTTP 门面,前端/其他服务直接调 REST 即可,无需感知 WebSocket 存在。搬到新项目改一下包和 `Result` 类型就能用:
**通用发送 / 状态查询:**
```
POST /device/command/send
Body: { "deviceSn": "SN123", "commandType": "takeoff_to_point", "params": {...} }
Resp: { "code": 0, "data": "<commandId>" }
GET /device/command/status/{commandId}
Resp: { "commandId":"...", "status":"SENT", "statusDesc":"已发送,等待设备响应",
"deviceSn":"SN123", "commandType":"takeoff_to_point",
"createTime":..., "sendTime":..., "retryCount":0, "errorMsg":null }
```
**语义化端点(对前端更友好):**
| 接口 | 方法 | 参数 | 说明 |
|------|------|------|------|
| `POST /device/command/takeoff` | body: `TakeoffRequest` | 一键起飞(自带默认值填充) |
| `POST /device/command/return?deviceSn=` | query | 一键返航 |
| `POST /device/command/return/cancel?deviceSn=` | query | 取消返航 |
| `POST /device/command/pause?deviceSn=` | query | 航线暂停 / 紧急悬停 |
| `POST /device/command/resume?deviceSn=` | query | 航线恢复 |
| `POST /device/command/photo?deviceSn=` | query | 拍照 |
| `POST /device/command/recording/start?deviceSn=` | query | 开始录像 |
| `POST /device/command/recording/stop?deviceSn=` | query | 停止录像 |
| `POST /device/command/camera/mode?deviceSn=&cameraMode=` | query | 切换相机模式 |
| `POST /device/command/drc/enter?deviceSn=` | query | 进入 DRC 模式 |
| `POST /device/command/drc/stick` | body: `StickControlRequest` | DRC 杆量控制 |
| `POST /device/command/gimbal` | body: `GimbalControlRequest` | 云台拖动控制 |
**调用示例(curl):**
```bash
# 拍照
curl -X POST 'http://<host>/device/command/photo?deviceSn=SN123'
# 一键起飞
curl -X POST 'http://<host>/device/command/takeoff' \
-H 'Content-Type: application/json' \
-d '{
"deviceSn": "SN123",
"targetLatitude": 31.2120679,
"targetLongitude": 110.86967,
"targetHeight": 322.6,
"commanderFlightHeight": 50,
"maxSpeed": 5
}'
# 查询命令执行状态
curl 'http://<host>/device/command/status/<commandId>'
```
**迁移改造清单:**
- `Result` / `@Tag` / `@Operation` 换成新项目对应的返回体和文档注解。
- `getStreamUrls(deviceSn)` 依赖本项目的设备表(推流地址),删掉或改成你项目的 Service。
- 起飞接口里 `flight_id` 默认取 UUID,业务上要联动订单号的话在这里改。
### 8.5.2 REST API 通道 — 直接调 JetLinks
JetLinks 平台自带一套设备属性下发 REST API,不需要 WebSocket 长连接。项目里"执行航线任务"就是走这条:
```
POST http://<jetlinks-host>:8848/device/instance/{deviceSn}/property
Header: Authorization: Bearer <token>
Body: { "method": "flighttask_prepare", "data": {...} }
Response: { "status": 200, "message": "success", "result": {...} }
错误码: 500 + "Device is offline" → 设备离线
```
**核心代码位置:** `DeviceCommandController.executeWayline()` 及其 `buildWaylineControlMessage()`。搬迁时需要一起带走的辅助类:
| 类 | 职责 |
|----|------|
| `RequestUtils` | 封装 `getPostRequestResult` 之类的 HTTP 调用(带鉴权头) |
| `IotRequestResult` | 解析 JetLinks 响应体 `{status, message, result}` |
| `ControlMessageConstant` | 保存指令模板 JSON(`flighttask_prepare`、`stick_control` 等) |
**REST 通道适用场景:**
- **航线任务下发**:payload 较大,一次性完成,需要立即知道结果。
- **属性读写**:与 `SubscriptionTopic.PROPERTY_READ / PROPERTY_WRITE` 等价,但同步返回。
- **无长连接的边缘节点/脚本**:只发一两条命令就退出,没必要建 WebSocket。
- **平台管理接口**:设备产品配置、日志查询、固件下发等 JetLinks 提供的 REST 能力。
**通用调用骨架(新项目可以直接抄):**
```java
@RestController
@RequestMapping("/device/rest-command")
public class DeviceRestCommandController {
@Value("${jetlinks.server.baseUrl}")
private String jetlinksBaseUrl;
@Autowired
private RequestUtils requestUtils; // 带 token 的 HTTP 调用工具
@PostMapping("/property/{deviceSn}")
public Result<String> sendProperty(@PathVariable String deviceSn,
@RequestBody JSONObject body) {
String url = jetlinksBaseUrl + "/device/instance/" + deviceSn + "/property";
Map<String, String> resp = requestUtils.getPostRequestResultMap(url, body.toJSONString());
JSONObject json = JSON.parseObject(resp.get(""));
IotRequestResult r = IotRequestResult.getInstance(json);
return r.getStatus() == 200
? Result.succeed(r.getMessage())
: Result.failed(r.getMessage());
}
}
```
`RequestUtils` 里需要注入 `TokenManager.getValidToken()` 作为 `Authorization: Bearer <token>` 头,Token 复用 WebSocket 通道那套 OAuth2 客户端凭证。
### 8.5.3 组合使用建议
| 场景 | 推荐通道 |
|------|---------|
| 前端页面持续订阅设备状态 | WebSocket |
| 高频控制指令(DRC 杆量、云台拖动) | WebSocket |
| 一次性拍照 / 录像开关 | 都可以,WebSocket 更省资源 |
| 航线下发、属性读写 | REST |
| 后台服务批量下发命令 | REST(无需维护长连接) |
| 无人值守脚本 / 定时任务 | REST |
**混合部署时的一致性:** 两条通道最终都到 JetLinks 平台,设备侧不区分来源。业务侧要注意命令幂等和状态跟踪 —— REST 通道没有 `commandId` 概念,需要业务方自己带任务号(如 `missionCode`)关联结果。
---
## 九、启动流程时序
```
1. Bean 装配
├── WebSocketProperties @ConfigurationProperties 装载
├── TokenManager 就绪(不请求 token)
├── JetLinksWebSocketClient.init() 只创建重连线程池
├── DeviceCommandManager.init() 回填 commandManager 引用
├── SubscriptionPoolService 就绪
└── WebSocketWiring.wire() setSubscriptionPoolService / setSseEmitterManager
2. 首次业务调用
├── 前端建立 SSE / 调 REST
├── SubscriptionPoolService.addSubscription() → isFirst=true
├── DeviceSubscriptionManager.subscribeDevice()
├── JetLinksWebSocketClient.subscribeDevice()
│ └── isConnected? → 否 → connect() → 等待 5s → afterConnectionEstablished()
│ ↓
│ startHeartbeat() + resubscribeAll()
└── 发订阅报文
```
---
## 十、监控与排障
**关键日志前缀:**
- `订阅设备:` / `取消订阅设备:` — 业务层订阅动作
- `发送订阅消息:` / `取消订阅主题:` — WebSocket 层实际报文
- `WebSocket连接成功` / `WebSocket连接关闭` — 连接状态
- `Token刷新成功` / `Token刷新失败` — Token 生命周期
- `命令发送成功` / `命令响应解析结果` — 命令流转
- `设备 X 数据未齐全` — fire_alarm 三段合并等待
**排障 checklist:**
- 收不到数据 → 确认 `subscribedTopics` 含目标 topic,`isConnected() == true`。
- 命令没响应 → 检查 topic 前缀(产品类型);检查 `pendingCommands` 是否有该 commandId。
- 重连后订阅错乱 → 确认 `setSubscriptionPoolService()` 已调用;查 `resubscribeAll()` 日志。
- Redis 池残留 → 手动跑 `SubscriptionPoolService.printSubscriptionStatus()` / `clearAllSubscriptions()`。
- 收到 `topic=null` warn → 通常是 `handleSubscriptionResult` 里的非设备消息(如订阅确认回执),不影响业务。
**订阅一致性巡检(推荐):**
```java
@Scheduled(fixedDelay = 300_000)
public void checkConsistency() {
for (String sn : wsClient.getActiveDevices()) {
int wsCount = wsClient.getDeviceSubscriptionCount(sn);
boolean redisHas = pool.hasSubscribers(sn, TopicType.FIRE_ALARM)
|| pool.hasSubscribers(sn, TopicType.MSG_ALARM)
|| pool.hasSubscribers(sn, TopicType.ONLINE);
if (wsCount > 0 && !redisHas) {
log.warn("检测到订阅残留: sn={}, wsCount={}", sn, wsCount);
}
}
}
```
---
## 十一、参考文档
同目录下的原始文档保留了更细节的部分,作为补充参考:
- `WebSocket懒加载使用说明.md` — 懒加载语义 + API 快速参考
- `WebSocket消息处理说明.md` — 消息 POJO 结构 + 处理逻辑
- `WebSocket订阅机制审计报告.md` — 已知问题 + 修复方案 + 场景推演
- `指令飞行.md` — 大疆 DRC 指令集完整参数字典
@@ -0,0 +1,92 @@
package com.central.device.websocket.manager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.model.CommandStatus;
import com.central.device.websocket.model.DeviceCommand;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Method;
public class DeviceCommandManagerTest {
@Test
public void flyToPointUsesNestedDataWrapper() throws Exception {
JSONObject params = new JSONObject();
params.put("fly_to_id", "FP20260724164503");
params.put("max_speed", 12.0f);
params.put("height", 55.327644f);
params.put("latitude", 30.61043916027994d);
params.put("longitude", 114.39342878294764d);
JSONObject properties = buildProperties("fly_to_point", params);
Assert.assertEquals("fly_to_point", properties.getString("method"));
JSONObject outerData = properties.getJSONObject("data");
Assert.assertNotNull("指点飞行外层 data 下必须继续包含 data", outerData.getJSONObject("data"));
JSONObject commandData = outerData.getJSONObject("data");
Assert.assertEquals("FP20260724164503", commandData.getString("fly_to_id"));
Assert.assertEquals(12.0f, commandData.getFloatValue("max_speed"), 0.001f);
JSONArray points = commandData.getJSONArray("points");
Assert.assertEquals(1, points.size());
Assert.assertEquals(55.327644f, points.getJSONObject(0).getFloatValue("height"), 0.001f);
}
@Test
public void flyToPointUpdateUsesNestedDataWrapper() throws Exception {
JSONObject params = new JSONObject();
params.put("max_speed", 10.0f);
params.put("height", 60.0f);
params.put("latitude", 30.61043916027994d);
params.put("longitude", 114.39342878294764d);
JSONObject properties = buildProperties("fly_to_point_update", params);
JSONObject commandData = properties.getJSONObject("data").getJSONObject("data");
Assert.assertNotNull("连续指点更新也必须使用 data.data 包装", commandData);
Assert.assertEquals(10.0f, commandData.getFloatValue("max_speed"), 0.001f);
Assert.assertEquals(60.0f, commandData.getJSONArray("points").getJSONObject(0).getFloatValue("height"), 0.001f);
}
@Test
public void returnHomeKeepsFlatEmptyData() throws Exception {
JSONObject properties = buildProperties("return_home", new JSONObject());
Assert.assertEquals("return_home", properties.getString("method"));
JSONObject data = properties.getJSONObject("data");
Assert.assertNotNull(data);
Assert.assertFalse("返航命令不能新增 data.data 包装", data.containsKey("data"));
Assert.assertTrue(data.isEmpty());
}
@Test
public void flyToPointCommandsUseAsyncHeader() throws Exception {
Assert.assertTrue(requiresAsyncHeader("fly_to_point"));
Assert.assertTrue(requiresAsyncHeader("fly_to_point_update"));
Assert.assertTrue(requiresAsyncHeader("fly_to_point_stop"));
Assert.assertFalse(requiresAsyncHeader("return_home"));
}
private JSONObject buildProperties(String commandType, JSONObject params) throws Exception {
DeviceCommand command = DeviceCommand.builder()
.commandId("cmd-test")
.deviceSn("device-test")
.commandType(commandType)
.params(params)
.status(CommandStatus.PENDING)
.build();
DeviceCommandManager manager = new DeviceCommandManager();
Method method = DeviceCommandManager.class.getDeclaredMethod("buildCommandProperties", DeviceCommand.class);
method.setAccessible(true);
return (JSONObject) method.invoke(manager, command);
}
private boolean requiresAsyncHeader(String commandType) throws Exception {
DeviceCommandManager manager = new DeviceCommandManager();
Method method = DeviceCommandManager.class.getDeclaredMethod("requiresAsyncHeader", String.class);
method.setAccessible(true);
return (boolean) method.invoke(manager, commandType);
}
}
@@ -8,6 +8,8 @@ import com.central.order.model.dto.AgeDeviceLocationDTO;
import com.central.order.model.dto.BoatRealtimePositionDTO;
import com.central.order.model.dto.DroneLatestTrackPointDTO;
import com.central.order.mission.VO.TakeoffRequestVO;
import com.central.order.mission.VO.FlyToPointRequestVO;
import com.central.order.mission.VO.FlyToPointUpdateRequestVO;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@@ -39,6 +41,10 @@ public interface DeviceCenterService {
@PostMapping("/device/command/takeoff")
Result<String> takeoff(@RequestBody TakeoffRequestVO request);
@Operation(summary = "无人机返航")
@PostMapping("/device/command/return")
Result<String> returnHome(@RequestParam("deviceSn") String deviceSn);
/**
* 执行航线任务
*
@@ -133,4 +139,25 @@ public interface DeviceCenterService {
@Operation(summary = "获取无人机最新轨迹点")
@GetMapping("/api/device/drone/track/latest/{deviceSn}")
Result<DroneLatestTrackPointDTO> getDroneLatestTrackPoint(@PathVariable("deviceSn") String deviceSn);
/**
* 指点飞行 - 首次飞向目标点
*/
@Operation(summary = "无人机指点飞行 - 飞向目标")
@PostMapping("/device/command/flyToPoint")
Result<String> flyToPoint(@RequestBody FlyToPointRequestVO request);
/**
* 指点飞行 - 更新目标点(连续指点)
*/
@Operation(summary = "无人机指点飞行 - 更新目标点")
@PostMapping("/device/command/flyToPointUpdate")
Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequestVO request);
/**
* 指点飞行 - 停止指点飞行
*/
@Operation(summary = "无人机指点飞行 - 停止")
@PostMapping("/device/command/flyToPointStop")
Result<String> flyToPointStop(@RequestParam("deviceSn") String deviceSn);
}
@@ -7,6 +7,8 @@ import com.central.order.model.dto.AgeDeviceLocationDTO;
import com.central.order.model.dto.BoatRealtimePositionDTO;
import com.central.order.model.dto.DroneLatestTrackPointDTO;
import com.central.order.mission.VO.TakeoffRequestVO;
import com.central.order.mission.VO.FlyToPointRequestVO;
import com.central.order.mission.VO.FlyToPointUpdateRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;
@@ -43,6 +45,12 @@ public class DeviceCenterServiceFallbackFactory implements FallbackFactory<Devic
return Result.failed("设备中心服务调用失败");
}
@Override
public Result<String> returnHome(String deviceSn) {
log.error("调用设备中心returnHome失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
@Override
public Result<String> executeWayline(String deviceSn, String waylineId, String missionCode) {
log.error("调用设备中心executeWayline失败: deviceSn={}, waylineId={}, missionCode={}, error={}",
@@ -98,6 +106,24 @@ public class DeviceCenterServiceFallbackFactory implements FallbackFactory<Devic
log.error("调用设备中心getDroneLatestTrackPoint失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
@Override
public Result<String> flyToPoint(FlyToPointRequestVO request) {
log.error("调用设备中心flyToPoint失败: deviceSn={}, error={}", request.getDeviceSn(), cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
@Override
public Result<String> flyToPointUpdate(FlyToPointUpdateRequestVO request) {
log.error("调用设备中心flyToPointUpdate失败: deviceSn={}, error={}", request.getDeviceSn(), cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
@Override
public Result<String> flyToPointStop(String deviceSn) {
log.error("调用设备中心flyToPointStop失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
};
}
}
@@ -0,0 +1,25 @@
package com.central.order.mission.VO;
import lombok.Data;
/**
* 指点飞行(首次飞向目标)Feign 请求 VO
*
* @author dzc
* @date 2026-01-23
*/
@Data
public class FlyToPointRequestVO {
/** 设备SN */
private String deviceSn;
/** 飞行会话ID(= missionCode) */
private String flyToId;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高 */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
@@ -0,0 +1,24 @@
package com.central.order.mission.VO;
import lombok.Data;
/**
* 指点飞行更新目标(连续指点)Feign 请求 VO
* 注意:设备协议不含 fly_to_id,仅传 max_speed + points
*
* @author dzc
* @date 2026-01-23
*/
@Data
public class FlyToPointUpdateRequestVO {
/** 设备SN */
private String deviceSn;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高 */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
@@ -0,0 +1,30 @@
package com.central.order.mission.command;
import lombok.Builder;
import lombok.Data;
/**
* 指点飞行目标下发参数。
*/
@Data
@Builder
public class FlyToPointTargetCommand {
private Double latitude;
private Double longitude;
private Float height;
private Float maxSpeed;
private String clearanceStatus;
private Float clearanceMeters;
private Float candidateSurfaceHeight;
private boolean riskAcknowledged;
private String riskReason;
private Long riskAcknowledgedUserId;
private String riskAcknowledgedUsername;
public void validateRiskAcknowledgement() {
if (!"VERIFIED".equals(clearanceStatus) && !riskAcknowledged) {
throw new IllegalArgumentException("路径净空未验证,请确认风险后再发送目标");
}
}
}
@@ -0,0 +1,34 @@
package com.central.order.mission.command;
import lombok.Data;
/**
* 指点飞行目标更新接口请求。
*/
@Data
public class FlyToPointUpdateRequest {
private String missionCode;
private Double latitude;
private Double longitude;
private Float height;
private Float maxSpeed;
private String clearanceStatus;
private Float clearanceMeters;
private Float candidateSurfaceHeight;
private Boolean riskAcknowledged;
private String riskReason;
public FlyToPointTargetCommand toCommand() {
return FlyToPointTargetCommand.builder()
.latitude(latitude)
.longitude(longitude)
.height(height)
.maxSpeed(maxSpeed == null ? 12f : maxSpeed)
.clearanceStatus(clearanceStatus == null ? "UNVERIFIED" : clearanceStatus)
.clearanceMeters(clearanceMeters)
.candidateSurfaceHeight(candidateSurfaceHeight)
.riskAcknowledged(Boolean.TRUE.equals(riskAcknowledged))
.riskReason(riskReason)
.build();
}
}
@@ -8,6 +8,8 @@ import com.central.common.model.Result;
import com.central.order.feign.FileCenterService;
import com.central.order.mission.enums.MissionStatus;
import com.central.order.mission.enums.MissionType;
import com.central.order.mission.command.FlyToPointTargetCommand;
import com.central.order.mission.command.FlyToPointUpdateRequest;
import com.central.order.mission.model.Mission;
import com.central.order.mission.model.MissionImage;
import com.central.order.mission.service.IMissionImageService;
@@ -279,6 +281,115 @@ public class MissionController {
}
}
// ==================== 指点飞行编排接口 ====================
/**
* 开始指点飞行
*/
@Operation(summary = "开始指点飞行")
@PostMapping("/startFlyToPoint")
public Result<Map<String, Object>> startFlyToPoint(@RequestBody Map<String, Object> params) {
try {
TenantContextHolder.setTenant("webApp");
String deviceSn = (String) params.get("deviceSn");
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
Double dockLatitude = params.get("dockLatitude") != null ?
Double.parseDouble(params.get("dockLatitude").toString()) : null;
Double dockLongitude = params.get("dockLongitude") != null ?
Double.parseDouble(params.get("dockLongitude").toString()) : null;
Float dockHeight = params.get("dockHeight") != null ?
Float.parseFloat(params.get("dockHeight").toString()) : null;
Boolean isAirborne = params.get("isAirborne") != null ?
(Boolean) params.get("isAirborne") : false;
String missionCode = missionService.startFlyToPoint(deviceSn, dockLatitude, dockLongitude, dockHeight, isAirborne);
Map<String, Object> result = new HashMap<>();
result.put("missionCode", missionCode);
return Result.succeed(result, "指点飞行任务已开始");
} catch (Exception e) {
log.error("开始指点飞行异常", e);
return Result.failed("开始指点飞行失败: " + e.getMessage());
} finally {
TenantContextHolder.clear();
}
}
/**
* 更新指点飞行目标点
*/
@Operation(summary = "更新指点飞行目标点")
@PostMapping("/flyToPointUpdate")
public Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequest request) {
try {
TenantContextHolder.setTenant("webApp");
String missionCode = request.getMissionCode();
if (!StringUtils.hasText(missionCode)) {
return Result.failed("任务编码不能为空");
}
FlyToPointTargetCommand command = request.toCommand();
// 第一版没有服务端路径净空验证能力,不能信任客户端声明“已验证”。
command.setClearanceStatus("UNVERIFIED");
if (command.getLatitude() == null || command.getLongitude() == null || command.getHeight() == null) {
return Result.failed("目标经纬度和高度不能为空");
}
if (command.getLatitude() < -90 || command.getLatitude() > 90
|| command.getLongitude() < -180 || command.getLongitude() > 180) {
return Result.failed("目标经纬度不合法");
}
LoginAppUser user = LoginUserContextHolder.getUser();
if (user == null) {
return Result.failed("用户未登录,无法确认飞行风险");
}
command.setRiskAcknowledgedUserId(user.getId());
command.setRiskAcknowledgedUsername(user.getUsername());
command.validateRiskAcknowledgement();
missionService.flyToPointUpdate(missionCode, command);
return Result.succeed("目标点已更新");
} catch (Exception e) {
log.error("更新指点飞行目标点异常", e);
return Result.failed("更新目标点失败: " + e.getMessage());
} finally {
TenantContextHolder.clear();
}
}
/**
* 结束指点飞行
*/
@Operation(summary = "结束指点飞行")
@PostMapping("/endFlyToPoint")
public Result<String> endFlyToPoint(@RequestBody Map<String, Object> params) {
try {
TenantContextHolder.setTenant("webApp");
String missionCode = (String) params.get("missionCode");
if (!StringUtils.hasText(missionCode)) {
return Result.failed("任务编码不能为空");
}
missionService.endFlyToPoint(missionCode);
return Result.succeed("指点飞行已结束,返航中");
} catch (Exception e) {
log.error("结束指点飞行异常", e);
return Result.failed("结束指点飞行失败: " + e.getMessage());
} finally {
TenantContextHolder.clear();
}
}
/**
* 获取当前登录人的任务及图片列表
*/
@@ -13,7 +13,8 @@ import lombok.Getter;
public enum MissionType implements ZltEnum {
WAYLINE(1, "航线任务"),
TAKEOFF(2, "一键起飞任务"),
BOAT_ROUTE(3, "无人船航线任务");
BOAT_ROUTE(3, "无人船航线任务"),
FLY_TO_POINT(4, "指点飞行任务");
MissionType(Integer id, String content) {
this.id = id;
@@ -58,4 +59,11 @@ public enum MissionType implements ZltEnum {
public static boolean isBoatRouteTask(Integer type) {
return type != null && type.equals(BOAT_ROUTE.getId());
}
/**
* 判断是否为指点飞行任务
*/
public static boolean isFlyToPointTask(Integer type) {
return type != null && type.equals(FLY_TO_POINT.getId());
}
}
@@ -0,0 +1,9 @@
package com.central.order.mission.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.order.mission.model.MissionFlyToPoint;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MissionFlyToPointMapper extends BaseMapper<MissionFlyToPoint> {
}
@@ -34,6 +34,11 @@ public interface MissionMapper extends BaseMapper<Mission> {
*/
Mission getByMissionCode(@Param("missionCode") String missionCode);
/**
* 锁定任务行,串行化同一指点飞行会话的目标更新。
*/
Mission getByMissionCodeForUpdate(@Param("missionCode") String missionCode);
/**
* 更新任务状态
*
@@ -108,4 +108,7 @@ public class Mission extends SuperEntity {
@Schema(description = "任务状态描述")
@TableField(exist = false)
private transient String missionStatusDesc;
@Schema(description = "会话阶段:ACTIVE / RETURNING")
private String phase;
}
@@ -0,0 +1,32 @@
package com.central.order.mission.model;
import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 指点飞行每次下发目标及风险确认审计记录。
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("mission_fly_to_point")
public class MissionFlyToPoint extends SuperEntity {
private String missionCode;
private String flyToId;
private String commandId;
private Integer seq;
private String commandType;
private Double latitude;
private Double longitude;
private Float height;
private Float maxSpeed;
private String status;
private String clearanceStatus;
private Float clearanceMeters;
private Float candidateSurfaceHeight;
private Integer riskAcknowledged;
private String riskReason;
private Long riskAcknowledgedUserId;
private String riskAcknowledgedUsername;
}
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.mission.model.Mission;
import com.central.order.mission.command.FlyToPointTargetCommand;
import java.util.Map;
@@ -96,4 +97,36 @@ public interface IMissionService extends IService<Mission> {
* @return 下发成功返回true
*/
boolean dispatchMissionToDevice(Mission mission);
// ==================== 指点飞行编排接口 ====================
/**
* 开始指点飞行
*
* @param deviceSn 设备SN
* @param dockLatitude 机库纬度
* @param dockLongitude 机库经度
* @param dockHeight 机库高度
* @param isAirborne 是否已升空(前端 SSE 判断)
* @return 任务编码
*/
String startFlyToPoint(String deviceSn, Double dockLatitude, Double dockLongitude, Float dockHeight, boolean isAirborne);
/**
* 更新指点飞行目标点
*
* @param missionCode 任务编码
* @param latitude 目标纬度
* @param longitude 目标经度
* @param height 目标椭球高
* @param maxSpeed 最大速度
*/
void flyToPointUpdate(String missionCode, FlyToPointTargetCommand command);
/**
* 结束指点飞行
*
* @param missionCode 任务编码
*/
void endFlyToPoint(String missionCode);
}
@@ -6,10 +6,14 @@ import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.feign.DeviceCenterService;
import com.central.order.mission.VO.TakeoffRequestVO;
import com.central.order.mission.VO.FlyToPointRequestVO;
import com.central.order.mission.command.FlyToPointTargetCommand;
import com.central.order.mission.enums.MissionStatus;
import com.central.order.mission.enums.MissionType;
import com.central.order.mission.mapper.MissionMapper;
import com.central.order.mission.mapper.MissionFlyToPointMapper;
import com.central.order.mission.model.Mission;
import com.central.order.mission.model.MissionFlyToPoint;
import com.central.order.mission.service.IMissionService;
import com.central.order.weather.model.WeatherCheckResult;
import com.central.order.weather.service.IWeatherRuleValidator;
@@ -38,6 +42,9 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
@Resource
DeviceCenterService deviceCenterService;
@Resource
MissionFlyToPointMapper missionFlyToPointMapper;
@Autowired
private IWeatherRuleValidator weatherRuleValidator;
@@ -249,6 +256,13 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
@Override
public boolean dispatchMissionToDevice(Mission mission) {
return dispatchMissionToDevice(mission, false);
}
/**
* 下发任务到设备(带升空状态)
*/
public boolean dispatchMissionToDevice(Mission mission, boolean isAirborne) {
try {
Integer missionType = mission.getMissionType();
@@ -311,6 +325,33 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
log.error("无人船航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg);
return false;
}
} else if (MissionType.isFlyToPointTask(missionType)) {
// 指点飞行任务:前端 SSE 判断是否已升空
log.info("下发指点飞行任务到设备: missionCode={}, deviceSn={}, isAirborne={}",
mission.getMissionCode(), mission.getDeviceSn(), isAirborne);
if (!isAirborne) {
// 未升空 → 先起飞
TakeoffRequestVO takeoffRequestVO = new TakeoffRequestVO();
takeoffRequestVO.setTargetHeight(mission.getTargetHeight() != null ? mission.getTargetHeight().floatValue() : 20f);
takeoffRequestVO.setDeviceSn(mission.getDeviceSn());
takeoffRequestVO.setFlightId(mission.getMissionCode());
takeoffRequestVO.setTargetLatitude(mission.getTargetLatitude() != null ? mission.getTargetLatitude().doubleValue() : 0d);
takeoffRequestVO.setTargetLongitude(mission.getTargetLongitude() != null ? mission.getTargetLongitude().doubleValue() : 0d);
Result<String> takeoffResult = deviceCenterService.takeoff(takeoffRequestVO);
if (takeoffResult == null || takeoffResult.getResp_code() != 0) {
log.error("指点飞行起飞命令失败: missionCode={}", mission.getMissionCode());
return false;
}
log.info("指点飞行起飞命令已发送: missionCode={}", mission.getMissionCode());
} else {
log.info("无人机已升空,跳过起飞步骤: missionCode={}", mission.getMissionCode());
}
// 命令入队成功 → 任务状态为 DOING
updateMissionStatus(mission.getMissionCode(), MissionStatus.DOING.getId());
return true;
} else {
log.error("未知的任务类型: {}", missionType);
return false;
@@ -321,4 +362,188 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
return false;
}
}
// ==================== 指点飞行编排方法 ====================
@Override
@Transactional(rollbackFor = Exception.class)
public String startFlyToPoint(String deviceSn, Double dockLatitude, Double dockLongitude, Float dockHeight, boolean isAirborne) {
log.info("开始指点飞行: deviceSn={}, dock=({}, {}, {})", deviceSn, dockLatitude, dockLongitude, dockHeight);
// 1. 创建 FLY_TO_POINT 任务
Mission mission = new Mission();
mission.setDeviceSn(deviceSn);
mission.setMissionType(MissionType.FLY_TO_POINT.getId());
mission.setMissionName("指点飞行任务");
mission.setMissionStatus(MissionStatus.PENDING.getId());
mission.setTargetLatitude(dockLatitude != null ? java.math.BigDecimal.valueOf(dockLatitude) : null);
mission.setTargetLongitude(dockLongitude != null ? java.math.BigDecimal.valueOf(dockLongitude) : null);
mission.setTargetHeight(java.math.BigDecimal.valueOf(20));
mission.setPhase("ACTIVE");
String missionCode = generateMissionCode();
mission.setMissionCode(missionCode);
save(mission);
log.info("指点飞行任务已创建: missionCode={}", missionCode);
// 2. 执行任务(dispatchMissionToDevice 会处理起飞逻辑)
boolean dispatched = dispatchMissionToDevice(mission, isAirborne);
if (!dispatched) {
log.error("指点飞行任务下发失败: missionCode={}", missionCode);
throw new RuntimeException("任务下发失败");
}
return missionCode;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void flyToPointUpdate(String missionCode, FlyToPointTargetCommand command) {
command.validateRiskAcknowledgement();
Double latitude = command.getLatitude();
Double longitude = command.getLongitude();
Float height = command.getHeight();
Float maxSpeed = command.getMaxSpeed();
log.info("更新指点飞行目标: missionCode={}, target=({}, {}, {})", missionCode, latitude, longitude, height);
Mission mission = baseMapper.getByMissionCodeForUpdate(missionCode);
if (mission == null) {
throw new RuntimeException("任务不存在: " + missionCode);
}
// 校验状态
if (!MissionStatus.DOING.getId().equals(mission.getMissionStatus())) {
throw new RuntimeException("任务状态不允许更新目标: " + mission.getMissionStatus());
}
if (!"ACTIVE".equals(mission.getPhase())) {
throw new RuntimeException("飞行已结束,无法更新目标");
}
String deviceSn = mission.getDeviceSn();
// 判断是否首次指点:查询 mission_fly_to_point 子表
boolean isFirstTarget = !hasSentFirstFlyToPoint(missionCode);
Result<String> result;
String commandType;
if (isFirstTarget) {
FlyToPointRequestVO requestVO = new FlyToPointRequestVO();
requestVO.setDeviceSn(deviceSn);
requestVO.setFlyToId(missionCode);
requestVO.setLatitude(latitude);
requestVO.setLongitude(longitude);
requestVO.setHeight(height);
requestVO.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
result = deviceCenterService.flyToPoint(requestVO);
if (result == null || result.getResp_code() != 0) {
throw new RuntimeException("指点飞行命令失败: " + (result != null ? result.getResp_msg() : "无响应"));
}
commandType = "fly_to_point";
log.info("首次指点飞行命令已发送: missionCode={}, commandId={}", missionCode, result.getData());
} else {
// 设备端不支持 fly_to_point_update,连续改飞复用 fly_to_point 并沿用同一会话标识。
FlyToPointRequestVO requestVO = new FlyToPointRequestVO();
requestVO.setDeviceSn(deviceSn);
requestVO.setFlyToId(missionCode);
requestVO.setLatitude(latitude);
requestVO.setLongitude(longitude);
requestVO.setHeight(height);
requestVO.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
result = deviceCenterService.flyToPoint(requestVO);
if (result == null || result.getResp_code() != 0) {
throw new RuntimeException("目标更新命令失败: " + (result != null ? result.getResp_msg() : "无响应"));
}
commandType = "fly_to_point";
log.info("目标更新命令已发送: missionCode={}, commandId={}", missionCode, result.getData());
}
MissionFlyToPoint record = new MissionFlyToPoint();
record.setMissionCode(missionCode);
record.setFlyToId(missionCode);
record.setCommandId(result.getData());
record.setSeq(nextTargetSequence(missionCode));
record.setCommandType(commandType);
record.setLatitude(latitude);
record.setLongitude(longitude);
record.setHeight(height);
record.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
record.setStatus("SENT");
record.setClearanceStatus(command.getClearanceStatus());
record.setClearanceMeters(command.getClearanceMeters());
record.setCandidateSurfaceHeight(command.getCandidateSurfaceHeight());
record.setRiskAcknowledged(command.isRiskAcknowledged() ? 1 : 0);
record.setRiskReason(command.getRiskReason());
record.setRiskAcknowledgedUserId(command.getRiskAcknowledgedUserId());
record.setRiskAcknowledgedUsername(command.getRiskAcknowledgedUsername());
missionFlyToPointMapper.insert(record);
mission.setTargetLatitude(java.math.BigDecimal.valueOf(latitude));
mission.setTargetLongitude(java.math.BigDecimal.valueOf(longitude));
mission.setTargetHeight(java.math.BigDecimal.valueOf(height));
updateById(mission);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void endFlyToPoint(String missionCode) {
log.info("结束指点飞行: missionCode={}", missionCode);
Mission mission = baseMapper.getByMissionCodeForUpdate(missionCode);
if (mission == null) {
throw new RuntimeException("任务不存在: " + missionCode);
}
// 校验状态
if (!MissionStatus.DOING.getId().equals(mission.getMissionStatus())) {
throw new RuntimeException("任务状态不允许结束: " + mission.getMissionStatus());
}
if (!"ACTIVE".equals(mission.getPhase())) {
log.warn("任务已处于返航状态,忽略重复结束请求: missionCode={}", missionCode);
return;
}
String deviceSn = mission.getDeviceSn();
// 1. 原子更新 phase = RETURNING(防止并发更新目标)
mission.setPhase("RETURNING");
updateById(mission);
// 2. 设备端不支持 fly_to_point_stop,直接发送一键返航命令。
Result<String> returnResult = deviceCenterService.returnHome(deviceSn);
// 返航命令失败不会阻塞流程(phase 保持 RETURNING)
if (returnResult == null || returnResult.getResp_code() != 0) {
log.error("返航命令失败,任务保持 RETURNING: missionCode={}", missionCode);
throw new RuntimeException("返航命令失败,任务未结束: " + (returnResult != null ? returnResult.getResp_msg() : "无响应"));
}
log.info("指点飞行结束流程完成,等待降落: missionCode={}", missionCode);
}
/**
* 判断是否已发送过首次 fly_to_point 指令
*/
private boolean hasSentFirstFlyToPoint(String missionCode) {
return missionFlyToPointMapper.selectCount(
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MissionFlyToPoint>()
.eq(MissionFlyToPoint::getMissionCode, missionCode)
.eq(MissionFlyToPoint::getCommandType, "fly_to_point")) > 0;
}
private int nextTargetSequence(String missionCode) {
Long count = missionFlyToPointMapper.selectCount(
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MissionFlyToPoint>()
.eq(MissionFlyToPoint::getMissionCode, missionCode));
return count.intValue() + 1;
}
/**
* 生成任务编码
*/
private String generateMissionCode() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return "FP" + sdf.format(new Date());
}
}
@@ -0,0 +1,12 @@
-- 指点飞行安全审计字段;适用于已执行初始迁移的数据库。
ALTER TABLE mission_fly_to_point
ADD COLUMN clearance_status VARCHAR(20) NOT NULL DEFAULT 'UNVERIFIED' COMMENT '净空状态:VERIFIED / UNVERIFIED',
ADD COLUMN clearance_meters FLOAT DEFAULT NULL COMMENT '计算得到的最小净空(米)',
ADD COLUMN candidate_surface_height FLOAT DEFAULT NULL COMMENT '点击命中的模型或地形表面椭球高,仅审计使用',
ADD COLUMN risk_acknowledged TINYINT NOT NULL DEFAULT 0 COMMENT '是否已确认未验证净空风险',
ADD COLUMN risk_reason VARCHAR(512) DEFAULT NULL COMMENT '风险原因',
ADD COLUMN risk_acknowledged_user_id BIGINT DEFAULT NULL COMMENT '确认风险的账户ID',
ADD COLUMN risk_acknowledged_username VARCHAR(64) DEFAULT NULL COMMENT '确认风险的账户名';
ALTER TABLE mission_fly_to_point
ADD UNIQUE KEY uk_mission_fly_to_point_seq (mission_code, seq);
@@ -0,0 +1,25 @@
-- =====================================================
-- 指点飞行功能 - 数据库迁移脚本
-- =====================================================
-- 1. missions 表新增 phase 字段
ALTER TABLE missions ADD COLUMN phase VARCHAR(20) DEFAULT 'ACTIVE' COMMENT '会话阶段:ACTIVE / RETURNING';
-- 2. 创建 mission_fly_to_point 子表(记录每次目标更新)
CREATE TABLE IF NOT EXISTS mission_fly_to_point (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
mission_code VARCHAR(64) NOT NULL COMMENT '关联任务编码',
fly_to_id VARCHAR(64) NOT NULL COMMENT '飞行会话ID(= missionCode)',
command_id VARCHAR(64) DEFAULT NULL COMMENT '设备命令ID',
seq INT DEFAULT 1 COMMENT '目标序号(1, 2, 3...)',
command_type VARCHAR(32) NOT NULL COMMENT '指令类型:fly_to_point / fly_to_point_update',
latitude DOUBLE COMMENT '目标纬度',
longitude DOUBLE COMMENT '目标经度',
height FLOAT COMMENT '目标椭球高',
max_speed FLOAT DEFAULT 12 COMMENT '最大速度',
status VARCHAR(20) DEFAULT 'SENT' COMMENT '状态:SENT / REACHED / FAILED',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_mission_code (mission_code),
INDEX idx_fly_to_id (fly_to_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='指点飞行目标点记录表';
@@ -28,6 +28,7 @@
<result column="is_del" property="isDel"/>
<result column="create_time" property="createTime"/>
<result column="update_time" property="updateTime"/>
<result column="phase" property="phase"/>
<!-- 临时字段 -->
<result column="tourism_name" property="tourismName"/>
<result column="image_count" property="imageCount"/>
@@ -40,7 +41,7 @@
m.workspace_id, m.tourism_id, m.mission_status,
m.target_latitude, m.target_longitude, m.target_height,
m.start_time, m.end_time, m.creator_id, m.creator_name, m.remark,
m.tenant_id, m.is_del, m.create_time, m.update_time
m.tenant_id, m.is_del, m.create_time, m.update_time, m.phase
</sql>
<!-- 分页查询任务列表 -->
@@ -99,6 +100,15 @@
AND m.is_del = 0
</select>
<select id="getByMissionCodeForUpdate" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM missions m
WHERE m.mission_code = #{missionCode}
AND m.is_del = 0
FOR UPDATE
</select>
<!-- 更新任务状态 -->
<update id="updateMissionStatus">
UPDATE missions
@@ -0,0 +1,29 @@
package com.central.order.mission.command;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FlyToPointTargetCommandTest {
@Test
void 未验证路径且未确认风险时拒绝发送() {
FlyToPointTargetCommand command = FlyToPointTargetCommand.builder()
.clearanceStatus("UNVERIFIED")
.riskAcknowledged(false)
.build();
assertThrows(IllegalArgumentException.class, command::validateRiskAcknowledgement);
}
@Test
void 已验证路径无需风险确认即可发送() {
FlyToPointTargetCommand command = FlyToPointTargetCommand.builder()
.clearanceStatus("VERIFIED")
.riskAcknowledged(false)
.build();
assertDoesNotThrow(command::validateRiskAcknowledgement);
}
}