Feature dzc #1
@@ -12,6 +12,7 @@ nacos/
|
||||
.claude/team-collaboration-matrix.md
|
||||
|
||||
.reasonix
|
||||
reasonix.toml
|
||||
|
||||
# Cesium static assets (auto-generated by npm install)
|
||||
zlt-web/react-web-next/public/cesium/
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<h2>哪种指点飞行操作流更顺手?</h2>
|
||||
<p class="subtitle">重点比较:从开始飞行到连续改点,需要多少次中断和确认。</p>
|
||||
|
||||
<div class="cards" style="grid-template-columns: repeat(3, minmax(0, 1fr));">
|
||||
<div class="card" data-choice="a" onclick="toggleSelect(this)">
|
||||
<div class="card-image" style="padding:16px;background:#122033;min-height:280px;color:#d9e8f5;">
|
||||
<div style="font-size:12px;color:#7f9bb5;margin-bottom:10px;">现有流程</div>
|
||||
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">右侧面板<br><b>指点飞行</b></div>
|
||||
<div style="text-align:center;color:#65b8ff;">↓ 确认开始</div>
|
||||
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">等待升空</div>
|
||||
<div style="text-align:center;color:#65b8ff;">↓ 点击地图</div>
|
||||
<div style="background:#f5f7fb;color:#14253b;padding:12px;border-radius:4px;margin:8px 0;">目标确认弹窗<br><small>高度、速度、确认</small></div>
|
||||
<div style="text-align:center;color:#65b8ff;">↓ 到达后才能再选点</div>
|
||||
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">重复上述步骤</div>
|
||||
</div>
|
||||
<div class="card-body"><h3>A. 分步确认</h3><p>控制感强,但连续指点时被弹窗和状态等待反复打断。</p></div>
|
||||
</div>
|
||||
|
||||
<div class="card" data-choice="b" onclick="toggleSelect(this)" style="border-color:#1f8fff;">
|
||||
<div class="card-image" style="padding:16px;background:#10273a;min-height:280px;color:#d9e8f5;position:relative;">
|
||||
<div style="font-size:12px;color:#7fcaef;margin-bottom:10px;">推荐:地图优先</div>
|
||||
<div style="height:140px;border:1px solid #39769b;background:linear-gradient(135deg,#173c55,#1d5870);position:relative;border-radius:3px;">
|
||||
<div style="position:absolute;left:42%;top:38%;font-size:32px;color:#ffcf5c;">✦</div>
|
||||
<div style="position:absolute;right:10px;top:8px;background:#0b1925cc;padding:6px 8px;font-size:12px;">正在指点 · 5 m/s</div>
|
||||
<div style="position:absolute;left:15%;bottom:15%;color:#7ad5ff;font-size:22px;">✈</div>
|
||||
</div>
|
||||
<div style="margin-top:10px;background:#0b1925;padding:10px;border-left:3px solid #1f9fff;display:flex;justify-content:space-between;align-items:center;">
|
||||
<span><b>新目标</b><br><small>113.123456, 23.123456</small></span>
|
||||
<span style="color:#ffcf5c;">发送</span>
|
||||
</div>
|
||||
<div style="font-size:12px;color:#9bb8c9;margin-top:10px;line-height:1.5;">首次进入模式后,地图点击直接更新目标。高度和速度沿用上次值,可在紧凑工具条修改;短暂显示“撤销”而不是每次弹窗。</div>
|
||||
</div>
|
||||
<div class="card-body"><h3>B. 地图优先</h3><p>一次启用,连续点击连续改点。危险操作才二次确认,常规改点不打断地图。</p></div>
|
||||
</div>
|
||||
|
||||
<div class="card" data-choice="c" onclick="toggleSelect(this)">
|
||||
<div class="card-image" style="padding:16px;background:#17242b;min-height:280px;color:#d9e8f5;">
|
||||
<div style="font-size:12px;color:#a9c4b8;margin-bottom:10px;">精细作业模式</div>
|
||||
<div style="height:92px;border:1px solid #607d70;background:#283b35;border-radius:3px;position:relative;">
|
||||
<span style="position:absolute;left:25%;top:22%;font-size:22px;color:#f2d477;">①</span>
|
||||
<span style="position:absolute;left:58%;top:50%;font-size:22px;color:#f2d477;">②</span>
|
||||
<span style="position:absolute;left:12%;bottom:10%;color:#79c9ee;">✈</span>
|
||||
</div>
|
||||
<div style="margin-top:10px;background:#24332e;padding:10px;border-radius:3px;">
|
||||
<b>下一目标</b><span style="float:right;color:#f2d477;">②</span><br>
|
||||
<small>113.123456, 23.123456 · 120m</small>
|
||||
</div>
|
||||
<div style="display:flex;gap:6px;margin-top:8px;"><span style="background:#31463e;padding:5px 7px;font-size:12px;">添加目标</span><span style="background:#31463e;padding:5px 7px;font-size:12px;">确认发送</span></div>
|
||||
<div style="font-size:12px;color:#a9c4b8;margin-top:10px;line-height:1.5;">地图点击先加入临时队列,用户可以复核、排序或删除后发送。</div>
|
||||
</div>
|
||||
<div class="card-body"><h3>C. 目标队列</h3><p>适合测绘和有规划的巡查,但增加了一层操作,与即时指点的感觉相反。</p></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section" style="margin-top:24px;">
|
||||
<p class="label">选择建议</p>
|
||||
<p>我建议选 <b>B</b>:首次启用和结束返航保留明确确认;飞行期间把地图点击变成主操作,避免“点一下、弹一次、等一次”。</p>
|
||||
</div>
|
||||
@@ -0,0 +1,38 @@
|
||||
<h2>点击建筑时,目标高度应该怎么计算?</h2>
|
||||
<p class="subtitle">现有代码把“模型命中高度 + 输入高度”直接下发;它不等于界面所说的“相对地面高度”。</p>
|
||||
|
||||
<div class="split">
|
||||
<div class="mockup" data-choice="surface" onclick="toggleSelect(this)">
|
||||
<div class="mockup-header">现有:相对点击表面</div>
|
||||
<div class="mockup-body" style="background:#132633;min-height:300px;position:relative;overflow:hidden;color:#e9f5fa;">
|
||||
<div style="position:absolute;left:12%;bottom:8%;width:78%;height:3px;background:#5e856a;"></div>
|
||||
<div style="position:absolute;left:52%;bottom:9%;width:22%;height:44%;background:#73808b;border:2px solid #aebac0;"><span style="position:absolute;top:8px;left:12px;font-size:12px;">楼</span></div>
|
||||
<div style="position:absolute;left:22%;bottom:12%;font-size:28px;">✈</div>
|
||||
<div style="position:absolute;left:63%;bottom:59%;font-size:26px;color:#ffca60;">✦</div>
|
||||
<div style="position:absolute;left:58%;bottom:72%;border-top:1px dashed #ffca60;width:10%;"></div>
|
||||
<div style="position:absolute;right:8%;top:9%;font-size:12px;background:#202f3b;padding:8px;line-height:1.5;">模型表面 40m<br>输入“120m”<br><b style="color:#ffca60;">目标 = 160m</b></div>
|
||||
<div style="position:absolute;left:7%;top:8%;font-size:12px;color:#ff9c9c;">问题:界面称“相对地面”,实际相对楼顶/立面;路径中的更高障碍也没有检查。</div>
|
||||
</div>
|
||||
<div style="padding:12px;"><b>方案 A:保留现状</b><br><small>实现最少,但语义误导,无法保证航线净空。</small></div>
|
||||
</div>
|
||||
|
||||
<div class="mockup" data-choice="safe-corridor" onclick="toggleSelect(this)" style="border-color:#1f8fff;">
|
||||
<div class="mockup-header">推荐:安全航高 + 净空保护</div>
|
||||
<div class="mockup-body" style="background:#132633;min-height:300px;position:relative;overflow:hidden;color:#e9f5fa;">
|
||||
<div style="position:absolute;left:12%;bottom:8%;width:78%;height:3px;background:#5e856a;"></div>
|
||||
<div style="position:absolute;left:52%;bottom:9%;width:22%;height:44%;background:#73808b;border:2px solid #aebac0;"><span style="position:absolute;top:8px;left:12px;font-size:12px;">楼</span></div>
|
||||
<div style="position:absolute;left:22%;bottom:12%;font-size:28px;">✈</div>
|
||||
<div style="position:absolute;left:63%;bottom:77%;font-size:26px;color:#75e5ff;">✦</div>
|
||||
<div style="position:absolute;left:26%;bottom:80%;width:42%;border-top:3px solid #4fc3f7;"></div>
|
||||
<div style="position:absolute;left:25%;bottom:74%;font-size:12px;color:#75e5ff;">安全飞行走廊:障碍物顶部 + 安全净空</div>
|
||||
<div style="position:absolute;right:7%;top:8%;font-size:12px;background:#163c4d;padding:8px;line-height:1.5;">地图点击只取经纬度<br>计划高度 = max:<br>· 当前安全航高<br>· 目标建筑顶部 + 净空<br>· 路径障碍顶部 + 净空</div>
|
||||
<div style="position:absolute;left:7%;top:8%;font-size:12px;color:#b8e8c5;">高度策略明确;无法可靠评估净空时,拒绝下发而不是猜测。</div>
|
||||
</div>
|
||||
<div style="padding:12px;"><b>方案 B:安全走廊(推荐)</b><br><small>点击只决定水平位置;系统决定或校验实际椭球目标高。</small></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section" style="margin-top:22px;">
|
||||
<p class="label">建议交互</p>
|
||||
<p>把“飞行高度”改成“安全航高(相对起飞点)”,默认继承当前安全高度。点击楼顶时显示“目标位于建筑上方,系统已抬升至安全高度”;若无法验证模型/地形净空,则显示风险并禁止确认飞行。</p>
|
||||
</div>
|
||||
@@ -0,0 +1,3 @@
|
||||
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
|
||||
<p class="subtitle">继续在终端确认安全策略...</p>
|
||||
</div>
|
||||
@@ -0,0 +1,3 @@
|
||||
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
|
||||
<p class="subtitle">正在整理“预览后发送 + 安全航高”的交互方案...</p>
|
||||
</div>
|
||||
@@ -0,0 +1 @@
|
||||
{"reason":"idle timeout","timestamp":1784875445807}
|
||||
@@ -0,0 +1 @@
|
||||
628
|
||||
@@ -0,0 +1,28 @@
|
||||
# 指点飞行交互与安全实现计划
|
||||
|
||||
## 目标
|
||||
|
||||
将指点飞行改为“点击产生候选点,明确发送后才改飞”的交互;防止把建筑或模型表面的命中高度直接作为飞行目标高度;记录每一次下发及风险确认。
|
||||
|
||||
## 第一版边界
|
||||
|
||||
- 点击模型表面仅作为目标位置与障碍物候选高度。
|
||||
- 目标椭球高度取当前无人机椭球高度与候选表面高度加净空的较大值。
|
||||
- 第一版不宣称已完成路径三维净空验证;路径未验证时必须由当前账户确认风险后才可发送。
|
||||
- 后端保存首次 `fly_to_point` 与后续 `fly_to_point_update` 的下发记录和风险审计信息。
|
||||
|
||||
## 实施步骤
|
||||
|
||||
1. 先为后端安全命令对象编写单元测试,覆盖“未验证净空必须确认风险”与“已验证净空不要求确认”两种行为。
|
||||
2. 新增安全命令对象、目标下发请求对象和 `mission_fly_to_point` 实体/Mapper;迁移脚本补充审计字段与唯一序号约束。
|
||||
3. 将任务更新接口改为强类型请求,后端从登录上下文取得确认人;对未验证风险但未确认的请求拒绝下发。
|
||||
4. 调整任务服务:根据目标历史决定首次命令或更新命令,设备命令成功后记录历史与最新任务目标;结束时先停止指点会话,再调用真实返航接口。
|
||||
5. 前端 Hook 分离候选目标和已发送目标;候选目标不会改变当前飞行目标,发送成功后才成为已发送目标。
|
||||
6. 前端 Cesium 点选在起飞、等待和飞行中均可用,候选点与已发送点使用不同标识;点选高度只用于净空计算和风险提示。
|
||||
7. 用紧凑浮层替代每次点选的大弹窗,提供发送、丢弃和风险确认;保留起飞、结束飞行的明确确认。
|
||||
|
||||
## 验证
|
||||
|
||||
- 后端:`mvn -pl zlt-business/order-center -am -Dtest=FlyToPointTargetCommandTest -Dsurefire.failIfNoSpecifiedTests=false test`
|
||||
- 前端:`npm run tsc`,随后执行 `npm run build`。
|
||||
- 人工:起飞后点 A 仅预览;发送 A 后飞行;飞往 A 时点 B 仅预览;发送 B 后才改飞;未勾选风险确认不可发送。
|
||||
+170
@@ -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;
|
||||
|
||||
+1
-1
@@ -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"),
|
||||
|
||||
+15
@@ -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" +
|
||||
"}";
|
||||
|
||||
|
||||
}
|
||||
|
||||
+167
-3
@@ -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 指令集完整参数字典
|
||||
+92
@@ -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);
|
||||
}
|
||||
}
|
||||
+27
@@ -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);
|
||||
}
|
||||
|
||||
+26
@@ -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("设备中心服务调用失败");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+25
@@ -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;
|
||||
}
|
||||
+24
@@ -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;
|
||||
}
|
||||
+30
@@ -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("路径净空未验证,请确认风险后再发送目标");
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -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();
|
||||
}
|
||||
}
|
||||
+111
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录人的任务及图片列表
|
||||
*/
|
||||
|
||||
+9
-1
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -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> {
|
||||
}
|
||||
+5
@@ -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;
|
||||
}
|
||||
|
||||
+32
@@ -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;
|
||||
}
|
||||
+33
@@ -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);
|
||||
}
|
||||
|
||||
+225
@@ -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
|
||||
|
||||
+29
@@ -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);
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -93,10 +93,9 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
});
|
||||
|
||||
try {
|
||||
// 处理跨域问题:非 localhost 访问时将 CDN URL 转换为代理路径
|
||||
// 处理跨域问题:将 CDN URL 转换为代理路径(始终使用代理,避免 CORS)
|
||||
let tilesetUrl = config.url;
|
||||
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
|
||||
if (!isLocalhost && tilesetUrl.includes('minicdn.goflytec.com')) {
|
||||
if (tilesetUrl.includes('minicdn.goflytec.com')) {
|
||||
tilesetUrl = tilesetUrl.replace('https://minicdn.goflytec.com', '');
|
||||
console.log('[Tileset] 使用代理路径:', tilesetUrl);
|
||||
}
|
||||
@@ -127,7 +126,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
foveatedMinimumScreenSpaceErrorRelaxation: 0.0,
|
||||
|
||||
// 裁剪优化 - 减少移动时的清晰度降低
|
||||
cullWithChildrenBounds: true,
|
||||
cullWithChildrenBounds: false, // 外部 tileset 引用的模型必须关闭,否则子 tileset 会被错误裁剪
|
||||
cullRequestsWhileMoving: false, // 禁用移动时的请求裁剪
|
||||
cullRequestsWhileMovingMultiplier: 1.0,
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# 指点飞行交互优化方案
|
||||
|
||||
## 目标
|
||||
|
||||
降低连续指点飞行的操作中断,同时避免将建筑模型表面直接作为不安全的飞行目标高度。
|
||||
|
||||
## 交互规则
|
||||
|
||||
1. 进入指点模式后,无人机起飞中、等待目标和飞往当前目标时均可在地图上选择候选目标。
|
||||
2. 地图点击只生成候选目标,不立即下发飞行指令,也不改变当前飞行目标。
|
||||
3. 地图展示候选目标标记和从无人机到候选目标的蓝色虚线;当前已下发目标保留独立标识。
|
||||
4. 地图浮层显示候选目标经纬度、安全航高和最大速度,提供“发送改飞”和“丢弃”操作。
|
||||
5. 只有用户点击“发送改飞”才下发首次 `fly_to_point` 或后续 `fly_to_point_update`。
|
||||
6. 起飞、结束指点飞行和返航保持明确确认流程。
|
||||
|
||||
## 高度和风险规则
|
||||
|
||||
1. 点击位置只用于取得经纬度与候选位置高程,不将模型表面高度直接作为飞行目标。
|
||||
2. 系统计算最终椭球高时采用当前安全航高、目标障碍物高程加安全净空、路径障碍物高程加安全净空三者的最大值。
|
||||
3. 净空可信时允许直接发送;无法验证净空时,展示风险原因、最终目标高度和风险确认操作。
|
||||
4. 当前登录账户可确认风险后继续下发;后端记录确认人、确认时间、风险原因和最终目标参数。
|
||||
5. 风险确认仅允许本次候选目标下发使用,重新选择候选目标后必须重新评估。
|
||||
|
||||
## 状态约束
|
||||
|
||||
- `TAKING_OFF`、`WAITING_TARGET`、`FLYING_TO` 均允许选择候选目标。
|
||||
- `RETURNING`、`COMPLETED`、`IDLE` 禁止选择和发送候选目标。
|
||||
- 选择候选目标不改变当前飞行状态;发送成功后状态进入或保持 `FLYING_TO`。
|
||||
- 候选目标被丢弃、发送失败或风险确认取消后,当前目标和当前飞行状态保持不变。
|
||||
|
||||
## 实施范围
|
||||
|
||||
- 前端:重构 `useFlyToPoint` 的候选目标与已发送目标状态,修改 Cesium 点击处理和 `FlyToPointPanel` 浮层。
|
||||
- 后端:扩展指点目标更新接口,接收风险确认审计字段;保存本次下发的安全计算结果与风险确认记录。
|
||||
- 测试:覆盖允许选点状态、预览不下发、明确发送才下发、风险确认与拒绝路径。
|
||||
@@ -0,0 +1,440 @@
|
||||
# 指点飞行实现方案
|
||||
|
||||
## 一、功能概述
|
||||
|
||||
用户在 Cesium 3D 地球上点击目标位置,无人机自动飞往该位置。支持一次飞行会话内连续点击多个目标点,所有照片和轨迹归属于同一个任务。
|
||||
|
||||
**核心设计思想:**
|
||||
|
||||
> 订单中心是飞行会话的唯一编排者,前端只负责展示和发起请求。
|
||||
> 一次飞行会话 = 一个 `FLY_TO_POINT` 任务;
|
||||
|
||||
```
|
||||
┌─ 订单中心(编排层)──────────────────────────────────────┐
|
||||
│ │
|
||||
│ 开始指点 → 起飞 → 等待目标 ←→ 更新目标 → 到达 │
|
||||
│ ↕ ↕ │
|
||||
│ 手动拍照 连续指点 │
|
||||
│ ↓ ↓ │
|
||||
│ fly_to_id 关联 fly_to_point_update │
|
||||
│ │
|
||||
│ 结束指点 → fly_to_point_stop → 返航 → 落地 → 任务完成 │
|
||||
└──────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、协议链路
|
||||
|
||||
### 2.1 已定义的协议模板(`ControlMessageConstant.java`)
|
||||
|
||||
| 模板常量 | method | 用途 |
|
||||
|---------|--------|------|
|
||||
| `FLY_TO_ID` | `fly_to_point` | 首次飞向目标,生成 `fly_to_id` |
|
||||
| `FLY_TO_POINT_UPDATE` | `fly_to_point_update` | 更新同一 `fly_to_id` 的目标点(打断当前飞行,立即转向新目标) |
|
||||
| `FLY_TO_ID_STOP` | `fly_to_point_stop` | 停止指点飞行 |
|
||||
|
||||
### 2.2 连续指点协议链路
|
||||
|
||||
```
|
||||
首次选点 → fly_to_point (data.fly_to_id = missionCode, 生成设备端飞行会话)
|
||||
后续选点 → fly_to_point_update (仅传 max_speed + points, 设备协议无 fly_to_id 字段)
|
||||
结束飞行 → fly_to_point_stop (停止指点飞行会话)
|
||||
→ return_home (返航)
|
||||
```
|
||||
|
||||
### 2.3 照片关联链路
|
||||
|
||||
```
|
||||
起飞指令 takeoff_to_point → flight_id = missionCode
|
||||
fly_to_point → fly_to_id = missionCode
|
||||
设备拍照 → 照片回传时携带 flight_id / fly_to_id
|
||||
机库回传服务 → 从回传报文中取出 missionCode
|
||||
→ 调用 POST /mission/image/saveMissionImage { missionCode, filePath }
|
||||
→ 照片关联到对应任务
|
||||
```
|
||||
|
||||
**前端不传 missionCode 给拍照接口,拍照指令 `camera_photo_take` 仅需 `deviceSn`;照片关联由机库回传服务完成。**
|
||||
|
||||
### 2.4 待修 BUG
|
||||
|
||||
`ControlEnum.java` 第13行:
|
||||
|
||||
```java
|
||||
// 当前(错误)
|
||||
FLY_TO_POINT_UPDATE("fly_to_point_stop"),
|
||||
// 应为
|
||||
FLY_TO_POINT_UPDATE("fly_to_point_update"),
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、高度基准定义
|
||||
|
||||
| 数据来源 | 坐标系 | 用途 |
|
||||
|---------|--------|------|
|
||||
| SSE `height` | 相对起飞点高度 | 起飞完成判断、降落判断 |
|
||||
| Cesium `Cartographic.height` | WGS84 椭球高 | 前端从点击位置取得,用于计算目标椭球高 |
|
||||
| 用户设定飞行高度 | 相对地面高度(m) | 由用户在地图确认框中输入 |
|
||||
| `fly_to_point.points[].height` | WGS84 椭球高 | 前端计算:椭球高 + 用户飞行高度 |
|
||||
|
||||
**规则:**
|
||||
- **起飞完成:** 使用 SSE 相对高度 > 安全阈值
|
||||
- **目标高度:** 前端从 Cesium 获取 `Cartographic.height`(点击点椭球高),加上用户输入的飞行高度(m),计算出目标椭球高提交后端
|
||||
- **到达判定:** 使用水平大地距离,默认阈值 5m,不受高度差影响
|
||||
|
||||
---
|
||||
|
||||
## 四、后端改动
|
||||
|
||||
### 4.1 文件清单
|
||||
|
||||
| # | 文件 | 改动 | 说明 |
|
||||
|---|------|------|------|
|
||||
| 1 | `order-center/.../enums/MissionType.java` | 修改 | 新增 `FLY_TO_POINT(4)` |
|
||||
| 2 | `order-center/.../feign/DeviceCenterService.java` | 修改 | 新增 `flyToPoint()`, `flyToPointUpdate()`, `flyToPointStop()`, `getDeviceRealtimeData()` |
|
||||
| 3 | `order-center/.../controller/MissionController.java` | 修改 | 新增三个编排接口 |
|
||||
| 4 | `order-center/.../service/impl/MissionServiceImpl.java` | 修改 | 编排逻辑 + 设备锁 |
|
||||
| 5 | `device-center/.../controller/DeviceCommandController.java` | 修改 | 新增 `flyToPoint`, `flyToPointUpdate`, `flyToPointStop` |
|
||||
| 6 | `device-center/.../websocket/manager/DeviceCommandManager.java` | 修改 | 新增三个 case |
|
||||
| 7 | `device-center/.../controller/request/FlyToPointRequest.java` | **新增** | 请求 DTO |
|
||||
| 8 | `device-center/.../message/ControlEnum.java` | 修改 | 修正 `FLY_TO_POINT_UPDATE` 值 |
|
||||
| 9 | 数据库迁移脚本 | **新增** | `missions` 表新增 `phase` 字段 + `mission_fly_to_point` 子表 |
|
||||
|
||||
### 4.2 会话阶段(Phase)设计
|
||||
|
||||
为解决"返航后仍可更新目标"的 TOCTOU 问题,在 `missions` 主表增加 `phase` 字段:
|
||||
|
||||
| phase | 含义 | 允许更新目标 | 允许结束 |
|
||||
|-------|------|:--:|:--:|
|
||||
| `ACTIVE` | 飞行会话活跃 | ✅ | ✅ |
|
||||
| `RETURNING` | 返航中 | ❌ | ❌(幂等拒绝) |
|
||||
|
||||
> **为什么放在主表而非子表:** 用户可能在起飞后、首次点击目标前就选择"结束飞行",此时 `mission_fly_to_point` 子表还没有任何记录,无法读取或更新 phase。主表始终存在,无论是否有目标记录。
|
||||
|
||||
**规则:**
|
||||
- `startFlyToPoint` 创建任务时 phase = `ACTIVE`
|
||||
- `flyToPointUpdate` 校验 `missions.phase = ACTIVE`,否则拒绝
|
||||
- `endFlyToPoint` 先原子更新 `missions.phase = RETURNING`,再发停止和返航指令
|
||||
- phase 为 `RETURNING` 时,`flyToPointUpdate` 直接返回错误"飞行已结束,无法更新目标"
|
||||
|
||||
### 4.3 订单中心编排接口
|
||||
|
||||
#### 4.2.1 开始指点飞行
|
||||
|
||||
```
|
||||
POST /mission/startFlyToPoint
|
||||
```
|
||||
|
||||
请求参数:`deviceSn`, `dockLatitude`, `dockLongitude`, `dockHeight`
|
||||
|
||||
逻辑:
|
||||
1. 获取分布式锁(deviceSn 维度)
|
||||
2. 在锁内校验设备是否已有 DOING 状态的任务 → 互斥拒绝
|
||||
3. 创建 `FLY_TO_POINT` 任务 → 状态 PENDING
|
||||
4. 判断无人机是否已升空:调用 `deviceCenterService.getDeviceRealtimeData(deviceSn)` 获取实时遥测
|
||||
- 遥测 `height`(相对起飞点高度)> 升空阈值(如 5m)→ 已升空
|
||||
- 未升空 → Feign `deviceCenterService.takeoff()` 发送 `takeoff_to_point`(flight_id = missionCode)
|
||||
- 若获取遥测失败 → 保守按未升空处理,执行起飞命令
|
||||
|
||||
> **依赖:** 需在 `DeviceCenterService` Feign 中新增 `getDeviceRealtimeData(deviceSn)` 方法,
|
||||
> 对应设备中心的实时数据查询接口。若暂无此接口,可退而调用 SSE 缓存或首次一律执行起飞(设备侧会忽略重复起飞)。
|
||||
5. 命令入队成功 → 任务状态 → DOING(与现有 TAKEOFF/WAYLINE 任务保持一致)
|
||||
6. 释放锁,返回 `missionCode`
|
||||
|
||||
> **关于起飞超时:** 现有 TAKEOFF 任务命令入队即置 DOING,此为项目统一模式。如需增强可后续统一加超时检测——起飞命令发出后 N 秒内 SSE 高度未达标则标记失败。本次保持与现有模式一致。
|
||||
|
||||
#### 4.2.2 更新目标点(连续指点)
|
||||
|
||||
```
|
||||
POST /mission/flyToPointUpdate
|
||||
```
|
||||
|
||||
请求参数:`missionCode`, `latitude`, `longitude`, `height`, `maxSpeed`
|
||||
|
||||
逻辑:
|
||||
1. 获取分布式锁(deviceSn 维度)
|
||||
2. 在锁内校验任务归属(deviceSn 匹配)、状态为 DOING、phase = ACTIVE
|
||||
- phase = RETURNING → 拒绝,返回"飞行已结束,无法更新目标"
|
||||
3. 判断是首次指点还是连续指点:
|
||||
- 首次 → Feign `deviceCenterService.flyToPoint()`,传 flyToId = missionCode
|
||||
- 非首次 → Feign `deviceCenterService.flyToPointUpdate()`,不传 flyToId(设备协议无此字段),仅传 deviceSn + points
|
||||
4. 持久化目标点到 `mission_fly_to_point` 子表
|
||||
5. 释放锁,返回结果
|
||||
|
||||
#### 4.2.3 结束指点飞行
|
||||
|
||||
```
|
||||
POST /mission/endFlyToPoint
|
||||
```
|
||||
|
||||
请求参数:`missionCode`
|
||||
|
||||
逻辑:
|
||||
1. 获取分布式锁(deviceSn 维度)
|
||||
2. 在锁内校验任务状态为 DOING、phase = ACTIVE
|
||||
3. 原子更新 phase = `RETURNING`(防止其他请求并发更新目标)
|
||||
4. 查询 `mission_fly_to_point` 子表,判断是否存在 status = SENT(成功发送)的首次 `fly_to_point` 记录:
|
||||
- **有记录** → 设备端存在 fly_to_point 会话 → 发送 `fly_to_point_stop`(同步等待)
|
||||
- 超时/失败 → phase 回退为 ACTIVE,保留 DOING,返回错误"停止指点失败,请重试或手动操控"
|
||||
- **无记录** → 尚未发送过任何目标点,设备端无会话 → 跳过 stop
|
||||
5. 发送 `return_home`(同步等待)
|
||||
- 超时/失败 → 保留 DOING + phase = RETURNING,返回错误"返航命令失败,任务未结束"
|
||||
6. 释放锁
|
||||
7. 前端通过 SSE 检测落地(高度 < LANDED_THRESHOLD)后,调用 `completeMission` → COMPLETED
|
||||
|
||||
> **命令结果等待机制:** `DeviceCommandManager.sendCommand()` 返回 `commandId`(入队确认),设备响应后命令从 pendingCommands 移除,`getCommandStatus()` 查不到已完成命令。
|
||||
>
|
||||
> **采用方案B(CompletableFuture 同步等待):** 在 `DeviceCommandManager` 中提供同步等待 API:
|
||||
> ```java
|
||||
> public CommandResult sendCommandSync(String deviceSn, String commandType, JSONObject params, long timeoutMs)
|
||||
> ```
|
||||
> **实现要点(必须避免竞态):**
|
||||
> 1. 先调用内部方法生成 `commandId`(UUID)
|
||||
> 2. 创建 `CompletableFuture<CommandResult>` 并注册到 `Map<commandId, CompletableFuture>`
|
||||
> 3. 再发送命令(通过 WebSocket)
|
||||
> 4. `future.get(timeoutMs, TimeUnit.MILLISECONDS)` 阻塞等待
|
||||
> 5. **finally 块中统一移除 Future**(无论成功/失败/超时/异常),避免内存泄漏
|
||||
>
|
||||
> **不能先 send 再注册 Future:** 设备可能极快响应(<1ms),响应回调到达时 Future 尚未注册,导致丢失完成信号并错误超时。
|
||||
|
||||
### 4.3 DeviceCommandController 新增接口
|
||||
|
||||
```java
|
||||
// 首次飞向目标
|
||||
@PostMapping("/flyToPoint")
|
||||
public Result<String> flyToPoint(@RequestBody FlyToPointRequest request);
|
||||
|
||||
// 更新飞行目标点(连续指点)
|
||||
@PostMapping("/flyToPointUpdate")
|
||||
public Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequest request);
|
||||
|
||||
// 停止指点飞行
|
||||
@PostMapping("/flyToPointStop")
|
||||
public Result<String> flyToPointStop(@RequestParam String deviceSn);
|
||||
```
|
||||
|
||||
`FlyToPointRequest`(fly_to_point 首次使用):
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| deviceSn | String | 是 | 设备序列号 |
|
||||
| flyToId | String | 是 | 飞行会话ID(= missionCode) |
|
||||
| latitude | Double | 是 | 目标纬度 |
|
||||
| longitude | Double | 是 | 目标经度 |
|
||||
| height | Float | 是 | 目标椭球高(前端计算:Cartographic.height + 用户飞行高度) |
|
||||
| maxSpeed | Float | 否 | 最大速度,默认 12 |
|
||||
|
||||
`FlyToPointUpdateRequest`(fly_to_point_update 使用,无 flyToId 字段——设备协议不包含):
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| deviceSn | String | 是 | 设备序列号 |
|
||||
| latitude | Double | 是 | 目标纬度 |
|
||||
| longitude | Double | 是 | 目标经度 |
|
||||
| height | Float | 是 | 目标椭球高 |
|
||||
| maxSpeed | Float | 否 | 最大速度,默认 12 |
|
||||
|
||||
### 4.4 DeviceCommandManager 新增 case
|
||||
|
||||
```java
|
||||
case "fly_to_point":
|
||||
data.put("fly_to_id", params.getString("fly_to_id"));
|
||||
data.put("max_speed", params.getFloatValue("max_speed"));
|
||||
// points 数组...
|
||||
break;
|
||||
|
||||
case "fly_to_point_update":
|
||||
// 注意:设备协议无 fly_to_id,仅传 max_speed + points
|
||||
data.put("max_speed", params.getFloatValue("max_speed"));
|
||||
// points 数组...
|
||||
break;
|
||||
|
||||
case "fly_to_point_stop":
|
||||
// 无参数
|
||||
break;
|
||||
```
|
||||
|
||||
### 4.5 数据库:`mission_fly_to_point` 子表
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | BIGINT | 主键 |
|
||||
| mission_code | VARCHAR | 关联任务编码 |
|
||||
| fly_to_id | VARCHAR | 飞行会话ID |
|
||||
| command_id | VARCHAR | 设备命令ID |
|
||||
| seq | INT | 目标序号(1, 2, 3...) |
|
||||
| command_type | VARCHAR | 指令类型:fly_to_point / fly_to_point_update |
|
||||
| latitude | DOUBLE | 目标纬度 |
|
||||
| longitude | DOUBLE | 目标经度 |
|
||||
| height | FLOAT | 目标高度 |
|
||||
| max_speed | FLOAT | 最大速度 |
|
||||
| status | VARCHAR | SENT / REACHED / FAILED |
|
||||
| create_time | DATETIME | 创建时间 |
|
||||
| update_time | DATETIME | 更新时间 |
|
||||
|
||||
### 4.6 设备级分布式锁
|
||||
|
||||
所有编排接口按 `deviceSn` 加锁,确保同一设备不会并发执行多个飞行操作。
|
||||
|
||||
---
|
||||
|
||||
## 五、前端改动
|
||||
|
||||
### 5.1 文件清单
|
||||
|
||||
| # | 文件 | 改动 | 说明 |
|
||||
|---|------|------|------|
|
||||
| 1 | `src/services/mission.ts` | 修改 | 新增 `startFlyToPoint()`, `flyToPointUpdate()`, `endFlyToPoint()` |
|
||||
| 3 | `CesiumContainer.tsx` | 修改 | 点击交互、目标标记、十字光标 |
|
||||
| 4 | `RightPanel.tsx` | 修改 | "指点飞行"入口按钮 |
|
||||
| 5 | `hooks/useFlyToPoint.ts` | **新增** | 状态机 hook |
|
||||
| 6 | `components/FlyToPointPanel.tsx` | **新增** | 确认弹窗 + 迷你确认 + 状态条 |
|
||||
|
||||
### 5.2 前端调用链路
|
||||
|
||||
```
|
||||
前端不直接调设备接口,全部走订单中心编排接口:
|
||||
|
||||
开始飞行 → POST /api-order/mission/startFlyToPoint → 订单中心编排起飞 + 任务
|
||||
更新目标 → POST /api-order/mission/flyToPointUpdate → 订单中心编排 fly_to_point / fly_to_point_update
|
||||
结束飞行 → POST /api-order/mission/endFlyToPoint → 订单中心编排 stop + return_home
|
||||
拍照 → POST /api-device/device/command/photo → 仅传 deviceSn(不变)
|
||||
|
||||
> **注意:** `src/services/device.ts` 不新增飞行 API。所有飞行指令由订单中心编排,前端仅调用 mission.ts 中的编排接口。
|
||||
```
|
||||
|
||||
### 5.3 `useFlyToPoint.ts` 状态机
|
||||
|
||||
```typescript
|
||||
type FlyToPointState =
|
||||
| 'IDLE' // 未激活
|
||||
| 'TAKING_OFF' // 正在起飞
|
||||
| 'WAITING_TARGET' // 已升空,等待用户点击目标 ←┐
|
||||
| 'FLYING_TO' // 正在飞向目标 │
|
||||
| 'RETURNING' // 返航中(前端展示态,后端任务仍为 DOING)│ 循环
|
||||
| 'COMPLETED'; // 已完成 ─┘
|
||||
```
|
||||
|
||||
**核心方法:**
|
||||
|
||||
| 方法 | 调用的接口 | 行为 |
|
||||
|------|-----------|------|
|
||||
| `startFlyToPoint()` | `missionApi.startFlyToPoint()` | 创建任务 + 起飞 → TAKING_OFF |
|
||||
| `selectTarget(lng, lat)` | — | 保存目标 → 弹出迷你确认 |
|
||||
| `confirmTarget(height, speed)` | `missionApi.flyToPointUpdate()` | 后端编排 → FLYING_TO |
|
||||
| `cancelTarget()` | — | 回到 WAITING_TARGET |
|
||||
| `endFlight()` | `missionApi.endFlyToPoint()` | 停止 + 返航 → RETURNING |
|
||||
| `cancel()` | — | 取消流程 |
|
||||
|
||||
**SSE 驱动自动状态切换:**
|
||||
|
||||
```typescript
|
||||
// TAKING_OFF → WAITING_TARGET(起飞完成,使用 SSE 相对高度)
|
||||
dronePosition.height > SAFE_HEIGHT
|
||||
|
||||
// FLYING_TO → WAITING_TARGET(到达目标,使用水平大地距离)
|
||||
horizontalDistance < ARRIVAL_THRESHOLD // 默认 5m
|
||||
|
||||
// RETURNING → COMPLETED(前端 SSE 检测落地后调 completeMission)
|
||||
dronePosition.height < LANDED_THRESHOLD
|
||||
// → 调用 missionApi.completeMission(missionCode) → 后端 → COMPLETED
|
||||
```
|
||||
|
||||
### 5.4 `CesiumContainer.tsx` 地图交互
|
||||
|
||||
```
|
||||
WAITING_TARGET 时:
|
||||
├─ 鼠标变为十字光标
|
||||
├─ LEFT_CLICK → pickPosition() → 坐标转换 → selectTarget()
|
||||
│ ├─ 命中地形 → 红色 Pin 标记
|
||||
│ └─ 未命中 → 提示"请点击地面"
|
||||
├─ RIGHT_CLICK → 取消选择
|
||||
└─ 顶部状态条
|
||||
|
||||
FLYING_TO 时:
|
||||
├─ 目标点与无人机之间虚线
|
||||
└─ 实时水平距离显示
|
||||
```
|
||||
|
||||
### 5.5 UI 组件
|
||||
|
||||
**Cesium 顶部状态条(飞行中常驻):**
|
||||
```
|
||||
┌────────────────────────────────────────────────┐
|
||||
│ 📍 指点飞行 | 任务 #xxx | ⬤等待目标 | [🏁结束] │
|
||||
│ 📍 指点飞行 | 任务 #xxx | ⬤飞向目标 距离 230m │
|
||||
│ 📍 指点飞行 | 任务 #xxx | ⬤起飞中... │
|
||||
└────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**迷你目标确认(每次点击地球后弹出):**
|
||||
```
|
||||
┌──────────────────────────────────────────┐
|
||||
│ 🎯 飞向目标 │
|
||||
│ 经度:113.123456 纬度:23.123456 │
|
||||
│ 飞行高度:[ 120 ] m ✏️ (相对地面) │
|
||||
│ 最大速度:[ 12 ] m/s ✏️ │
|
||||
│ [取消] [确认飞行] │
|
||||
└──────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 六、任务状态流转
|
||||
|
||||
```
|
||||
PENDING ──(命令入队成功)──→ DOING ─────────────────────────────────┐
|
||||
│ │
|
||||
┌───────────────┼───────────────┐ │
|
||||
↓ ↓ ↓ │
|
||||
fly_to_point fly_to_point_ endFlyToPoint │
|
||||
(首次目标) update(连续) (停止+返航) │
|
||||
│ │ │ │
|
||||
↓ ↓ ↓ │
|
||||
持久化到 持久化到 任务保持 DOING │
|
||||
mission_ mission_ 前端 SSE 检测落地 │
|
||||
fly_to_point fly_to_point ↓ │
|
||||
completeMission │
|
||||
↓ │
|
||||
COMPLETED │
|
||||
```
|
||||
|
||||
> **不新增 COMPLETING 状态。** 返航期间任务保持 DOING,前端本地展示为 RETURNING;落地后由前端调用 `completeMission` 完成。
|
||||
|
||||
---
|
||||
|
||||
## 七、边缘情况
|
||||
|
||||
| 场景 | 处理方式 |
|
||||
|------|---------|
|
||||
| 点击天空(未命中地形) | `pickPosition()` 返回 undefined → 提示"请点击地面" |
|
||||
| 起飞中取消 | 调用 `endFlyToPoint`:先 stop 再 return_home,任务保持 DOING,前端 SSE 检测落地后 completeMission |
|
||||
| 返航中更新目标 | `endFlyToPoint` 已将 phase 改为 RETURNING,`flyToPointUpdate` 校验 phase 拒绝 |
|
||||
| fly_to_point 超时/失败 | 错误提示,回到 WAITING_TARGET,失败原因记录到 `mission_fly_to_point` |
|
||||
| fly_to_point_stop 失败 | 保留 DOING,返回错误"停止指点失败,请重试或手动操控" |
|
||||
| return_home 失败 | 保留 DOING,返回错误"返航命令失败,任务未结束",可重试 |
|
||||
| 无人机断连 | SSE onError → 中止流程,提示"设备已断开",任务保持 DOING 待人工处理 |
|
||||
| 多端并发 | 后端先获取 deviceSn 锁,再检查冲突,杜绝 TOCTOU 竞态 |
|
||||
| 同一设备有其他 DOING 任务 | 锁内检查,互斥拒绝,提示"设备正在执行其他任务" |
|
||||
| 到达后继续选点 | 自动回到 WAITING_TARGET,上一目标保留灰色标记 |
|
||||
| 目标高度 | 前端从 Cesium 点击点取 `Cartographic.height`(椭球高),加上用户输入的飞行高度,计算最终椭球高提交 |
|
||||
|
||||
---
|
||||
|
||||
## 八、涉及文件总览(14 个文件)
|
||||
|
||||
| 层 | 文件 | 类型 |
|
||||
|----|------|------|
|
||||
| 后端 | `order-center/.../enums/MissionType.java` | 修改 |
|
||||
| 后端 | `order-center/.../feign/DeviceCenterService.java` | 修改 |
|
||||
| 后端 | `order-center/.../controller/MissionController.java` | 修改 |
|
||||
| 后端 | `order-center/.../service/impl/MissionServiceImpl.java` | 修改 |
|
||||
| 后端 | `device-center/.../controller/DeviceCommandController.java` | 修改 |
|
||||
| 后端 | `device-center/.../websocket/manager/DeviceCommandManager.java` | 修改 |
|
||||
| 后端 | `device-center/.../message/ControlEnum.java` | 修改 |
|
||||
| 后端 | `device-center/.../controller/request/FlyToPointRequest.java` | 新增 |
|
||||
| 后端 | 数据库迁移脚本 | 新增 |
|
||||
| 前端 | `src/services/mission.ts` | 修改 |
|
||||
| 前端 | `CesiumContainer.tsx` | 修改 |
|
||||
| 前端 | `RightPanel.tsx` | 修改 |
|
||||
| 前端 | `hooks/useFlyToPoint.ts` | 新增 |
|
||||
| 前端 | `components/FlyToPointPanel.tsx` | 新增 |
|
||||
+116
@@ -973,6 +973,120 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.zoomControl {
|
||||
position: relative;
|
||||
flex: 0 0 52px;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
|
||||
.zoomBtn {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
}
|
||||
|
||||
.zoomBar {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 3;
|
||||
width: 52px;
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
border: 1px solid rgba(0, 212, 255, 0.52);
|
||||
border-radius: 12px;
|
||||
background: rgba(5, 17, 29, 0.96);
|
||||
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.zoomCloseBtn,
|
||||
.zoomStepBtn {
|
||||
width: 42px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: rgba(208, 242, 250, 0.85);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.16s ease, color 0.16s ease, transform 0.16s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(0, 212, 255, 0.16);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
&:active:not(:disabled) {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
transform: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
.zoomCloseBtn {
|
||||
height: 26px;
|
||||
border-bottom: 1px solid rgba(168, 210, 226, 0.16);
|
||||
border-radius: 7px 7px 0 0;
|
||||
color: rgba(201, 222, 230, 0.62);
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 92, 105, 0.13);
|
||||
color: #ff9ca4;
|
||||
}
|
||||
}
|
||||
|
||||
.zoomStepBtn {
|
||||
height: 38px;
|
||||
margin: 2px 0;
|
||||
border-radius: 8px;
|
||||
font-size: 17px;
|
||||
line-height: 1;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.zoomReadout {
|
||||
width: 42px;
|
||||
height: 47px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-top: 1px solid rgba(168, 210, 226, 0.12);
|
||||
border-bottom: 1px solid rgba(168, 210, 226, 0.12);
|
||||
}
|
||||
|
||||
.zoomLabel {
|
||||
color: rgba(183, 211, 222, 0.56);
|
||||
font-size: 9px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.08em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.zoomValue {
|
||||
margin-top: 2px;
|
||||
color: #eefbff;
|
||||
font-family: 'Bahnschrift', 'Microsoft YaHei', sans-serif;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.zoomUnit {
|
||||
margin-left: 1px;
|
||||
color: @primary;
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
opacity: 0.82;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -994,6 +1108,8 @@
|
||||
50% { opacity: 0.4; }
|
||||
}
|
||||
|
||||
|
||||
|
||||
@keyframes recordPulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(255, 71, 87, 0.6); }
|
||||
70% { box-shadow: 0 0 0 15px rgba(255, 71, 87, 0); }
|
||||
|
||||
+161
-3
@@ -17,6 +17,9 @@ import {
|
||||
DisconnectOutlined,
|
||||
CompassOutlined,
|
||||
WarningOutlined,
|
||||
ZoomInOutlined,
|
||||
MinusOutlined,
|
||||
PlusOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { message, Modal, Tooltip, Spin } from 'antd';
|
||||
import { deviceApi } from '@/services/device';
|
||||
@@ -108,6 +111,8 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
hSpeed: Number(data?.horizontal_speed ?? 0).toFixed(1),
|
||||
vSpeed: Number(data?.vertical_speed ?? 0).toFixed(1),
|
||||
alt: Number(data?.height ?? data?.elevation ?? 0).toFixed(1),
|
||||
relAlt: Number(data?.height ?? 0).toFixed(1),
|
||||
absAlt: Number(data?.elevation ?? 0).toFixed(1),
|
||||
dist: Number(data?.home_distance ?? 0).toFixed(1),
|
||||
sat: data?.position_state?.gps_number ?? 0,
|
||||
rtk: data?.position_state?.is_fixed === 2 ? 'FIX' : 'FLOAT',
|
||||
@@ -142,6 +147,11 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
const [cameraMode, setCameraMode] = useState<number | null>(null);
|
||||
// 相机操作loading状态
|
||||
const [cameraLoading, setCameraLoading] = useState(false);
|
||||
// 变焦
|
||||
const [zoomFactor, setZoomFactor] = useState<number>(2);
|
||||
const [zoomLoading, setZoomLoading] = useState(false);
|
||||
const [zoomActive, setZoomActive] = useState(false);
|
||||
const zoomTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 视频尺寸状态
|
||||
const [videoSize, setVideoSize] = useState<'normal' | 'large' | 'fullscreen'>('normal');
|
||||
@@ -365,7 +375,60 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
// 进入指令飞行模式(DRC模式)
|
||||
// ========== 云台变焦 ==========
|
||||
|
||||
// 切换到变焦镜头并展开变焦控制
|
||||
const switchToZoomLens = useCallback(async () => {
|
||||
if (!deviceSn || !wsConnected || !drcModeRef.current) return;
|
||||
setZoomLoading(true);
|
||||
try {
|
||||
await deviceApi.liveLensChange({ deviceSn, videoType: 'zoom' });
|
||||
setZoomActive(true);
|
||||
message.success('已切换到变焦镜头');
|
||||
} catch {
|
||||
message.error('切换变焦镜头失败');
|
||||
} finally {
|
||||
setZoomLoading(false);
|
||||
}
|
||||
}, [deviceSn, wsConnected]);
|
||||
|
||||
// 设置变焦倍数
|
||||
const setZoom = useCallback(async (factor: number) => {
|
||||
if (!deviceSn || !wsConnected || !drcModeRef.current) return;
|
||||
const clamped = Math.max(2, Math.min(200, Math.round(factor * 10) / 10));
|
||||
setZoomFactor(clamped);
|
||||
try {
|
||||
await deviceApi.cameraFocalLengthSet({ deviceSn, zoomFactor: clamped });
|
||||
} catch {
|
||||
// 变焦失败时静默
|
||||
}
|
||||
}, [deviceSn, wsConnected]);
|
||||
|
||||
// 连续变焦(按住时持续调用)
|
||||
const startContinuousZoom = useCallback((delta: number) => {
|
||||
if (zoomTimerRef.current) return; // 已在变焦中
|
||||
const step = delta > 0 ? 2 : -2; // 每次步进2倍
|
||||
const ms = 200; // 200ms 间隔
|
||||
|
||||
const tick = () => {
|
||||
setZoomFactor(prev => {
|
||||
const next = Math.max(2, Math.min(200, prev + step));
|
||||
deviceApi.cameraFocalLengthSet({ deviceSn, zoomFactor: next }).catch(() => {});
|
||||
return next;
|
||||
});
|
||||
zoomTimerRef.current = setTimeout(tick, ms);
|
||||
};
|
||||
tick();
|
||||
}, [deviceSn]);
|
||||
|
||||
const stopContinuousZoom = useCallback(() => {
|
||||
if (zoomTimerRef.current) {
|
||||
clearTimeout(zoomTimerRef.current);
|
||||
zoomTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ===============================
|
||||
const handleEnterDrcMode = async () => {
|
||||
if (!deviceSn || !wsConnected || drcLoading) return;
|
||||
|
||||
@@ -392,6 +455,8 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
setDrcMode(false);
|
||||
drcModeRef.current = false;
|
||||
setActiveKeys(new Set());
|
||||
setZoomActive(false);
|
||||
setZoomFactor(2);
|
||||
message.info('已退出指令飞行模式');
|
||||
};
|
||||
|
||||
@@ -465,6 +530,9 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
'arrowleft': ['left', 'gimbal'], // 云台左转
|
||||
'arrowright': ['right', 'gimbal'] // 云台右转
|
||||
};
|
||||
// 变焦用独立定时器(连续按键)
|
||||
let zoomInTimer: NodeJS.Timeout | null = null;
|
||||
let zoomOutTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
const down = (e: KeyboardEvent) => {
|
||||
const k = e.key.toLowerCase();
|
||||
@@ -480,6 +548,25 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
if (map[k] && !activeKeys.has(k)) {
|
||||
setActiveKeys(p => new Set(p).add(k));
|
||||
}
|
||||
// 变焦按键:`+` / `=` 放大,`-` 缩小(仅在DRC模式)
|
||||
const isZoomIn = (k === '=' || k === '+');
|
||||
const isZoomOut = (k === '-');
|
||||
if (drcModeRef.current && (isZoomIn || isZoomOut) && !e.repeat) {
|
||||
e.preventDefault();
|
||||
const timer = isZoomIn ? zoomInTimer : zoomOutTimer;
|
||||
if (timer) return;
|
||||
const step = isZoomIn ? 2 : -2;
|
||||
const tick = () => {
|
||||
setZoomFactor(prev => {
|
||||
const next = Math.max(2, Math.min(200, prev + step));
|
||||
deviceApi.cameraFocalLengthSet({ deviceSn, zoomFactor: next }).catch(() => {});
|
||||
return next;
|
||||
});
|
||||
if (isZoomIn) { zoomInTimer = setTimeout(tick, 200); }
|
||||
else { zoomOutTimer = setTimeout(tick, 200); }
|
||||
};
|
||||
tick();
|
||||
}
|
||||
};
|
||||
|
||||
const up = (e: KeyboardEvent) => {
|
||||
@@ -491,6 +578,13 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
return n;
|
||||
});
|
||||
}
|
||||
// 停止连续变焦
|
||||
if (k === '=' || k === '+') {
|
||||
if (zoomInTimer) { clearTimeout(zoomInTimer); zoomInTimer = null; }
|
||||
}
|
||||
if (k === '-') {
|
||||
if (zoomOutTimer) { clearTimeout(zoomOutTimer); zoomOutTimer = null; }
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', down);
|
||||
@@ -877,6 +971,8 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
<div>X: 切换速度档位</div>
|
||||
<div style={{ marginTop: '4px' }}><b>云台控制:</b></div>
|
||||
<div>方向键: 上/下/左/右</div>
|
||||
<div style={{ marginTop: '4px' }}><b>变焦:</b></div>
|
||||
<div>- / + : 缩小 / 放大</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -945,8 +1041,12 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
<div className={styles.rightDataPanel}>
|
||||
<div className={styles.dataCard}>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.label}>高度</span>
|
||||
<span className={styles.value}>{flightData.alt}<span className={styles.unit}>m</span></span>
|
||||
<span className={styles.label}>相对高度</span>
|
||||
<span className={styles.value}>{flightData.relAlt}<span className={styles.unit}>m</span></span>
|
||||
</div>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.label}>绝对高度</span>
|
||||
<span className={styles.value}>{flightData.absAlt}<span className={styles.unit}>m</span></span>
|
||||
</div>
|
||||
<div className={styles.divider}></div>
|
||||
<div className={styles.attitudeRow}>
|
||||
@@ -1057,6 +1157,63 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
|
||||
{/* 右侧相机控制 */}
|
||||
<div className={styles.cameraControls}>
|
||||
{/* 变焦入口固定在相机按钮组内;展开时仅在该位置向上显示竖向控制 */}
|
||||
<div className={styles.zoomControl}>
|
||||
{!zoomActive ? (
|
||||
<Tooltip title={drcMode ? '切换至变焦镜头' : '请先进入手动控制模式'} placement="top">
|
||||
<button
|
||||
className={`${styles.cameraBtn} ${styles.zoomBtn} ${(!drcMode || zoomLoading) ? styles.disabled : ''}`}
|
||||
onClick={switchToZoomLens}
|
||||
disabled={!drcMode || zoomLoading}
|
||||
aria-label="切换至变焦镜头"
|
||||
>
|
||||
{zoomLoading ? <LoadingOutlined spin /> : <ZoomInOutlined />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<div className={styles.zoomBar}>
|
||||
<Tooltip title="退出变焦" placement="left">
|
||||
<button
|
||||
className={styles.zoomCloseBtn}
|
||||
aria-label="退出变焦"
|
||||
onClick={() => {
|
||||
setZoomActive(false);
|
||||
setZoomFactor(2);
|
||||
if (deviceSn && drcModeRef.current) {
|
||||
deviceApi.cameraFocalLengthSet({ deviceSn, zoomFactor: 2 }).catch(() => {});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<CloseOutlined style={{ fontSize: 12 }} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<button
|
||||
className={styles.zoomStepBtn}
|
||||
onMouseDown={() => startContinuousZoom(2)}
|
||||
onMouseUp={stopContinuousZoom}
|
||||
onMouseLeave={stopContinuousZoom}
|
||||
disabled={!drcMode}
|
||||
aria-label="放大"
|
||||
>
|
||||
<PlusOutlined />
|
||||
</button>
|
||||
<div className={styles.zoomReadout}>
|
||||
<span className={styles.zoomLabel}>变焦</span>
|
||||
<span className={styles.zoomValue}>{zoomFactor.toFixed(1)}<span className={styles.zoomUnit}>×</span></span>
|
||||
</div>
|
||||
<button
|
||||
className={styles.zoomStepBtn}
|
||||
onMouseDown={() => startContinuousZoom(-2)}
|
||||
onMouseUp={stopContinuousZoom}
|
||||
onMouseLeave={stopContinuousZoom}
|
||||
disabled={!drcMode}
|
||||
aria-label="缩小"
|
||||
>
|
||||
<MinusOutlined />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Tooltip title={isRecording ? '录像中,请先停止录像' : (cameraLoading ? '处理中...' : '拍照')} placement="top">
|
||||
<button
|
||||
className={`${styles.cameraBtn} ${(cameraLoading || isRecording) ? styles.disabled : ''}`}
|
||||
@@ -1084,6 +1241,7 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</>
|
||||
|
||||
+39
-10
@@ -31,8 +31,12 @@ interface RightPanelProps {
|
||||
/** 关闭面板(退出设备:会清空选中设备等) */
|
||||
onClose: () => void;
|
||||
onControlClick: (device: any, realtimeData: any) => void;
|
||||
/** 一键起飞任务创建成功后切换到操控台 */
|
||||
onTakeoffSuccess?: (device: any, realtimeData: any) => void;
|
||||
onTaskPanelOpen?: (device: any, dockData: any) => void; // 打开任务管理面板回调
|
||||
onRoutePlanningOpen?: (device: any) => void; // 打开航线规划面板回调(无人船)
|
||||
onFlyToPointActivate?: (deviceSn: string, dockLat?: number, dockLng?: number, dockH?: number) => void; // 激活指点飞行
|
||||
flyToPointState?: string; // 指点飞行状态(用于按钮禁用)
|
||||
viewer?: any; // Cesium Viewer 实例
|
||||
Cesium?: any; // Cesium 库
|
||||
}
|
||||
@@ -43,8 +47,11 @@ const RightPanel: React.FC<RightPanelProps> = ({
|
||||
onMinimize,
|
||||
onClose,
|
||||
onControlClick,
|
||||
onTakeoffSuccess,
|
||||
onTaskPanelOpen,
|
||||
onRoutePlanningOpen,
|
||||
onFlyToPointActivate,
|
||||
flyToPointState,
|
||||
viewer,
|
||||
Cesium
|
||||
}) => {
|
||||
@@ -171,12 +178,13 @@ const RightPanel: React.FC<RightPanelProps> = ({
|
||||
targetHeight: targetHeight,
|
||||
});
|
||||
|
||||
// 兼容两种响应格式:resp_code/resp_msg 或 code/msg
|
||||
const code = res.resp_code !== undefined ? res.resp_code : res.resp_code;
|
||||
const msg = res.resp_msg !== undefined ? res.resp_msg : res.resp_msg;
|
||||
// 网关与服务端可能分别返回 resp_code 或 code,统一为数值后判断。
|
||||
const code = Number(res.resp_code ?? res.code);
|
||||
const msg = res.resp_msg ?? res.msg;
|
||||
|
||||
if (code === 0) {
|
||||
message.success('一键起飞任务已创建,无人机将自动开机并起飞');
|
||||
onTakeoffSuccess?.(device, realtimeData);
|
||||
} else {
|
||||
message.error(msg || '一键起飞任务创建失败');
|
||||
}
|
||||
@@ -318,13 +326,34 @@ const RightPanel: React.FC<RightPanelProps> = ({
|
||||
<div className={styles.section}>
|
||||
<div className={styles.sectionHeader}>
|
||||
<span>机库信息 / DOCK INFO</span>
|
||||
<button
|
||||
className={styles.takeoffBtn}
|
||||
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0}
|
||||
onClick={handleTakeoff}
|
||||
>
|
||||
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞
|
||||
</button>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button
|
||||
className={styles.takeoffBtn}
|
||||
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0}
|
||||
onClick={handleTakeoff}
|
||||
>
|
||||
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞
|
||||
</button>
|
||||
<button
|
||||
className={styles.takeoffBtn}
|
||||
disabled={
|
||||
!onFlyToPointActivate ||
|
||||
!device?.deviceSn ||
|
||||
!!flyToPointState && flyToPointState !== 'IDLE' && flyToPointState !== 'COMPLETED'
|
||||
}
|
||||
onClick={() => {
|
||||
if (onFlyToPointActivate && device?.deviceSn) {
|
||||
const dockLat = dockData?.latitude || realtimeData?.gps?.latitude;
|
||||
const dockLng = dockData?.longitude || realtimeData?.gps?.longitude;
|
||||
const dockH = dockData?.height || realtimeData?.gps?.altitude || 0;
|
||||
onFlyToPointActivate(device.deviceSn, dockLat, dockLng, dockH);
|
||||
}
|
||||
}}
|
||||
title="创建指点飞行任务,升空后可在地图上连续点击目标位置"
|
||||
>
|
||||
<EnvironmentOutlined /> 指点飞行
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 状态卡片 */}
|
||||
|
||||
+104
-104
@@ -156,7 +156,7 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
||||
const modalPendingPosRef = useRef({ x: 0, y: 0 });
|
||||
|
||||
// Tab 状态
|
||||
const [activeTab, setActiveTab] = useState<string>('route');
|
||||
const [activeTab, setActiveTab] = useState<string>('task');
|
||||
|
||||
// 拖拽状态
|
||||
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||||
@@ -258,8 +258,8 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
||||
}));
|
||||
setRouteList(unifiedRoutes);
|
||||
|
||||
// 默认选中第一条,并绘制到模型上(仅首次进入或未选中时)
|
||||
if (!selectedRouteId && unifiedRoutes.length > 0) {
|
||||
// 默认选中第一条航线(仅在航线 Tab 激活时)
|
||||
if (!selectedRouteId && unifiedRoutes.length > 0 && activeTab === 'route') {
|
||||
const first = unifiedRoutes[0];
|
||||
setSelectedRouteId(first.routeId);
|
||||
loadWaypointsRef.current?.(first.routeId, first.routeType);
|
||||
@@ -286,7 +286,7 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
||||
}));
|
||||
setRouteList(unifiedRoutes);
|
||||
|
||||
if (!selectedRouteId && unifiedRoutes.length > 0) {
|
||||
if (!selectedRouteId && unifiedRoutes.length > 0 && activeTab === 'route') {
|
||||
const first = unifiedRoutes[0];
|
||||
setSelectedRouteId(first.routeId);
|
||||
loadWaypointsRef.current?.(first.routeId, first.routeType);
|
||||
@@ -966,7 +966,105 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
className={styles.tabs}
|
||||
items={[
|
||||
items={[{
|
||||
key: 'task',
|
||||
label: <span><UnorderedListOutlined /> 任务</span>,
|
||||
children: (
|
||||
<div className={styles.tabContent}>
|
||||
<div className={styles.section}>
|
||||
<div className={styles.sectionTitle}>
|
||||
任务列表
|
||||
{missionLoading && <Spin size="small" style={{ marginLeft: 8 }} />}
|
||||
</div>
|
||||
<div className={styles.taskList}>
|
||||
{missionLoading && missionList.length === 0 ? (
|
||||
<div className={styles.loading}>加载中...</div>
|
||||
) : missionList.length === 0 ? (
|
||||
<Empty
|
||||
description="暂无任务,请先创建"
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
className={styles.emptyState}
|
||||
/>
|
||||
) : (
|
||||
missionList.map(mission => (
|
||||
<div
|
||||
key={mission.missionCode}
|
||||
className={`${styles.taskItem} ${selectedMissionCode === mission.missionCode ? styles.selected : ''}`}
|
||||
onClick={() => setSelectedMissionCode(mission.missionCode || null)}
|
||||
>
|
||||
<div className={styles.taskInfo}>
|
||||
<div className={styles.taskHeader}>
|
||||
<span className={styles.taskCode}>{mission.missionCode}</span>
|
||||
</div>
|
||||
<div className={styles.taskName}>
|
||||
{mission.missionName || mission.waylineName || '未命名任务'}
|
||||
</div>
|
||||
<div className={styles.taskMeta}>
|
||||
<Tag color={mission.missionType === MissionType.TAKEOFF ? 'orange' : 'blue'}>
|
||||
{MissionTypeMap[mission.missionType || 1]}
|
||||
</Tag>
|
||||
<Tag
|
||||
icon={getMissionStatusIcon(mission.missionStatus || 1)}
|
||||
color={MissionStatusColorMap[mission.missionStatus || 1]}
|
||||
>
|
||||
{MissionStatusMap[mission.missionStatus || 1]}
|
||||
</Tag>
|
||||
<span className={styles.taskTime}>{formatTime(mission.createTime)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.taskActions}>
|
||||
<Tooltip title="查看媒体">
|
||||
<button
|
||||
className={styles.actionBtn}
|
||||
onClick={(e) => { e.stopPropagation(); handleViewMissionMedia(mission); }}
|
||||
disabled={mediaLoading}
|
||||
>
|
||||
<PictureOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{mission.missionStatus === MissionStatus.PENDING && mission.missionType === MissionType.WAYLINE && (
|
||||
<Tooltip title={isDockIdle ? '执行任务' : '机库忙碌中'}>
|
||||
<button
|
||||
className={`${styles.actionBtn} ${styles.execute}`}
|
||||
onClick={(e) => { e.stopPropagation(); handleExecuteMission(mission); }}
|
||||
disabled={!isDockIdle}
|
||||
>
|
||||
<PlayCircleOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{(mission.missionStatus === MissionStatus.DOING || mission.missionStatus === MissionStatus.UPLOADING || mission.missionStatus === MissionStatus.UPLOADED) && (
|
||||
<Tooltip title="完成任务">
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); handleCompleteMission(mission); }}>
|
||||
<CheckCircleOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{mission.missionStatus === MissionStatus.PENDING && (
|
||||
<Tooltip title="取消任务">
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); handleCancelMission(mission); }}>
|
||||
<CloseCircleOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{(mission.missionStatus === MissionStatus.COMPLETE || mission.missionStatus === MissionStatus.CANCELED) && (
|
||||
<Tooltip title="删除任务">
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={(e) => { e.stopPropagation(); handleDeleteMission(mission); }}>
|
||||
<DeleteOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
,
|
||||
|
||||
{
|
||||
key: 'route',
|
||||
label: <span><EnvironmentOutlined /> 航线</span>,
|
||||
@@ -1072,105 +1170,7 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'task',
|
||||
label: <span><UnorderedListOutlined /> 任务</span>,
|
||||
children: (
|
||||
<div className={styles.tabContent}>
|
||||
<div className={styles.section}>
|
||||
<div className={styles.sectionTitle}>
|
||||
任务列表
|
||||
{missionLoading && <Spin size="small" style={{ marginLeft: 8 }} />}
|
||||
</div>
|
||||
<div className={styles.taskList}>
|
||||
{missionLoading && missionList.length === 0 ? (
|
||||
<div className={styles.loading}>加载中...</div>
|
||||
) : missionList.length === 0 ? (
|
||||
<Empty
|
||||
description="暂无任务,请先创建"
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
className={styles.emptyState}
|
||||
/>
|
||||
) : (
|
||||
missionList.map(mission => (
|
||||
<div
|
||||
key={mission.missionCode}
|
||||
className={`${styles.taskItem} ${selectedMissionCode === mission.missionCode ? styles.selected : ''}`}
|
||||
onClick={() => setSelectedMissionCode(mission.missionCode || null)}
|
||||
>
|
||||
<div className={styles.taskInfo}>
|
||||
<div className={styles.taskHeader}>
|
||||
<span className={styles.taskCode}>{mission.missionCode}</span>
|
||||
</div>
|
||||
<div className={styles.taskName}>
|
||||
{mission.missionName || mission.waylineName || '未命名任务'}
|
||||
</div>
|
||||
<div className={styles.taskMeta}>
|
||||
<Tag color={mission.missionType === MissionType.TAKEOFF ? 'orange' : 'blue'}>
|
||||
{MissionTypeMap[mission.missionType || 1]}
|
||||
</Tag>
|
||||
<Tag
|
||||
icon={getMissionStatusIcon(mission.missionStatus || 1)}
|
||||
color={MissionStatusColorMap[mission.missionStatus || 1]}
|
||||
>
|
||||
{MissionStatusMap[mission.missionStatus || 1]}
|
||||
</Tag>
|
||||
<span className={styles.taskTime}>{formatTime(mission.createTime)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.taskActions}>
|
||||
<Tooltip title="查看媒体">
|
||||
<button
|
||||
className={styles.actionBtn}
|
||||
onClick={(e) => { e.stopPropagation(); handleViewMissionMedia(mission); }}
|
||||
disabled={mediaLoading}
|
||||
>
|
||||
<PictureOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{mission.missionStatus === MissionStatus.PENDING && mission.missionType === MissionType.WAYLINE && (
|
||||
<Tooltip title={isDockIdle ? '执行任务' : '机库忙碌中'}>
|
||||
<button
|
||||
className={`${styles.actionBtn} ${styles.execute}`}
|
||||
onClick={(e) => { e.stopPropagation(); handleExecuteMission(mission); }}
|
||||
disabled={!isDockIdle}
|
||||
>
|
||||
<PlayCircleOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{(mission.missionStatus === MissionStatus.DOING || mission.missionStatus === MissionStatus.UPLOADING || mission.missionStatus === MissionStatus.UPLOADED) && (
|
||||
<Tooltip title="完成任务">
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); handleCompleteMission(mission); }}>
|
||||
<CheckCircleOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{mission.missionStatus === MissionStatus.PENDING && (
|
||||
<Tooltip title="取消任务">
|
||||
<button className={styles.actionBtn} onClick={(e) => { e.stopPropagation(); handleCancelMission(mission); }}>
|
||||
<CloseCircleOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{(mission.missionStatus === MissionStatus.COMPLETE || mission.missionStatus === MissionStatus.CANCELED) && (
|
||||
<Tooltip title="删除任务">
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={(e) => { e.stopPropagation(); handleDeleteMission(mission); }}>
|
||||
<DeleteOutlined />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
}]}
|
||||
/>
|
||||
|
||||
{/* 实时位置 */}
|
||||
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
.targetPanel {
|
||||
position: absolute;
|
||||
top: 92px;
|
||||
right: 18px;
|
||||
z-index: 1000;
|
||||
width: 356px;
|
||||
overflow: hidden;
|
||||
color: #f3fbff;
|
||||
background: linear-gradient(155deg, rgba(7, 21, 34, 0.98), rgba(5, 13, 24, 0.98));
|
||||
border: 1px solid rgba(0, 212, 255, 0.42);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 18px 44px rgba(0, 0, 0, 0.52), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 70px;
|
||||
padding: 14px 16px;
|
||||
background: linear-gradient(90deg, rgba(0, 212, 255, 0.13), rgba(0, 212, 255, 0.02));
|
||||
border-bottom: 1px solid rgba(0, 212, 255, 0.2);
|
||||
}
|
||||
|
||||
.eyebrow,
|
||||
.sectionTitle,
|
||||
.label {
|
||||
display: block;
|
||||
color: rgba(164, 220, 239, 0.68);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.9px;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin-top: 3px;
|
||||
color: #ffffff;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.closeButton {
|
||||
display: grid;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
color: rgba(230, 248, 255, 0.72);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.13);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
place-items: center;
|
||||
|
||||
&:hover {
|
||||
color: #ffffff;
|
||||
background: rgba(255, 77, 79, 0.18);
|
||||
border-color: rgba(255, 77, 79, 0.65);
|
||||
}
|
||||
}
|
||||
|
||||
.targetSummary {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
|
||||
.locationIcon {
|
||||
display: grid;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
color: #00d4ff;
|
||||
background: rgba(0, 212, 255, 0.1);
|
||||
border: 1px solid rgba(0, 212, 255, 0.28);
|
||||
border-radius: 8px;
|
||||
font-size: 17px;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.coordinateBlock,
|
||||
.heightBlock {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.coordinate {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
overflow: hidden;
|
||||
color: #72e8ff;
|
||||
font-family: Consolas, 'Courier New', monospace;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.heightBlock {
|
||||
padding-left: 12px;
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
strong {
|
||||
display: block;
|
||||
margin-top: 3px;
|
||||
color: #ffffff;
|
||||
font-family: Consolas, 'Courier New', monospace;
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
small {
|
||||
color: rgba(191, 230, 241, 0.65);
|
||||
font-size: 10px;
|
||||
font-weight: 400;
|
||||
}
|
||||
}
|
||||
|
||||
.riskNotice {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin: 14px 16px 0;
|
||||
padding: 11px 12px;
|
||||
background: rgba(255, 170, 0, 0.1);
|
||||
border: 1px solid rgba(255, 170, 0, 0.38);
|
||||
border-radius: 8px;
|
||||
|
||||
strong {
|
||||
display: block;
|
||||
color: #ffca70;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 5px 0 0;
|
||||
color: rgba(255, 235, 197, 0.75);
|
||||
font-size: 11px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
}
|
||||
|
||||
.warningIcon {
|
||||
margin-top: 2px;
|
||||
color: #ffaa00;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.parameterSection {
|
||||
padding: 15px 16px 12px;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
margin-bottom: 9px;
|
||||
}
|
||||
|
||||
.parameterGrid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.parameterField {
|
||||
position: relative;
|
||||
display: block;
|
||||
padding: 7px 10px 8px;
|
||||
background: rgba(255, 255, 255, 0.035);
|
||||
border: 1px solid rgba(128, 209, 235, 0.18);
|
||||
border-radius: 7px;
|
||||
|
||||
> span {
|
||||
display: block;
|
||||
margin-bottom: 3px;
|
||||
color: rgba(185, 223, 235, 0.64);
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
em {
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
color: rgba(185, 223, 235, 0.6);
|
||||
font-size: 10px;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
:global(.ant-input-number) {
|
||||
width: 100%;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
|
||||
input {
|
||||
height: 21px;
|
||||
padding: 0 26px 0 0;
|
||||
color: #ffffff;
|
||||
font-family: Consolas, 'Courier New', monospace;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.riskCheck {
|
||||
display: flex;
|
||||
margin: 0 16px 14px;
|
||||
color: rgba(230, 245, 250, 0.84);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
|
||||
:global(.ant-checkbox) {
|
||||
top: 2px;
|
||||
}
|
||||
|
||||
:global(.ant-checkbox-inner) {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-color: rgba(130, 222, 248, 0.6);
|
||||
}
|
||||
|
||||
:global(.ant-checkbox-checked .ant-checkbox-inner) {
|
||||
background: #00b8df;
|
||||
border-color: #00b8df;
|
||||
}
|
||||
|
||||
:global(.ant-checkbox + span) {
|
||||
padding-inline-start: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: grid;
|
||||
grid-template-columns: 88px 1fr;
|
||||
gap: 10px;
|
||||
padding: 13px 16px 16px;
|
||||
background: rgba(0, 0, 0, 0.18);
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
|
||||
.discardButton,
|
||||
.sendButton {
|
||||
height: 38px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.discardButton {
|
||||
color: rgba(230, 245, 250, 0.84) !important;
|
||||
background: rgba(255, 255, 255, 0.04) !important;
|
||||
border-color: rgba(255, 255, 255, 0.2) !important;
|
||||
|
||||
&:hover {
|
||||
color: #ffffff !important;
|
||||
background: rgba(255, 77, 79, 0.14) !important;
|
||||
border-color: rgba(255, 77, 79, 0.65) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.sendButton {
|
||||
background: linear-gradient(90deg, #009bc1, #00c7e8) !important;
|
||||
border-color: #20d7f3 !important;
|
||||
box-shadow: 0 0 16px rgba(0, 212, 255, 0.2);
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: linear-gradient(90deg, #00afda, #14d8f7) !important;
|
||||
box-shadow: 0 0 20px rgba(0, 212, 255, 0.38);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
color: rgba(255, 255, 255, 0.55) !important;
|
||||
background: rgba(68, 112, 126, 0.55) !important;
|
||||
border-color: rgba(125, 190, 208, 0.25) !important;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.targetPanel {
|
||||
right: 12px;
|
||||
left: 12px;
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Alert, Button, Checkbox, InputNumber, Modal, Space } from 'antd';
|
||||
import { CloseOutlined, EnvironmentOutlined, SendOutlined, StopOutlined, WarningFilled } from '@ant-design/icons';
|
||||
import type { FlyToPointState, TargetPoint } from '../hooks/useFlyToPoint';
|
||||
import styles from './FlyToPointPanel.less';
|
||||
|
||||
interface FlyToPointPanelProps {
|
||||
visible: boolean;
|
||||
state: FlyToPointState;
|
||||
missionCode: string | null;
|
||||
candidateTarget: TargetPoint | null;
|
||||
currentTarget: TargetPoint | null;
|
||||
distanceToTarget: number;
|
||||
isAirborne: boolean;
|
||||
isSending: boolean;
|
||||
onConfirmStart: () => void;
|
||||
onCancelStart: () => void;
|
||||
onConfirmFly: (clearanceMeters: number, maxSpeed: number, riskAcknowledged: boolean) => void;
|
||||
onCancelTarget: () => void;
|
||||
onEndFlight: () => void;
|
||||
}
|
||||
|
||||
const FlyToPointPanel: React.FC<FlyToPointPanelProps> = ({
|
||||
visible, state, missionCode, candidateTarget, currentTarget, distanceToTarget, isAirborne, isSending,
|
||||
onConfirmStart, onCancelStart, onConfirmFly, onCancelTarget, onEndFlight,
|
||||
}) => {
|
||||
const [clearanceMeters, setClearanceMeters] = useState(30);
|
||||
const [maxSpeed, setMaxSpeed] = useState(12);
|
||||
const [riskAcknowledged, setRiskAcknowledged] = useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (candidateTarget) {
|
||||
setClearanceMeters(candidateTarget.clearanceMeters);
|
||||
setRiskAcknowledged(false);
|
||||
}
|
||||
}, [candidateTarget]);
|
||||
|
||||
const status = state === 'TAKING_OFF' ? '起飞中' : state === 'RETURNING' ? '返航中' : state === 'FLYING_TO'
|
||||
? `飞往已发送目标,距离 ${distanceToTarget.toFixed(0)}m` : '等待地图点选目标';
|
||||
|
||||
return <>
|
||||
{state !== 'IDLE' && state !== 'COMPLETED' && <div style={{ position: 'absolute', top: 10, left: '50%', transform: 'translateX(-50%)', zIndex: 1000, background: 'rgba(0,0,0,.78)', color: '#fff', padding: '8px 14px', borderRadius: 20, display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
<span>指点飞行 | {status}</span>
|
||||
{(state === 'WAITING_TARGET' || state === 'FLYING_TO') && <Button size="small" danger icon={<StopOutlined />} onClick={onEndFlight}>结束飞行</Button>}
|
||||
</div>}
|
||||
|
||||
<Modal title={<Space><EnvironmentOutlined />指点飞行</Space>} open={visible && state === 'IDLE'} onCancel={onCancelStart} footer={<Space><Button onClick={onCancelStart}>取消</Button><Button type="primary" icon={<SendOutlined />} onClick={onConfirmStart}>确认开始</Button></Space>}>
|
||||
<Alert type="info" showIcon message="将创建指点飞行任务" description={isAirborne ? '无人机已升空,确认后可在地图连续点选候选目标。' : '将先自动起飞,升空后可在地图连续点选候选目标。'} />
|
||||
</Modal>
|
||||
|
||||
{candidateTarget && <aside className={styles.targetPanel} aria-label="候选飞行目标确认">
|
||||
<header className={styles.header}>
|
||||
<div>
|
||||
<div className={styles.eyebrow}>POINT-TO-POINT FLIGHT</div>
|
||||
<div className={styles.title}>{currentTarget ? '确认改飞目标' : '确认飞行目标'}</div>
|
||||
</div>
|
||||
<button className={styles.closeButton} type="button" onClick={onCancelTarget} aria-label="丢弃候选目标">
|
||||
<CloseOutlined />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section className={styles.targetSummary}>
|
||||
<div className={styles.locationIcon}><EnvironmentOutlined /></div>
|
||||
<div className={styles.coordinateBlock}>
|
||||
<span className={styles.label}>目标坐标</span>
|
||||
<span className={styles.coordinate}>{candidateTarget.longitude.toFixed(6)}, {candidateTarget.latitude.toFixed(6)}</span>
|
||||
</div>
|
||||
<div className={styles.heightBlock}>
|
||||
<span className={styles.label}>模型高度</span>
|
||||
<strong>{candidateTarget.candidateSurfaceHeight.toFixed(1)}<small> m</small></strong>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className={styles.riskNotice}>
|
||||
<WarningFilled className={styles.warningIcon} />
|
||||
<div>
|
||||
<strong>路径净空尚未完成三维验证</strong>
|
||||
<p>模型表面高度不等于安全飞行高度。下发时将取当前安全高度与目标净空高度中的较大值。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className={styles.parameterSection}>
|
||||
<div className={styles.sectionTitle}>飞行参数</div>
|
||||
<div className={styles.parameterGrid}>
|
||||
<label className={styles.parameterField}>
|
||||
<span>目标净空</span>
|
||||
<InputNumber value={clearanceMeters} min={10} max={200} controls={false} onChange={(v) => setClearanceMeters(v ?? 30)} />
|
||||
<em>m</em>
|
||||
</label>
|
||||
<label className={styles.parameterField}>
|
||||
<span>最大速度</span>
|
||||
<InputNumber value={maxSpeed} min={1} max={15} controls={false} onChange={(v) => setMaxSpeed(v ?? 12)} />
|
||||
<em>m/s</em>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Checkbox className={styles.riskCheck} checked={riskAcknowledged} onChange={(e) => setRiskAcknowledged(e.target.checked)}>
|
||||
我已知晓路径净空未验证,确认继续飞行
|
||||
</Checkbox>
|
||||
|
||||
<footer className={styles.actions}>
|
||||
<Button className={styles.discardButton} onClick={onCancelTarget}>丢弃</Button>
|
||||
<Button className={styles.sendButton} type="primary" loading={isSending} disabled={!riskAcknowledged} icon={<SendOutlined />} onClick={() => onConfirmFly(clearanceMeters, maxSpeed, riskAcknowledged)}>
|
||||
{currentTarget ? '发送改飞' : '发送飞行'}
|
||||
</Button>
|
||||
</footer>
|
||||
</aside>}
|
||||
</>;
|
||||
};
|
||||
|
||||
export default FlyToPointPanel;
|
||||
@@ -0,0 +1,216 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { message } from 'antd';
|
||||
import * as missionApi from '@/services/mission';
|
||||
import type { DroneData } from './useDroneSSE';
|
||||
|
||||
export type FlyToPointState = 'IDLE' | 'TAKING_OFF' | 'WAITING_TARGET' | 'FLYING_TO' | 'RETURNING' | 'COMPLETED';
|
||||
|
||||
export interface TargetPoint {
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
candidateSurfaceHeight: number;
|
||||
clearanceStatus: 'VERIFIED' | 'UNVERIFIED';
|
||||
clearanceMeters: number;
|
||||
}
|
||||
|
||||
const SAFE_HEIGHT = 5;
|
||||
const ARRIVAL_THRESHOLD = 5;
|
||||
const LANDED_THRESHOLD = 2;
|
||||
const DEFAULT_CLEARANCE = 30;
|
||||
|
||||
export function useFlyToPoint(droneData: DroneData | null, onStarted?: (deviceSn: string) => void, isDroneInDock?: boolean) {
|
||||
const [state, setState] = useState<FlyToPointState>('IDLE');
|
||||
const [missionCode, setMissionCode] = useState<string | null>(null);
|
||||
const [deviceSn, setDeviceSn] = useState<string | null>(null);
|
||||
const [candidateTarget, setCandidateTarget] = useState<TargetPoint | null>(null);
|
||||
const [currentTarget, setCurrentTarget] = useState<TargetPoint | null>(null);
|
||||
const [distanceToTarget, setDistanceToTarget] = useState(0);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
|
||||
const stateRef = useRef(state);
|
||||
const candidateRef = useRef(candidateTarget);
|
||||
const targetRef = useRef(currentTarget);
|
||||
const missionCodeRef = useRef(missionCode);
|
||||
const takeoffElevationRef = useRef<number>(0); // 记录起飞时的椭球高
|
||||
const returnTimerRef = useRef<NodeJS.Timeout | null>(null); // 返航超时兜底
|
||||
stateRef.current = state;
|
||||
candidateRef.current = candidateTarget;
|
||||
targetRef.current = currentTarget;
|
||||
missionCodeRef.current = missionCode;
|
||||
|
||||
const startFlyToPoint = useCallback(async (sn: string, dockLat?: number, dockLng?: number, dockH?: number) => {
|
||||
try {
|
||||
setState('TAKING_OFF');
|
||||
setDeviceSn(sn);
|
||||
takeoffElevationRef.current = droneData?.elevation ?? droneData?.height ?? 0;
|
||||
const res = await missionApi.startFlyToPoint({
|
||||
deviceSn: sn,
|
||||
dockLatitude: dockLat,
|
||||
dockLongitude: dockLng,
|
||||
dockHeight: dockH,
|
||||
isAirborne: (droneData?.height ?? 0) > SAFE_HEIGHT || ((droneData?.elevation ?? 0) - takeoffElevationRef.current) > SAFE_HEIGHT,
|
||||
});
|
||||
if (res?.resp_code !== 0 || !res?.data?.missionCode) {
|
||||
throw new Error(res?.resp_msg || '启动失败');
|
||||
}
|
||||
setMissionCode(res.data.missionCode);
|
||||
if ((droneData?.height ?? 0) > SAFE_HEIGHT) setState('WAITING_TARGET');
|
||||
onStarted?.(sn);
|
||||
message.success('指点飞行任务已启动');
|
||||
} catch (error: any) {
|
||||
message.error(`开始指点飞行失败:${error?.message || '请重试'}`);
|
||||
setState('IDLE');
|
||||
setDeviceSn(null);
|
||||
}
|
||||
}, [droneData, onStarted]);
|
||||
|
||||
const selectTarget = useCallback((longitude: number, latitude: number, candidateSurfaceHeight: number) => {
|
||||
if (!['TAKING_OFF', 'WAITING_TARGET', 'FLYING_TO'].includes(stateRef.current)) return;
|
||||
// 第一版不把不可验证的模型表面伪装成已验证的安全路径。
|
||||
setCandidateTarget({
|
||||
longitude,
|
||||
latitude,
|
||||
candidateSurfaceHeight,
|
||||
clearanceStatus: 'UNVERIFIED',
|
||||
clearanceMeters: DEFAULT_CLEARANCE,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const cancelTarget = useCallback(() => setCandidateTarget(null), []);
|
||||
|
||||
const confirmFly = useCallback(async (clearanceMeters: number, maxSpeed = 12, riskAcknowledged = false) => {
|
||||
const target = candidateRef.current;
|
||||
const code = missionCodeRef.current;
|
||||
if (!target || !code) return;
|
||||
if (!riskAcknowledged && target.clearanceStatus !== 'VERIFIED') {
|
||||
message.warning('请确认路径净空尚未验证的飞行风险');
|
||||
return;
|
||||
}
|
||||
|
||||
// 高度以当前无人机椭球高度为下限,模型命中高度仅作为障碍物顶高度候选。
|
||||
const targetEllipsoidHeight = Math.max(
|
||||
droneData?.elevation ?? Number.NEGATIVE_INFINITY,
|
||||
target.candidateSurfaceHeight + clearanceMeters,
|
||||
);
|
||||
if (!Number.isFinite(targetEllipsoidHeight)) {
|
||||
message.error('缺少无人机高度和模型高度,无法计算安全目标高度');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSending(true);
|
||||
try {
|
||||
const res = await missionApi.flyToPointUpdate({
|
||||
missionCode: code,
|
||||
latitude: target.latitude,
|
||||
longitude: target.longitude,
|
||||
height: targetEllipsoidHeight,
|
||||
maxSpeed,
|
||||
clearanceStatus: target.clearanceStatus,
|
||||
clearanceMeters,
|
||||
candidateSurfaceHeight: target.candidateSurfaceHeight,
|
||||
riskAcknowledged,
|
||||
riskReason: target.clearanceStatus === 'VERIFIED' ? undefined : '路径净空尚未完成三维验证',
|
||||
});
|
||||
if (res?.resp_code !== 0) throw new Error(res?.resp_msg || '命令发送失败');
|
||||
setCurrentTarget({ ...target, clearanceMeters });
|
||||
setCandidateTarget(null);
|
||||
setState('FLYING_TO');
|
||||
message.success(currentTarget ? '已发送改飞指令' : '已发送飞往目标指令');
|
||||
} catch (error: any) {
|
||||
message.error(`发送目标失败:${error?.message || '请重试'}`);
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
}, [droneData, currentTarget]);
|
||||
|
||||
const endFlight = useCallback(async () => {
|
||||
const code = missionCodeRef.current;
|
||||
if (!code) return;
|
||||
setState('RETURNING');
|
||||
try {
|
||||
const res = await missionApi.endFlyToPoint(code);
|
||||
if (res?.resp_code !== 0) throw new Error(res?.resp_msg || '结束失败');
|
||||
setCandidateTarget(null);
|
||||
message.success('正在返航,等待降落');
|
||||
} catch (error: any) {
|
||||
message.error(`结束飞行失败:${error?.message || '请重试'}`);
|
||||
setState(currentTarget ? 'FLYING_TO' : 'WAITING_TARGET');
|
||||
}
|
||||
}, [currentTarget]);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
setState('IDLE');
|
||||
setMissionCode(null);
|
||||
setDeviceSn(null);
|
||||
setCandidateTarget(null);
|
||||
setCurrentTarget(null);
|
||||
setDistanceToTarget(0);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// RETURNING 超时兜底:120 秒后自动完成(SSE 断流时也能正常结束)
|
||||
if (stateRef.current === 'RETURNING' && !returnTimerRef.current) {
|
||||
returnTimerRef.current = setTimeout(() => {
|
||||
if (stateRef.current === 'RETURNING' && missionCodeRef.current) {
|
||||
missionApi.completeMission(missionCodeRef.current).finally(() => {
|
||||
setState('COMPLETED');
|
||||
message.success('指点飞行完成(超时自动结束)');
|
||||
});
|
||||
}
|
||||
}, 120_000);
|
||||
}
|
||||
if (stateRef.current !== 'RETURNING' && returnTimerRef.current) {
|
||||
clearTimeout(returnTimerRef.current);
|
||||
returnTimerRef.current = null;
|
||||
}
|
||||
|
||||
if (!droneData) return;
|
||||
const relHeight = droneData.height ?? 0;
|
||||
const elevation = droneData.elevation ?? 0;
|
||||
// 起飞检测:相对高度 > 5m,或椭球高相对起飞基准升高 > 5m
|
||||
const isAirborne = relHeight > SAFE_HEIGHT || (elevation - takeoffElevationRef.current) > SAFE_HEIGHT;
|
||||
const target = targetRef.current;
|
||||
if (stateRef.current === 'TAKING_OFF' && isAirborne) {
|
||||
setState('WAITING_TARGET');
|
||||
message.success('无人机已升空,请在地图上点击候选目标');
|
||||
}
|
||||
if (stateRef.current === 'FLYING_TO' && target && droneData.latitude != null && droneData.longitude != null) {
|
||||
const distance = getHorizontalDistance(droneData.latitude, droneData.longitude, target.latitude, target.longitude);
|
||||
setDistanceToTarget(distance);
|
||||
if (distance < ARRIVAL_THRESHOLD) {
|
||||
setState('WAITING_TARGET');
|
||||
setCurrentTarget(null);
|
||||
message.success('已到达目标位置,可继续点选下一个目标');
|
||||
}
|
||||
}
|
||||
// RETURNING 状态:检测无人机是否已回库
|
||||
// elevation 回到起飞基准附近 + 相对高度接近0,判定回库
|
||||
const elevBackToBase = Math.abs(elevation - takeoffElevationRef.current) < 3;
|
||||
const hasLanded = relHeight < 3;
|
||||
if (stateRef.current === 'RETURNING' && (isDroneInDock || elevBackToBase || hasLanded) && missionCodeRef.current) {
|
||||
missionApi.completeMission(missionCodeRef.current).finally(() => {
|
||||
setState('COMPLETED');
|
||||
message.success('指点飞行完成,无人机已回库');
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
if (returnTimerRef.current) {
|
||||
clearTimeout(returnTimerRef.current);
|
||||
returnTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [droneData]);
|
||||
|
||||
return {
|
||||
state, missionCode, deviceSn, candidateTarget, currentTarget, distanceToTarget, isSending,
|
||||
startFlyToPoint, selectTarget, cancelTarget, confirmFly, endFlight, cancel,
|
||||
isAirborne: (droneData?.height ?? 0) > SAFE_HEIGHT || ((droneData?.elevation ?? 0) - takeoffElevationRef.current) > SAFE_HEIGHT,
|
||||
};
|
||||
}
|
||||
|
||||
function getHorizontalDistance(lat1: number, lng1: number, lat2: number, lng2: number): number {
|
||||
const dLat = ((lat2 - lat1) * Math.PI) / 180;
|
||||
const dLng = ((lng2 - lng1) * Math.PI) / 180;
|
||||
const a = Math.sin(dLat / 2) ** 2 + Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLng / 2) ** 2;
|
||||
return 6371000 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
}
|
||||
+13
-5
@@ -93,16 +93,19 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
});
|
||||
|
||||
try {
|
||||
// 处理跨域问题:非 localhost 访问时将 CDN URL 转换为代理路径
|
||||
// 处理跨域问题:将 CDN URL 转换为代理路径(始终使用代理,避免 CORS)
|
||||
let tilesetUrl = config.url;
|
||||
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
|
||||
if (!isLocalhost && tilesetUrl.includes('minicdn.goflytec.com')) {
|
||||
if (tilesetUrl.includes('minicdn.goflytec.com')) {
|
||||
tilesetUrl = tilesetUrl.replace('https://minicdn.goflytec.com', '');
|
||||
console.log('[Tileset] 使用代理路径:', tilesetUrl);
|
||||
}
|
||||
|
||||
// 使用 Resource 显式设置 baseUrl,确保外部 tileset 引用的相对路径正确解析
|
||||
const resource = Cesium.Resource.createIfNeeded(tilesetUrl);
|
||||
console.log('[Tileset] Resource URL:', resource.url, 'baseUrl:', resource.baseUrl);
|
||||
|
||||
// 创建3DTileset - 高清晰度渲染配置
|
||||
const tileset = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, {
|
||||
const tileset = await Cesium.Cesium3DTileset.fromUrl(resource, {
|
||||
// 核心清晰度控制 - 值越小越清晰(大疆司空使用约1-2)
|
||||
maximumScreenSpaceError: config.style?.maximumScreenSpaceError ?? 1,
|
||||
maximumMemoryUsage: config.style?.maximumMemoryUsage ?? 2048, // 增加内存以加载更多高精度瓦片
|
||||
@@ -127,7 +130,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
foveatedMinimumScreenSpaceErrorRelaxation: 0.0,
|
||||
|
||||
// 裁剪优化 - 减少移动时的清晰度降低
|
||||
cullWithChildrenBounds: true,
|
||||
cullWithChildrenBounds: false, // 外部 tileset 引用的模型必须关闭,否则子 tileset 会被错误裁剪
|
||||
cullRequestsWhileMoving: false, // 禁用移动时的请求裁剪
|
||||
cullRequestsWhileMovingMultiplier: 1.0,
|
||||
|
||||
@@ -154,6 +157,11 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
|
||||
});
|
||||
});
|
||||
|
||||
// 监听瓦片加载失败(外部 tileset 引用失败会在这里体现)
|
||||
tileset.tileFailed.addEventListener((error: any) => {
|
||||
console.error(`[Tileset] 模型 [${config.name}] 瓦片加载失败:`, error);
|
||||
});
|
||||
|
||||
// 模型位置调整 - 根据当前地形类型选择对应的高度偏移
|
||||
if (config.position) {
|
||||
const { longitude = 0, latitude = 0, cesiumHeight, arcgisHeight } = config.position;
|
||||
|
||||
@@ -9,6 +9,8 @@ import RouteEditor from '../RouteEditor';
|
||||
import BoundaryEditor from '../BoundaryEditor';
|
||||
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
|
||||
import { useDroneSSE } from './3d/hooks/useDroneSSE';
|
||||
import { useFlyToPoint } from './3d/hooks/useFlyToPoint';
|
||||
import FlyToPointPanel from './3d/components/FlyToPointPanel';
|
||||
import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel';
|
||||
import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel";
|
||||
|
||||
@@ -21,6 +23,24 @@ const DEFAULT_GLOBAL_VIEW = {
|
||||
height: 19000000,
|
||||
};
|
||||
|
||||
const TERRAIN_LOAD_TIMEOUT_MS = 8000;
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, providerName: string): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => reject(new Error(`${providerName} 地形服务连接超时`)), TERRAIN_LOAD_TIMEOUT_MS);
|
||||
promise.then(
|
||||
value => {
|
||||
window.clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
error => {
|
||||
window.clearTimeout(timer);
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
interface CesiumContainerProps {
|
||||
deviceList: any[];
|
||||
externalSelectedDevice?: any; // 接收外部选择的设备
|
||||
@@ -66,6 +86,49 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
const [droneDeviceSn, setDroneDeviceSn] = useState<string>('');
|
||||
const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE();
|
||||
|
||||
// 指点飞行
|
||||
const flyToPointStartedRef = useRef<(deviceSn: string) => void>();
|
||||
|
||||
// 无人机在库状态(来自实时数据)
|
||||
const isDroneInDock = useMemo(
|
||||
() => controlRealtimeData?.rawData?.dockData?.drone_in_dock === 1,
|
||||
[controlRealtimeData]
|
||||
);
|
||||
|
||||
const flyToPoint = useFlyToPoint(droneData, (deviceSn) => flyToPointStartedRef.current?.(deviceSn), isDroneInDock);
|
||||
const [flyToPointStartVisible, setFlyToPointStartVisible] = useState(false);
|
||||
const [pendingFlyDeviceSn, setPendingFlyDeviceSn] = useState<string | null>(null);
|
||||
const [pendingDockCoords, setPendingDockCoords] = useState<{lat?: number; lng?: number; height?: number}>({});
|
||||
|
||||
// 激活指点飞行(从 RightPanel 按钮触发,仅打开确认弹窗)
|
||||
const handleFlyToPointActivate = useCallback((deviceSn: string, dockLat?: number, dockLng?: number, dockH?: number) => {
|
||||
setPendingFlyDeviceSn(deviceSn);
|
||||
setPendingDockCoords({ lat: dockLat, lng: dockLng, height: dockH });
|
||||
setFlyToPointStartVisible(true);
|
||||
}, []);
|
||||
|
||||
// 确认开始指点飞行
|
||||
const handleFlyToPointConfirm = useCallback(() => {
|
||||
setFlyToPointStartVisible(false);
|
||||
if (pendingFlyDeviceSn) {
|
||||
flyToPoint.startFlyToPoint(pendingFlyDeviceSn, pendingDockCoords.lat, pendingDockCoords.lng, pendingDockCoords.height);
|
||||
setPendingFlyDeviceSn(null);
|
||||
setPendingDockCoords({});
|
||||
}
|
||||
}, [pendingFlyDeviceSn, pendingDockCoords, flyToPoint]);
|
||||
|
||||
// 取消指点飞行
|
||||
const handleFlyToPointCancel = useCallback(() => {
|
||||
setFlyToPointStartVisible(false);
|
||||
setPendingFlyDeviceSn(null);
|
||||
}, []);
|
||||
|
||||
// 指点飞行目标标记实体 ref
|
||||
const flyTargetEntityRef = useRef<any>(null);
|
||||
const flyCandidateEntityRef = useRef<any>(null);
|
||||
const flyToPointStateRef = useRef(flyToPoint.state);
|
||||
flyToPointStateRef.current = flyToPoint.state;
|
||||
|
||||
// 无人机位置渲染相关引用
|
||||
const droneEntityRef = useRef<any>(null);
|
||||
const flightTrackEntityRef = useRef<any>(null);
|
||||
@@ -80,6 +143,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
const [modelLoading, setModelLoading] = useState(false);
|
||||
const [terrainLoading, setTerrainLoading] = useState(false); // 是否正在加载高程地形
|
||||
const terrainLoadedRef = useRef(false); // 是否已加载高程地形
|
||||
const terrainRequestIdRef = useRef(0);
|
||||
const {
|
||||
tilesets,
|
||||
loadTileset,
|
||||
@@ -143,6 +207,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
return 'loaded';
|
||||
}
|
||||
|
||||
const requestId = ++terrainRequestIdRef.current;
|
||||
setTerrainLoading(true);
|
||||
console.log('开始加载高程地形...', preferredTerrainType ? `优先使用: ${preferredTerrainType}` : '');
|
||||
|
||||
@@ -152,9 +217,9 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
if (preferredTerrainType === 'arcgis') {
|
||||
// 优先尝试 ArcGIS
|
||||
try {
|
||||
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
const terrainProvider = await withTimeout(Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
), 'ArcGIS');
|
||||
console.log('高程地形加载成功: ArcGIS World Elevation (根据模型配置)');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
@@ -163,10 +228,10 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
} catch (arcgisError) {
|
||||
console.warn('ArcGIS 加载失败,尝试 Cesium Ion:', arcgisError);
|
||||
try {
|
||||
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
const terrainProvider = await withTimeout(Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: true,
|
||||
});
|
||||
}), 'Cesium Ion');
|
||||
console.log('高程地形加载成功: Cesium World Terrain (备用)');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
@@ -181,10 +246,10 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
} else {
|
||||
// 默认优先尝试 Cesium Ion
|
||||
try {
|
||||
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
const terrainProvider = await withTimeout(Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: true,
|
||||
});
|
||||
}), 'Cesium Ion');
|
||||
console.log('高程地形加载成功: Cesium World Terrain');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
@@ -193,9 +258,9 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
} catch (cesiumError) {
|
||||
console.warn('Cesium World Terrain 加载失败,尝试 ArcGIS:', cesiumError);
|
||||
try {
|
||||
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
const terrainProvider = await withTimeout(Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
), 'ArcGIS');
|
||||
console.log('高程地形加载成功: ArcGIS World Elevation');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
@@ -211,7 +276,9 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
}
|
||||
}
|
||||
|
||||
setTerrainLoading(false);
|
||||
if (terrainRequestIdRef.current === requestId) {
|
||||
setTerrainLoading(false);
|
||||
}
|
||||
return loadedTerrainType;
|
||||
}, []);
|
||||
|
||||
@@ -391,6 +458,18 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
}
|
||||
}, [droneDeviceSn, disconnectDroneSSE, connectDroneSSE, clearDroneLayers]);
|
||||
|
||||
flyToPointStartedRef.current = (deviceSn: string) => {
|
||||
const device = selectedDevice?.deviceSn === deviceSn ? selectedDevice : { deviceSn };
|
||||
setRightPanelVisible(false);
|
||||
handleOpenControl(device, controlRealtimeData);
|
||||
};
|
||||
|
||||
// 一键起飞成功后切换到操控台,便于立即查看视频和实时飞行状态。
|
||||
const handleTakeoffSuccess = useCallback((device: any, realtimeData: any) => {
|
||||
setRightPanelVisible(false);
|
||||
handleOpenControl(device, realtimeData);
|
||||
}, [handleOpenControl]);
|
||||
|
||||
// 关闭操控台 - 断开无人机SSE
|
||||
const handleCloseControl = useCallback(() => {
|
||||
setLeftPanelVisible(false);
|
||||
@@ -936,6 +1015,47 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
}
|
||||
|
||||
handler.setInputAction((movement: any) => {
|
||||
// 指点飞行模式:优先处理地图点击
|
||||
if (['TAKING_OFF', 'WAITING_TARGET', 'FLYING_TO'].includes(flyToPointStateRef.current)) {
|
||||
const cartesian = viewer.scene.pickPosition(movement.position);
|
||||
if (Cesium.defined(cartesian)) {
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
|
||||
const lng = Cesium.Math.toDegrees(cartographic.longitude);
|
||||
const lat = Cesium.Math.toDegrees(cartographic.latitude);
|
||||
const cartographicHeight = cartographic.height; // WGS84 椭球高
|
||||
|
||||
// 蓝色标记表示尚未发送的候选点,避免与当前飞行目标混淆。
|
||||
if (flyCandidateEntityRef.current) {
|
||||
viewer.entities.remove(flyCandidateEntityRef.current);
|
||||
}
|
||||
flyCandidateEntityRef.current = viewer.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(lng, lat, cartographicHeight),
|
||||
point: {
|
||||
pixelSize: 16,
|
||||
color: Cesium.Color.CYAN,
|
||||
outlineColor: Cesium.Color.WHITE,
|
||||
outlineWidth: 2,
|
||||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
},
|
||||
label: {
|
||||
text: '候选目标(未发送)',
|
||||
font: '14px sans-serif',
|
||||
fillColor: Cesium.Color.CYAN,
|
||||
outlineColor: Cesium.Color.WHITE,
|
||||
outlineWidth: 2,
|
||||
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
|
||||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||||
pixelOffset: new Cesium.Cartesian2(0, -20),
|
||||
},
|
||||
});
|
||||
|
||||
flyToPoint.selectTarget(lng, lat, cartographicHeight);
|
||||
return; // 不执行设备选择逻辑
|
||||
}
|
||||
message.info('未能获取目标表面高度,请选择可见模型或地形位置');
|
||||
return;
|
||||
}
|
||||
|
||||
const pickedObject = viewer.scene.pick(movement.position);
|
||||
if (Cesium.defined(pickedObject) && pickedObject.id) {
|
||||
const entity = pickedObject.id;
|
||||
@@ -974,6 +1094,27 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
};
|
||||
}, [loading, handleDeviceSelect]);
|
||||
|
||||
useEffect(() => {
|
||||
const viewer = viewerRef.current;
|
||||
if (!viewer || !Cesium) return;
|
||||
if (!flyToPoint.candidateTarget && flyCandidateEntityRef.current) {
|
||||
viewer.entities.remove(flyCandidateEntityRef.current);
|
||||
flyCandidateEntityRef.current = null;
|
||||
}
|
||||
if (flyTargetEntityRef.current) {
|
||||
viewer.entities.remove(flyTargetEntityRef.current);
|
||||
flyTargetEntityRef.current = null;
|
||||
}
|
||||
const target = flyToPoint.currentTarget;
|
||||
if (target) {
|
||||
flyTargetEntityRef.current = viewer.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(target.longitude, target.latitude, target.candidateSurfaceHeight),
|
||||
point: { pixelSize: 15, color: Cesium.Color.ORANGE, outlineColor: Cesium.Color.WHITE, outlineWidth: 2, heightReference: Cesium.HeightReference.CLAMP_TO_GROUND },
|
||||
label: { text: '当前飞行目标', font: '14px sans-serif', fillColor: Cesium.Color.ORANGE, outlineColor: Cesium.Color.WHITE, outlineWidth: 2, style: Cesium.LabelStyle.FILL_AND_OUTLINE, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, pixelOffset: new Cesium.Cartesian2(0, -20) },
|
||||
});
|
||||
}
|
||||
}, [flyToPoint.candidateTarget, flyToPoint.currentTarget]);
|
||||
|
||||
// @ts-ignore
|
||||
return (
|
||||
<div style={{ width: '100%', height: '100%', position: 'relative' }}>
|
||||
@@ -1144,12 +1285,32 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
onClose={handleRightPanelClose}
|
||||
onMinimize={handleRightPanelMinimize}
|
||||
onControlClick={handleOpenControl}
|
||||
onTakeoffSuccess={handleTakeoffSuccess}
|
||||
onTaskPanelOpen={handleOpenTaskPanel}
|
||||
onRoutePlanningOpen={handleOpenRoutePlanning}
|
||||
onFlyToPointActivate={handleFlyToPointActivate}
|
||||
flyToPointState={flyToPoint.state}
|
||||
viewer={viewerRef.current}
|
||||
Cesium={Cesium}
|
||||
/>
|
||||
|
||||
{/* 指点飞行面板 */}
|
||||
<FlyToPointPanel
|
||||
visible={flyToPointStartVisible}
|
||||
state={flyToPoint.state}
|
||||
missionCode={flyToPoint.missionCode}
|
||||
candidateTarget={flyToPoint.candidateTarget}
|
||||
currentTarget={flyToPoint.currentTarget}
|
||||
distanceToTarget={flyToPoint.distanceToTarget}
|
||||
isAirborne={flyToPoint.isAirborne}
|
||||
isSending={flyToPoint.isSending}
|
||||
onConfirmStart={handleFlyToPointConfirm}
|
||||
onCancelStart={handleFlyToPointCancel}
|
||||
onConfirmFly={flyToPoint.confirmFly}
|
||||
onCancelTarget={flyToPoint.cancelTarget}
|
||||
onEndFlight={flyToPoint.endFlight}
|
||||
/>
|
||||
|
||||
{/* 任务管理面板 - 左下角独立渲染 */}
|
||||
<TaskPanel
|
||||
visible={taskPanelVisible}
|
||||
|
||||
@@ -142,6 +142,18 @@ export const deviceApi = {
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 切换直播镜头(如 zoom / wide / normal / ir)
|
||||
liveLensChange: async (params: { deviceSn: string; videoType: 'zoom' | 'wide' | 'normal' | 'ir' }): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/liveLensChange', { method: 'POST', data: params });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 设置变焦倍数(2~200)
|
||||
cameraFocalLengthSet: async (params: { deviceSn: string; zoomFactor: number }): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/cameraFocalLengthSet', { method: 'POST', data: params });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 订阅无人机遥测
|
||||
subscribeDroneTelemetry: async (deviceSn: string): Promise<{ success: boolean; message?: string }> => {
|
||||
try {
|
||||
|
||||
@@ -6,6 +6,8 @@ import { request } from 'umi';
|
||||
export enum MissionType {
|
||||
WAYLINE = 1, // 航线任务
|
||||
TAKEOFF = 2, // 一键起飞任务
|
||||
BOAT_ROUTE = 3, // 无人船航线任务
|
||||
FLY_TO_POINT = 4, // 指点飞行任务
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -26,6 +28,8 @@ export enum MissionStatus {
|
||||
export const MissionTypeMap: Record<number, string> = {
|
||||
[MissionType.WAYLINE]: '航线任务',
|
||||
[MissionType.TAKEOFF]: '一键起飞',
|
||||
[MissionType.BOAT_ROUTE]: '无人船航线',
|
||||
[MissionType.FLY_TO_POINT]: '指点飞行',
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -274,3 +278,52 @@ export async function countMissionImage(missionCode: string) {
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 指点飞行编排接口 ====================
|
||||
|
||||
/**
|
||||
* 开始指点飞行
|
||||
*/
|
||||
export async function startFlyToPoint(params: {
|
||||
deviceSn: string;
|
||||
dockLatitude?: number;
|
||||
dockLongitude?: number;
|
||||
dockHeight?: number;
|
||||
isAirborne?: boolean;
|
||||
}) {
|
||||
return request<API.Result<{ missionCode: string }>>('/api-order/mission/startFlyToPoint', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新指点飞行目标点
|
||||
*/
|
||||
export async function flyToPointUpdate(params: {
|
||||
missionCode: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
height: number;
|
||||
maxSpeed?: number;
|
||||
clearanceStatus: 'VERIFIED' | 'UNVERIFIED';
|
||||
clearanceMeters?: number;
|
||||
candidateSurfaceHeight?: number;
|
||||
riskAcknowledged: boolean;
|
||||
riskReason?: string;
|
||||
}) {
|
||||
return request<API.Result<string>>('/api-order/mission/flyToPointUpdate', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束指点飞行
|
||||
*/
|
||||
export async function endFlyToPoint(missionCode: string) {
|
||||
return request<API.Result<string>>('/api-order/mission/endFlyToPoint', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user