feat: 3d控制指令

This commit is contained in:
2025-12-11 12:11:48 +08:00
parent 358639a8ac
commit 4921ab15ce
29 changed files with 3383 additions and 204 deletions
+3 -1
View File
@@ -54,7 +54,9 @@
"Bash(curl:*)",
"Bash(del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\service\\MinioModelUploadService.java\")",
"Bash(cmd /c \"dir /s /b \"\"D:\\模型\\新建模型重建-2025-09-29 20_24_08 (UTC+08)\\model\\download\"\"\")",
"Bash(cmd /c \"dir \"\"D:\\模型\\新建模型重建-2025-09-29 20_24_08 (UTC+08)\\model\\download\"\"\")"
"Bash(cmd /c \"dir \"\"D:\\模型\\新建模型重建-2025-09-29 20_24_08 (UTC+08)\\model\\download\"\"\")",
"Bash(del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\websocket\\config\\DeviceControlWebSocketConfig.java\")",
"Bash(del \"F:\\project\\go-fly-platform-services\\zlt-web\\react-web-next\\src\\services\\deviceControlWs.ts\")"
],
"deny": [],
"ask": []
@@ -0,0 +1,307 @@
**指令飞行**
websocket发送指令json格式
```
{
"type": "sub",
"topic": "/device-message-sender/D-Dock2/deviceSn",
"parameter": {
"messageType":"WRITE_PROPERTY",
"properties": {指令json},
"headers":{
"async":false
}
},
"id": "request-id-ceshi123-2222"
}
```
**一键起飞**
Topic: /write-property
Direction: down
Method: takeoff_to_point
Data:
| | | | | |
| --- | --- | --- | --- | --- |
| **Column** | **Name** | **Type** | **constraint** | **Description** |
| target_latitude | 目标点纬度 | double | {"max":90,"min":-90} | 目标点纬度,角度值,南纬是负,北纬是正,精度到小数点后6位 |
| target_longitude | 目标点经度 | double | {"max":180,"min":-180} | 目标点经度,角度值,东经是正,西经是负,精度到小数点后6位 |
| target_height | 目标点高度 | float | {"max":1500,"min":2,"step":0.1,"unit_name":"米 / m"} | 目标点高度(椭球高),使用 WGS84 模型,飞行器到点后默认行为:悬停 |
| security_takeoff_height | 安全起飞高度 | float | {"max":1500,"min":20,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度(ALT),飞行器先升到特定的高度,然后再飞向目标点。 |
| rth_mode | 返航模式设置值 | enum_int | {"0":"智能高度","1":"设定高度"} | 智能返航模式下,飞行器将自动规划最佳返航高度。大疆机场当前不支持设置返航高度模式,只能选择'设定高度'模式。当环境,光线不满足视觉系统要求时(譬如傍晚阳光直射、夜间弱光无光),飞行器将使用您设定的返航高度进行直线返航 |
| rth_altitude | 返航高度 | int | {"max":1500,"min":2,"step":1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT |
| rc_lost_action | 遥控器失控动作 | enum_int | {"0":"悬停","1":"着陆(降落)","2":"返航"} | 遥控器失控动作 |
| commander_mode_lost_action | 指点飞行失控动作 | enum_int | {"0":"继续执行指点飞行任务","1":"退出指点飞行任务,执行普通失控行为"} | |
| commander_flight_mode | 指点飞行模式设置值 | enum_int | {"0":"智能高度飞行","1":"设定高度飞行"} | |
| commander_flight_height | 指点飞行高度 | float | {"max":3000,"min":2,"step":0.1,"unit_name":"米 / m"} | 相对(机场)起飞点的高度,相对高 ALT |
| flight_id | 一键起飞任务 UUID | text | | 任务 UUID,全局唯一,用于染色,云端区分该值是普通计划任务还是一键起飞任务 |
| max_speed | 一键起飞的飞行过程中能达到的最大速度 | int | {"max":15,"min":1,"unit_name":"米每秒 / m/s"} | |
| simulate_mission | 是否在模拟器中执行任务 | struct | | 可选字段,用于在室内进行模拟任务调试。 <br>注意:进行模拟飞行前,请务必取下桨叶,以防舱盖关闭时夹断桨叶。 |
| »is_enable | 是否开启模拟器任务 | enum_int | {"0":"不开启","1":"开启"} | 当次任务打开或关闭模拟器 |
| »latitude | 纬度 | double | {"max":"90.0","min":"-90.0"} | |
| »longitude | 经度 | double | {"max":"180.0","min":"-180.0"} | |
| flight_safety_advance_check | 飞行安全预检查 | bool | {"0":"关闭","1":"开启"} | 设置一键起飞和航线任务中的飞行安全是否预先检查。此字段为可选,默认为0,值为0表示关闭,1表示开启。飞行安全预先检查表示: 飞行器执行任务前,检查自身作业区文件是否与云端一致,如果不一致则拉取文件更新,如果一致则不处理 |
Example:
JSON
```
{
"method": "takeoff_to_point",
"data": {
"data": {
"rth_altitude": 50,
"target_latitude": 31.2120679,
"rth_mode": 1,
"commander_flight_mode": 1,
"flight_safety_advance_check": 0,
"max_speed": 5,
"security_takeoff_height": 50,
"flight_id": "ABDEAC21DCADDA",
"commander_mode_lost_action": 1,
"target_height": 322.63797,
"commander_flight_height": 50,
"rc_lost_action": 2,
"target_longitude": 110.86967
}
}
}
```
**一键返航**
Topic: /write-property
Direction: down
Method: return_home
Data: null
JSON
{
"data": {
},
"method": "return_home"
}
**返航取消**
Topic: /write-property
Direction: down
Method: return_home_cancel
Data: null
JSON
{
"data": {
},
"method": "return_home_cancel"
}
**航线恢复**
Topic: /write-property
Direction: down
Method: flighttask_recovery
Data: null
Example:
JSON
{
"data": {
},
"method": "flighttask_recovery"
}
**航线暂停**
Topic: /write-property
Direction: down
Method: flighttask_pause
Data: null
Example:
JSON
{
"data": {
},
"method": "flighttask_pause"
}
**进入指令飞行模式**
Topic: /write-property
Direction: down
Method: drc_mode_enter
Data: null
Example:
JSON
{
"data": {
},
"method": "drc_mode_enter"
}
**负载控制—画面拖动控制**
Topic: /write-property
Direction: down
Method: camera_screen_drag
Data:
| | | | | |
| --- | --- | --- | --- | --- |
| **Column** | **Name** | **Type** | **constraint** | **Description** |
| locked | 机头和云台的相对关系是否锁定 | bool | {"false":"仅云台转,机身不转","true":"锁定机头,云台和机身一起转"} | |
| pitch_speed | 云台 pitch 速度 | double | {"unit_name":"度每秒 / degree/s"} | 云台 pitch 速度 |
| yaw_speed | 云台 yaw 速度 | double | {"unit_name":"度每秒 / degree/s"} | 云台 yaw 速度,仅不锁机头时才生效 |
Example:
JSON
{
"data": {
"pitch_speed": 10,
"yaw_speed": -10,
"locked": false
},
"method": "stick_control"
}
**切换相机模式**
Topic: /write-property
Direction: down
Method: camera_mode_switch
Data:
| | | | | |
| --- | --- | --- | --- | --- |
| **Column** | **Name** | **Type** | **constraint** | **Description** |
| camera_mode | 相机模式 | enum_int | {"0":"拍照","1":"录像","2":"智能低光","3":"全景拍照"} | |
Example:
JSON
{
"data": {
"camera_mode": 0,
},
"method": "camera_mode_switch"
}
**开始拍照**
Topic: /write-property
Direction: down
Method: camera_photo_take
Data: null
Example:
JSON
{
"data": {
},
"method": "camera_photo_take"
}
**开始录像**
Topic: /write-property
Direction: down
Method: camera_recording_start
Data: null
Example:
JSON
{
"data": {
},
"method": "camera_recording_start"
}
**停止录像**
Topic: /write-property
Direction: down
Method: camera_recording_stop
Data: null
Example:
JSON
{
"data": {
},
"method": "camera_recording_stop"
}
**DRC-杆量控制**
建立DRC链路之后,可通过“DRC-杆量控制”指令控制飞行器和云台姿态。发送频率需要保持5-10hz,才能比较精准地控制飞行器的运动。本协议无回包机制。
Topic: /write-property
Direction: down
Method: stick_control
Data:
| | | | | | |
| --- | --- | --- | --- | --- | --- |
| **Column** | **Name** | **Type** | **constraint** | **Description** | **remark** |
| roll | 横滚通道 | int | {"max":"1424","min":"624","unit_name":""} | 对应遥控器A通道,控制飞行器横滚(表现为左右平移)。杆量范围\[1024±400\],1024为中值(无动作),数值增大表示向右倾斜,减小表示向左倾斜。 | \>1074判定为1424 <974判定为624,每次下发持续10s |
| pitch | 俯仰通道 | int | {"max":"1424","min":"624","unit_name":""} | 对应遥控器E通道,控制飞行器俯仰(表现为前后平移)。杆量范围\[1024±400\]\*\*,1024为中值(无动作),数值增大表示向前俯冲,减小表示向后抬头。 | \>1074判定为1424 <974判定为624,每次下发持续10s |
| throttle | 升降通道 | int | {"max":"1424","min":"624","unit_name":""} | 对应遥控器T通道,控制飞行器升降。杆量范围\[1024±400\],1024为悬停状态,数值增大表示升高,减小表示降低。 | \>1074判定为1424 <974判定为624,每次下发持续10s |
| yaw | 偏航通道 | int | {"max":"1424","min":"624","unit_name":""} | 对应遥控器R通道,控制飞行器偏航(表现为左右旋转)。杆量范围\[1024±400\],1024为中值(无动作),数值增大表示顺时针旋转,减小表示逆时针旋转。 | \>1074判定为1424 <974判定为624,每次下发持续10s |
JSON
{
"data": {
"roll": 1024,
"pitch": 1024,
"throttle": 1024,
"yaw": 1024
},
"method": "stick_control"
}
@@ -99,3 +99,27 @@ CREATE TABLE IF NOT EXISTS `3d_model_file_detail` (
-- VALUES
-- ('黄山景区倾斜模型', 1, 'https://minicdn.goflytec.com/goflymodel/scenic_001/tileset.json',
-- 'scenic_001/tileset.json', 'goflymodel', 'scenic_001', 101, 1);
-- =====================================================
-- 数据库迁移脚本
-- =====================================================
-- V1.1: 添加地形类型字段和双高度偏移字段
-- 用于记录高度偏移标定时使用的地形服务类型,以及两种地形对应的高度偏移值
-- 以便加载模型时使用相同的地形服务,避免高度不匹配问题
-- 如果一种地形服务加载失败,可以自动使用另一种地形服务及其对应的高度
-- 添加地形类型字段
ALTER TABLE `3d_model_file`
ADD COLUMN `terrain_type` VARCHAR(20) DEFAULT 'cesium_ion' COMMENT '高度偏移标定时使用的地形服务: cesium_ion/arcgis/ellipsoid'
AFTER `offset_height`;
-- 添加 Cesium Ion 地形对应的高度偏移字段
ALTER TABLE `3d_model_file`
ADD COLUMN `cesium_height` DECIMAL(10,2) DEFAULT NULL COMMENT 'Cesium Ion地形对应的高度偏移(米)'
AFTER `terrain_type`;
-- 添加 ArcGIS 地形对应的高度偏移字段
ALTER TABLE `3d_model_file`
ADD COLUMN `arcgis_height` DECIMAL(10,2) DEFAULT NULL COMMENT 'ArcGIS地形对应的高度偏移(米)'
AFTER `cesium_height`;
@@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.*;
* 设备命令控制器
* 提供HTTP接口接收前端命令请求,发送命令到设备
*
* @author lishilin
* @author dzc
* @date 2025-01-01
*/
@Slf4j
@@ -82,20 +82,42 @@ public class DeviceCommandController {
}
/**
* 一键起飞
* 一键起飞(飞向指定点)
*/
@Operation(summary = "无人机一键起飞")
@PostMapping("/takeoff")
public Result<String> takeoff(@RequestBody TakeoffRequest request) {
log.info("收到起飞命令: device={}, altitude={}", request.getDeviceSn(), request.getAltitude());
log.info("收到起飞命令: device={}, target=({}, {}), height={}",
request.getDeviceSn(), request.getTargetLatitude(), request.getTargetLongitude(), request.getTargetHeight());
try {
// 验证必要参数
if (request.getDeviceSn() == null || request.getDeviceSn().isEmpty()) {
return Result.failed("设备SN不能为空");
}
if (request.getTargetLatitude() == null || request.getTargetLongitude() == null) {
return Result.failed("目标点经纬度不能为空");
}
// 构建参数
JSONObject params = new JSONObject();
params.put("altitude", request.getAltitude() != null ? request.getAltitude() : 50);
params.put("target_latitude", request.getTargetLatitude());
params.put("target_longitude", request.getTargetLongitude());
params.put("target_height", request.getTargetHeight() != null ? request.getTargetHeight() : 100f);
params.put("security_takeoff_height", request.getSecurityTakeoffHeight() != null ? request.getSecurityTakeoffHeight() : 50f);
params.put("rth_mode", request.getRthMode() != null ? request.getRthMode() : 1); // 默认设定高度模式
params.put("rth_altitude", request.getRthAltitude() != null ? request.getRthAltitude() : 50);
params.put("rc_lost_action", request.getRcLostAction() != null ? request.getRcLostAction() : 2); // 默认返航
params.put("commander_mode_lost_action", request.getCommanderModeLostAction() != null ? request.getCommanderModeLostAction() : 1);
params.put("commander_flight_mode", request.getCommanderFlightMode() != null ? request.getCommanderFlightMode() : 1); // 默认设定高度飞行
params.put("commander_flight_height", request.getCommanderFlightHeight() != null ? request.getCommanderFlightHeight() : 50f);
params.put("flight_id", request.getFlightId() != null ? request.getFlightId() : java.util.UUID.randomUUID().toString().replace("-", "").toUpperCase());
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 5);
params.put("flight_safety_advance_check", request.getFlightSafetyAdvanceCheck() != null ? request.getFlightSafetyAdvanceCheck() : 0);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"takeoff",
"takeoff_to_point",
params
);
@@ -129,23 +151,238 @@ public class DeviceCommandController {
}
/**
* 一键降落
* 取消返航
*/
@Operation(summary = "无人机一键降落")
@PostMapping("/land")
public Result<String> land(@RequestParam String deviceSn) {
log.info("收到降落命令: device={}", deviceSn);
@Operation(summary = "取消返航")
@PostMapping("/return/cancel")
public Result<String> cancelReturnHome(@RequestParam String deviceSn) {
log.info("收到取消返航命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"land",
"return_home_cancel",
new JSONObject()
);
return Result.succeed(commandId, "降落命令已发送");
return Result.succeed(commandId, "取消返航命令已发送");
} catch (Exception e) {
log.error("发送降落命令失败: device={}, error={}", deviceSn, e.getMessage());
log.error("发送取消返航命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 航线暂停(紧急悬停)
*/
@Operation(summary = "航线暂停/紧急悬停")
@PostMapping("/pause")
public Result<String> pause(@RequestParam String deviceSn) {
log.info("收到暂停命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"flighttask_pause",
new JSONObject()
);
return Result.succeed(commandId, "暂停命令已发送");
} catch (Exception e) {
log.error("发送暂停命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 航线恢复
*/
@Operation(summary = "航线恢复")
@PostMapping("/resume")
public Result<String> resume(@RequestParam String deviceSn) {
log.info("收到恢复命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"flighttask_recovery",
new JSONObject()
);
return Result.succeed(commandId, "恢复命令已发送");
} catch (Exception e) {
log.error("发送恢复命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 拍照
*/
@Operation(summary = "无人机拍照")
@PostMapping("/photo")
public Result<String> takePhoto(@RequestParam String deviceSn) {
log.info("收到拍照命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"camera_photo_take",
new JSONObject()
);
return Result.succeed(commandId, "拍照命令已发送");
} catch (Exception e) {
log.error("发送拍照命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 开始录像
*/
@Operation(summary = "开始录像")
@PostMapping("/recording/start")
public Result<String> startRecording(@RequestParam String deviceSn) {
log.info("收到开始录像命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"camera_recording_start",
new JSONObject()
);
return Result.succeed(commandId, "开始录像命令已发送");
} catch (Exception e) {
log.error("发送开始录像命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 停止录像
*/
@Operation(summary = "停止录像")
@PostMapping("/recording/stop")
public Result<String> stopRecording(@RequestParam String deviceSn) {
log.info("收到停止录像命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"camera_recording_stop",
new JSONObject()
);
return Result.succeed(commandId, "停止录像命令已发送");
} catch (Exception e) {
log.error("发送停止录像命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 切换相机模式
*/
@Operation(summary = "切换相机模式")
@PostMapping("/camera/mode")
public Result<String> switchCameraMode(@RequestParam String deviceSn, @RequestParam Integer cameraMode) {
log.info("收到切换相机模式命令: device={}, mode={}", deviceSn, cameraMode);
try {
JSONObject params = new JSONObject();
// camera_mode: 0=拍照模式, 1=录像模式
params.put("camera_mode", cameraMode != null ? cameraMode : 0);
String commandId = commandManager.sendCommand(
deviceSn,
"camera_mode_switch",
params
);
return Result.succeed(commandId, "切换相机模式命令已发送");
} catch (Exception e) {
log.error("发送切换相机模式命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 进入指令飞行模式(DRC模式)
*/
@Operation(summary = "进入指令飞行模式")
@PostMapping("/drc/enter")
public Result<String> enterDrcMode(@RequestParam String deviceSn) {
log.info("收到进入DRC模式命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"drc_mode_enter",
new JSONObject()
);
return Result.succeed(commandId, "进入DRC模式命令已发送");
} catch (Exception e) {
log.error("发送进入DRC模式命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* DRC杆量控制
*/
@Operation(summary = "DRC杆量控制")
@PostMapping("/drc/stick")
public Result<String> stickControl(@RequestBody StickControlRequest request) {
log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}",
request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw());
try {
JSONObject params = new JSONObject();
params.put("roll", request.getRoll() != null ? request.getRoll() : 1024);
params.put("pitch", request.getPitch() != null ? request.getPitch() : 1024);
params.put("throttle", request.getThrottle() != null ? request.getThrottle() : 1024);
params.put("yaw", request.getYaw() != null ? request.getYaw() : 1024);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"stick_control",
params
);
return Result.succeed(commandId, "杆量控制命令已发送");
} catch (Exception e) {
log.error("发送杆量控制命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 云台控制
*/
@Operation(summary = "云台控制")
@PostMapping("/gimbal")
public Result<String> gimbalControl(@RequestBody GimbalControlRequest request) {
log.info("收到云台控制命令: device={}, pitchSpeed={}, yawSpeed={}, locked={}",
request.getDeviceSn(), request.getPitchSpeed(), request.getYawSpeed(), request.getLocked());
try {
JSONObject params = new JSONObject();
params.put("pitch_speed", request.getPitchSpeed() != null ? request.getPitchSpeed() : 0);
params.put("yaw_speed", request.getYawSpeed() != null ? request.getYawSpeed() : 0);
params.put("locked", request.getLocked() != null ? request.getLocked() : false);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"camera_screen_drag",
params
);
return Result.succeed(commandId, "云台控制命令已发送");
} catch (Exception e) {
log.error("发送云台控制命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
@@ -174,10 +411,71 @@ public class DeviceCommandController {
private JSONObject params;
}
/**
* 一键起飞请求参数
*/
@Data
public static class TakeoffRequest {
/** 设备SN */
private String deviceSn;
private Integer altitude; // 起飞高度(米)
/** 目标点纬度 */
private Double targetLatitude;
/** 目标点经度 */
private Double targetLongitude;
/** 目标点高度(椭球高),使用 WGS84 模型 */
private Float targetHeight;
/** 安全起飞高度,相对起飞点的高度 */
private Float securityTakeoffHeight;
/** 返航模式:0=智能高度,1=设定高度 */
private Integer rthMode;
/** 返航高度,相对起飞点的高度 */
private Integer rthAltitude;
/** 遥控器失控动作:0=悬停,1=降落,2=返航 */
private Integer rcLostAction;
/** 指点飞行失控动作:0=继续执行,1=退出任务 */
private Integer commanderModeLostAction;
/** 指点飞行模式:0=智能高度飞行,1=设定高度飞行 */
private Integer commanderFlightMode;
/** 指点飞行高度,相对起飞点的高度 */
private Float commanderFlightHeight;
/** 一键起飞任务UUID */
private String flightId;
/** 最大飞行速度(m/s),范围1-15 */
private Integer maxSpeed;
/** 飞行安全预检查:0=关闭,1=开启 */
private Integer flightSafetyAdvanceCheck;
}
/**
* DRC杆量控制请求参数
*/
@Data
public static class StickControlRequest {
/** 设备SN */
private String deviceSn;
/** 横滚通道(624-1424,1024为中值) */
private Integer roll;
/** 俯仰通道(624-1424,1024为中值) */
private Integer pitch;
/** 升降通道(624-1424,1024为悬停) */
private Integer throttle;
/** 偏航通道(624-1424,1024为中值) */
private Integer yaw;
}
/**
* 云台控制请求参数
*/
@Data
public static class GimbalControlRequest {
/** 设备SN */
private String deviceSn;
/** 云台 pitch 速度(度/秒) */
private Double pitchSpeed;
/** 云台 yaw 速度(度/秒) */
private Double yawSpeed;
/** 是否锁定机头:false=仅云台转,true=机身一起转 */
private Boolean locked;
}
@Data
@@ -95,9 +95,18 @@ public class ThreeDModelFile extends SuperEntity {
@Schema(description = "纬度偏移(度)")
private BigDecimal offsetLatitude;
@Schema(description = "高度偏移(米)")
@Schema(description = "高度偏移(米) - 通用/兼容旧数据")
private BigDecimal offsetHeight;
@Schema(description = "Cesium Ion地形对应的高度偏移(米)")
private BigDecimal cesiumHeight;
@Schema(description = "ArcGIS地形对应的高度偏移(米)")
private BigDecimal arcgisHeight;
@Schema(description = "高度偏移标定时使用的地形服务: cesium_ion/arcgis/ellipsoid")
private String terrainType;
// ========== 变换参数 ==========
@Schema(description = "缩放比例")
@@ -49,9 +49,18 @@ public class ThreeDModelFileDTO {
@Schema(description = "纬度偏移(度)", defaultValue = "0")
private BigDecimal offsetLatitude = BigDecimal.ZERO;
@Schema(description = "高度偏移(米)", defaultValue = "0")
@Schema(description = "高度偏移(米) - 通用", defaultValue = "0")
private BigDecimal offsetHeight = BigDecimal.ZERO;
@Schema(description = "Cesium Ion地形对应的高度偏移(米)")
private BigDecimal cesiumHeight;
@Schema(description = "ArcGIS地形对应的高度偏移(米)")
private BigDecimal arcgisHeight;
@Schema(description = "高度偏移标定时使用的地形服务: cesium_ion/arcgis/ellipsoid", defaultValue = "cesium_ion")
private String terrainType = "cesium_ion";
// ========== 变换参数 ==========
@Schema(description = "缩放比例", defaultValue = "1.0")
@@ -108,8 +108,17 @@ public class ThreeDModelFileVO {
@Schema(description = "纬度偏移")
private BigDecimal latitude;
@Schema(description = "高度偏移")
@Schema(description = "高度偏移 - 通用/兼容旧数据")
private BigDecimal height;
@Schema(description = "Cesium Ion地形对应的高度偏移(米)")
private BigDecimal cesiumHeight;
@Schema(description = "ArcGIS地形对应的高度偏移(米)")
private BigDecimal arcgisHeight;
@Schema(description = "高度偏移标定时使用的地形服务: cesium_ion/arcgis/ellipsoid")
private String terrainType;
}
/**
@@ -149,6 +149,18 @@ public class ThreeDModelFileServiceImpl extends SuperServiceImpl<ThreeDModelFile
if (dto.getOffsetHeight() != null) {
model.setOffsetHeight(dto.getOffsetHeight());
}
// 更新Cesium Ion地形对应的高度偏移
if (dto.getCesiumHeight() != null) {
model.setCesiumHeight(dto.getCesiumHeight());
}
// 更新ArcGIS地形对应的高度偏移
if (dto.getArcgisHeight() != null) {
model.setArcgisHeight(dto.getArcgisHeight());
}
// 更新地形类型(高度标定时使用的地形服务)
if (StrUtil.isNotBlank(dto.getTerrainType())) {
model.setTerrainType(dto.getTerrainType());
}
// 更新变换参数
if (dto.getScale() != null) {
@@ -372,6 +384,9 @@ public class ThreeDModelFileServiceImpl extends SuperServiceImpl<ThreeDModelFile
position.setLongitude(model.getOffsetLongitude());
position.setLatitude(model.getOffsetLatitude());
position.setHeight(model.getOffsetHeight());
position.setCesiumHeight(model.getCesiumHeight());
position.setArcgisHeight(model.getArcgisHeight());
position.setTerrainType(model.getTerrainType());
vo.setPosition(position);
// 设置变换配置
@@ -102,4 +102,52 @@ public class DeviceStatusSseController {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,开始接收无人机实时遥测数据
*
* @param deviceSn 设备SN
* @return 订阅结果
*/
@Operation(summary = "订阅无人机遥测数据")
@PostMapping("/drone-telemetry/{deviceSn}/subscribe")
public org.springframework.http.ResponseEntity<String> subscribeDroneTelemetry(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
log.info("订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
sseEmitterManager.subscribeDroneTelemetry(deviceSn);
return org.springframework.http.ResponseEntity.ok("无人机遥测数据订阅成功");
} catch (Exception e) {
log.error("订阅无人机遥测数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
return org.springframework.http.ResponseEntity.badRequest().body("订阅失败: " + e.getMessage());
}
}
/**
* 取消订阅无人机遥测数据(msg_alarm)
* 退出操控台时调用,停止接收无人机实时遥测数据
*
* @param deviceSn 设备SN
* @return 取消订阅结果
*/
@Operation(summary = "取消订阅无人机遥测数据")
@PostMapping("/drone-telemetry/{deviceSn}/unsubscribe")
public org.springframework.http.ResponseEntity<String> unsubscribeDroneTelemetry(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
sseEmitterManager.unsubscribeDroneTelemetry(deviceSn);
return org.springframework.http.ResponseEntity.ok("无人机遥测数据已取消订阅");
} catch (Exception e) {
log.error("取消订阅无人机遥测数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
return org.springframework.http.ResponseEntity.badRequest().body("取消订阅失败: " + e.getMessage());
}
}
}
@@ -327,4 +327,26 @@ public class SseEmitterManager {
public int getDeviceRefCount(String deviceSn) {
return deviceRefCount.getOrDefault(deviceSn, 0);
}
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,开始接收无人机实时遥测数据
*
* @param deviceSn 设备SN
*/
public void subscribeDroneTelemetry(String deviceSn) {
log.info("订阅无人机遥测数据: deviceSn={}", deviceSn);
deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn);
}
/**
* 取消订阅无人机遥测数据(msg_alarm)
* 退出操控台时调用,停止接收无人机实时遥测数据
*
* @param deviceSn 设备SN
*/
public void unsubscribeDroneTelemetry(String deviceSn) {
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
}
}
@@ -160,10 +160,11 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
try {
String payload = message.getPayload();
// log.info("收到WebSocket消息: length={}, payload={}", payload.length(), payload);
log.debug("收到WebSocket消息: length={}", payload.length());
JSONObject json = JSON.parseObject(payload);
String type = json.getString("type");
String topic = json.getString("topic");
// 处理心跳响应
if ("pong".equals(type)) {
@@ -177,9 +178,15 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
return;
}
// 处理命令响应(/device-message-sender/...)
if (topic != null && topic.contains("/device-message-sender/")) {
handleCommandResponseMessage(json);
return;
}
// 处理订阅结果(包括各种消息类型)
// JetLinks返回的消息可能是:result、event、property等
if ("result".equals(type) || json.containsKey("requestId")) {
if ("result".equals(type) || json.containsKey("requestId") || json.containsKey("topic")) {
handleSubscriptionResult(json);
return;
}
@@ -192,6 +199,56 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
}
}
/**
* 处理命令响应消息
*/
private void handleCommandResponseMessage(JSONObject json) {
String topic = json.getString("topic");
String requestId = json.getString("id");
String deviceSn = extractDeviceSn(topic);
log.info("收到命令响应: topic={}, requestId={}, deviceSn={}", topic, requestId, deviceSn);
// 通知命令管理器处理响应
if (commandManager != null && requestId != null) {
try {
// 检查是否成功 - JetLinks响应格式可能有多种
JSONObject payload = json.getJSONObject("payload");
boolean success = false;
String message = null;
if (payload != null) {
// 检查 payload.success 或 payload.result.success
if (payload.containsKey("success")) {
success = payload.getBooleanValue("success");
message = payload.getString("message");
} else if (payload.containsKey("result")) {
JSONObject result = payload.getJSONObject("result");
if (result != null) {
success = result.getBooleanValue("success");
message = result.getString("message");
}
} else {
// 如果有 payload 但没有 success 字段,可能是成功的
success = true;
}
} else {
// 没有 payload,检查顶层是否有 success
success = json.getBooleanValue("success");
message = json.getString("message");
}
log.info("命令响应解析: requestId={}, success={}, message={}", requestId, success, message);
commandManager.getClass()
.getMethod("handleCommandResponse", String.class, boolean.class, String.class)
.invoke(commandManager, requestId, success, message);
} catch (Exception e) {
log.warn("调用命令管理器处理响应失败: {}", e.getMessage());
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
log.warn("WebSocket连接关闭: code={}, reason={}, isAutoClose={}, isManualClose={}",
@@ -252,7 +309,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
// 从topic中提取deviceSn
String deviceSn = extractDeviceSn(topic);
if (deviceSn == null) {
log.warn("无法从topic提取deviceSn: {}", topic);
// 可能是其他类型的响应,打印日志但不阻断
log.debug("无法从topic提取deviceSn,可能是非设备消息: topic={}", topic);
return;
}
@@ -291,15 +349,25 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
/**
* 从topic中提取deviceSn
* topic格式: /device/D-Dock2/{deviceSn}/...
* 支持的topic格式:
* 1. /device/D-Dock2/{deviceSn}/... (订阅消息)
* 2. /device-message-sender/D-Dock2/{deviceSn} (命令响应)
*/
private String extractDeviceSn(String topic) {
if (topic == null || !topic.startsWith("/device/D-Dock2/")) {
if (topic == null) {
log.warn("无法从topic提取deviceSn: {}", topic);
return null;
}
String[] parts = topic.split("/");
if (parts.length >= 4) {
// 格式1: /device/D-Dock2/{deviceSn}/...
if (topic.startsWith("/device/D-Dock2/") && parts.length >= 4) {
return parts[3];
}
// 格式2: /device-message-sender/D-Dock2/{deviceSn}
if (topic.startsWith("/device-message-sender/D-Dock2/") && parts.length >= 4) {
return parts[3];
}
@@ -449,12 +517,13 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
}
});
// 为每个设备重新订阅标准主题(只订阅关键主题)
// 为每个设备重新订阅标准主题(订阅关键主题)
deviceSns.forEach(deviceSn -> {
subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm最重要
SubscriptionTopic.EVENT_FIRE_ALARM, // fire_alarm(机库状态数据)
SubscriptionTopic.EVENT_MSG_ALARM // msg_alarm(无人机遥测数据)
);
});
}
@@ -0,0 +1,30 @@
package com.central.device.websocket.config;
import com.central.device.websocket.handler.DeviceControlWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* 设备控制WebSocket配置
* 用于云台控制和摇杆控制的高频实时通信
*
* @author lishilin
* @date 2025-01-19
*/
@Configuration
@EnableWebSocket
public class DeviceControlWebSocketConfig implements WebSocketConfigurer {
@Autowired
private DeviceControlWebSocketHandler deviceControlWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 注册WebSocket端点,路径格式: /ws/control/{deviceSn}
registry.addHandler(deviceControlWebSocketHandler, "/ws/control/*")
.setAllowedOrigins("*"); // 生产环境应配置具体域名
}
}
@@ -7,7 +7,7 @@ import org.springframework.stereotype.Component;
/**
* WebSocket配置属性
*
* @author lishilin
* @author dzc
* @date 2025-01-01
*/
@Data
@@ -0,0 +1,309 @@
package com.central.device.websocket.handler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.config.WebSocketProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 设备控制WebSocket处理器
* 处理前端发送的高频控制指令(云台、摇杆)
* 直接转发到JetLinks WebSocket
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class DeviceControlWebSocketHandler extends TextWebSocketHandler {
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
@Autowired
private WebSocketProperties properties;
/**
* 活跃的WebSocket会话: sessionId -> WebSocketSession
*/
private final Map<String, WebSocketSession> activeSessions = new ConcurrentHashMap<>();
/**
* 会话对应的设备SN: sessionId -> deviceSn
*/
private final Map<String, String> sessionDeviceMap = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 从URL路径中提取deviceSn: /ws/control/{deviceSn}
String path = session.getUri().getPath();
String deviceSn = extractDeviceSn(path);
if (deviceSn == null || deviceSn.isEmpty()) {
log.warn("无效的WebSocket连接,缺少deviceSn: path={}", path);
session.close(CloseStatus.BAD_DATA.withReason("Missing deviceSn"));
return;
}
String sessionId = session.getId();
activeSessions.put(sessionId, session);
sessionDeviceMap.put(sessionId, deviceSn);
log.info("设备控制WebSocket连接建立: sessionId={}, deviceSn={}", sessionId, deviceSn);
// 确保JetLinks WebSocket已连接
if (!jetLinksWebSocketClient.isConnected()) {
log.info("JetLinks WebSocket未连接,自动建立连接");
jetLinksWebSocketClient.connect();
}
// 发送连接成功消息
sendResponse(session, "response", true, "连接成功", null);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String sessionId = session.getId();
String deviceSn = sessionDeviceMap.get(sessionId);
if (deviceSn == null) {
log.warn("未知会话收到消息: sessionId={}", sessionId);
return;
}
try {
String payload = message.getPayload();
JSONObject json = JSON.parseObject(payload);
String type = json.getString("type");
switch (type) {
case "heartbeat":
// 心跳响应
sendPong(session);
break;
case "stick_control":
// 摇杆控制
handleStickControl(session, deviceSn, json.getJSONObject("data"));
break;
case "gimbal_control":
// 云台控制
handleGimbalControl(session, deviceSn, json.getJSONObject("data"));
break;
default:
log.warn("未知消息类型: type={}, sessionId={}", type, sessionId);
sendResponse(session, "error", false, "未知消息类型: " + type, null);
}
} catch (Exception e) {
log.error("处理控制消息失败: sessionId={}, error={}", sessionId, e.getMessage());
sendResponse(session, "error", false, "消息处理失败: " + e.getMessage(), null);
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
String sessionId = session.getId();
String deviceSn = sessionDeviceMap.remove(sessionId);
activeSessions.remove(sessionId);
log.info("设备控制WebSocket连接关闭: sessionId={}, deviceSn={}, status={}",
sessionId, deviceSn, status);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
String sessionId = session.getId();
log.error("设备控制WebSocket传输错误: sessionId={}, error={}", sessionId, exception.getMessage());
}
/**
* 处理摇杆控制
*/
private void handleStickControl(WebSocketSession session, String deviceSn, JSONObject data) {
if (data == null) {
sendResponse(session, "error", false, "缺少控制数据", null);
return;
}
// 构建JetLinks命令
JSONObject params = new JSONObject();
params.put("roll", data.getIntValue("roll") != 0 ? data.getIntValue("roll") : 1024);
params.put("pitch", data.getIntValue("pitch") != 0 ? data.getIntValue("pitch") : 1024);
params.put("throttle", data.getIntValue("throttle") != 0 ? data.getIntValue("throttle") : 1024);
params.put("yaw", data.getIntValue("yaw") != 0 ? data.getIntValue("yaw") : 1024);
String commandId = sendToJetLinks(deviceSn, "stick_control", params);
if (commandId != null) {
sendResponse(session, "response", true, "摇杆指令已发送", commandId);
} else {
sendResponse(session, "error", false, "摇杆指令发送失败", null);
}
}
/**
* 处理云台控制
*/
private void handleGimbalControl(WebSocketSession session, String deviceSn, JSONObject data) {
if (data == null) {
sendResponse(session, "error", false, "缺少控制数据", null);
return;
}
// 构建JetLinks命令
JSONObject params = new JSONObject();
params.put("pitch_speed", data.getDoubleValue("pitchSpeed"));
params.put("yaw_speed", data.getDoubleValue("yawSpeed"));
params.put("locked", data.getBooleanValue("locked"));
String commandId = sendToJetLinks(deviceSn, "camera_screen_drag", params);
if (commandId != null) {
sendResponse(session, "response", true, "云台指令已发送", commandId);
} else {
sendResponse(session, "error", false, "云台指令发送失败", null);
}
}
/**
* 发送命令到JetLinks
*
* @return commandId 或 null(失败时)
*/
private String sendToJetLinks(String deviceSn, String method, JSONObject data) {
if (!jetLinksWebSocketClient.isConnected()) {
log.warn("JetLinks WebSocket未连接,尝试重连");
jetLinksWebSocketClient.connect();
// 等待连接(最多1秒,避免阻塞高频控制)
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 10) {
try {
Thread.sleep(100);
waitCount++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
if (!jetLinksWebSocketClient.isConnected()) {
log.error("JetLinks WebSocket连接失败");
return null;
}
}
try {
String commandId = UUID.randomUUID().toString();
// 构造 properties
JSONObject properties = new JSONObject();
properties.put("method", method);
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
// 构造 parameter
JSONObject parameter = new JSONObject();
parameter.put("messageType", "WRITE_PROPERTY");
parameter.put("properties", properties);
JSONObject headers = new JSONObject();
headers.put("async", false);
parameter.put("headers", headers);
// 构造完整消息
JSONObject message = new JSONObject();
message.put("type", "sub");
message.put("topic", "/device-message-sender/D-Dock2/" + deviceSn);
message.put("parameter", parameter);
message.put("id", commandId);
// 发送
String messageJson = message.toJSONString();
log.debug("发送实时控制命令: deviceSn={}, method={}, commandId={}", deviceSn, method, commandId);
jetLinksWebSocketClient.send(messageJson);
return commandId;
} catch (Exception e) {
log.error("发送JetLinks命令失败: deviceSn={}, method={}, error={}", deviceSn, method, e.getMessage());
return null;
}
}
/**
* 发送响应消息
*/
private void sendResponse(WebSocketSession session, String type, boolean success, String message, String commandId) {
try {
JSONObject response = new JSONObject();
response.put("type", type);
response.put("success", success);
response.put("message", message);
if (commandId != null) {
response.put("commandId", commandId);
}
session.sendMessage(new TextMessage(response.toJSONString()));
} catch (IOException e) {
log.error("发送响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
}
}
/**
* 发送心跳响应
*/
private void sendPong(WebSocketSession session) {
try {
JSONObject pong = new JSONObject();
pong.put("type", "pong");
pong.put("timestamp", System.currentTimeMillis());
session.sendMessage(new TextMessage(pong.toJSONString()));
} catch (IOException e) {
log.error("发送心跳响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
}
}
/**
* 从路径中提取deviceSn
* 路径格式: /ws/control/{deviceSn}
*/
private String extractDeviceSn(String path) {
if (path == null) return null;
// 移除末尾的斜杠
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
// 提取最后一段作为deviceSn
int lastSlash = path.lastIndexOf('/');
if (lastSlash >= 0 && lastSlash < path.length() - 1) {
return path.substring(lastSlash + 1);
}
return null;
}
/**
* 获取活跃连接数
*/
public int getActiveConnectionCount() {
return activeSessions.size();
}
}
@@ -331,7 +331,11 @@ public class DeviceMessageHandler {
extractKeyFields(data, mergedDockData);
// 保存合并后的完整设备状态数据
JSONObject rawData = new JSONObject();
// 【重要】保留现有的 rawData,避免覆盖 droneData
JSONObject rawData = data.getRawData();
if (rawData == null) {
rawData = new JSONObject();
}
rawData.put("eventType", "device_state");
rawData.put("messageId", messageId);
rawData.put("timestamp", timestamp);
@@ -406,7 +410,8 @@ public class DeviceMessageHandler {
alarmDataService.saveMsgAlarmData(deviceSn, msgAlarmData);
}
log.debug("处理 msg_alarm 事件: deviceSn={}, timestamp={}", deviceSn, timestamp);
log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}",
deviceSn, timestamp, droneData.keySet());
// 触发 msg_alarm 回调(用于一次性订阅)
BiConsumer<String, JSONObject> msgAlarmCallback = msgAlarmCallbacks.get(deviceSn);
@@ -418,7 +423,7 @@ public class DeviceMessageHandler {
}
}
// 如果设备已在 deviceDataMap 中注册,更新其数据
// 如果设备已在 deviceDataMap 中注册,更新其数据并推送SSE
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data != null) {
data.setOnline(true);
@@ -426,6 +431,19 @@ public class DeviceMessageHandler {
// 从 droneData 提取关键字段更新到 DeviceRealtimeData
extractDroneKeyFields(data, droneData);
// 将 msg_alarm 数据合并到 rawData 中
JSONObject rawData = data.getRawData();
if (rawData == null) {
rawData = new JSONObject();
}
// 只保留 droneData,不再重复存储 msgAlarmData
// 前端直接从 rawData.droneData 读取无人机遥测数据
rawData.put("droneData", droneData);
data.setRawData(rawData);
// 推送到前端(通过SSE)
pushDeviceDataUpdate(data);
}
} catch (Exception e) {
@@ -118,22 +118,49 @@ public class DeviceCommandManager {
/**
* 立即发送命令(通过全局WebSocket客户端)
*
* WebSocket发送指令JSON格式:
* {
* "type": "sub",
* "topic": "/device-message-sender/D-Dock2/{deviceSn}",
* "parameter": {
* "messageType": "WRITE_PROPERTY",
* "properties": {指令JSON},
* "headers": {
* "async": false
* }
* },
* "id": "request-id-xxx"
* }
*/
private void sendCommandImmediately(DeviceCommand command) {
try {
command.setStatus(CommandStatus.SENDING);
command.setSendTime(System.currentTimeMillis());
// 构造命令消息
// TODO: 根据JetLinks平台实际API调整消息格式
// 构造指令内容 (properties)
JSONObject properties = buildCommandProperties(command);
// 构造 parameter
JSONObject parameter = new JSONObject();
parameter.put("messageType", "WRITE_PROPERTY");
parameter.put("properties", properties);
JSONObject headers = new JSONObject();
headers.put("async", false);
parameter.put("headers", headers);
// 构造完整消息
JSONObject message = new JSONObject();
message.put("messageId", command.getCommandId());
message.put("deviceId", command.getDeviceSn());
message.put("command", command.getCommandType());
message.put("params", command.getParams());
message.put("type", "sub");
message.put("topic", "/device-message-sender/D-Dock2/" + command.getDeviceSn());
message.put("parameter", parameter);
message.put("id", command.getCommandId());
// 通过全局WebSocket发送
jetLinksWebSocketClient.send(message.toJSONString());
String messageJson = message.toJSONString();
log.info("发送命令消息: {}", messageJson);
jetLinksWebSocketClient.send(messageJson);
command.setStatus(CommandStatus.SENT);
@@ -153,6 +180,102 @@ public class DeviceCommandManager {
}
}
/**
* 根据命令类型构造 properties 内容
*
* @param command 命令对象
* @return properties JSON
*/
private JSONObject buildCommandProperties(DeviceCommand command) {
JSONObject properties = new JSONObject();
JSONObject data = new JSONObject();
String method = command.getCommandType();
JSONObject params = command.getParams();
switch (method) {
case "takeoff_to_point":
// 一键起飞
data.put("target_latitude", params.getDoubleValue("target_latitude"));
data.put("target_longitude", params.getDoubleValue("target_longitude"));
data.put("target_height", params.getFloatValue("target_height"));
data.put("security_takeoff_height", params.getFloatValue("security_takeoff_height"));
data.put("rth_mode", params.getIntValue("rth_mode"));
data.put("rth_altitude", params.getIntValue("rth_altitude"));
data.put("rc_lost_action", params.getIntValue("rc_lost_action"));
data.put("commander_mode_lost_action", params.getIntValue("commander_mode_lost_action"));
data.put("commander_flight_mode", params.getIntValue("commander_flight_mode"));
data.put("commander_flight_height", params.getFloatValue("commander_flight_height"));
data.put("flight_id", params.getString("flight_id"));
data.put("max_speed", params.getIntValue("max_speed"));
data.put("flight_safety_advance_check", params.getIntValue("flight_safety_advance_check"));
break;
case "return_home":
// 一键返航 - 无参数
break;
case "return_home_cancel":
// 返航取消 - 无参数
break;
case "flighttask_pause":
// 航线暂停 - 无参数
break;
case "flighttask_recovery":
// 航线恢复 - 无参数
break;
case "drc_mode_enter":
// 进入指令飞行模式 - 无参数
break;
case "camera_photo_take":
// 拍照 - 无参数
break;
case "camera_recording_start":
// 开始录像 - 无参数
break;
case "camera_recording_stop":
// 停止录像 - 无参数
break;
case "camera_mode_switch":
// 切换相机模式
data.put("camera_mode", params.getIntValue("camera_mode"));
break;
case "stick_control":
// DRC杆量控制
data.put("roll", params.getIntValue("roll"));
data.put("pitch", params.getIntValue("pitch"));
data.put("throttle", params.getIntValue("throttle"));
data.put("yaw", params.getIntValue("yaw"));
break;
case "camera_screen_drag":
// 云台画面拖动控制
data.put("pitch_speed", params.getDoubleValue("pitch_speed"));
data.put("yaw_speed", params.getDoubleValue("yaw_speed"));
data.put("locked", params.getBooleanValue("locked"));
break;
default:
// 其他命令,直接使用 params 作为 data
data = params;
break;
}
properties.put("method", method);
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
return properties;
}
/**
* 加入队列
*/
@@ -132,7 +132,8 @@ public class DeviceSubscriptionManager {
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
SubscriptionTopic.EVENT_FIRE_ALARM,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
messageHandler.removeDevice(deviceSn);
log.debug("取消订阅设备: {}", deviceSn);
@@ -199,7 +200,8 @@ public class DeviceSubscriptionManager {
deviceSn,
SubscriptionTopic.ONLINE, // 设备上线
SubscriptionTopic.OFFLINE, // 设备离线
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(最重要)
SubscriptionTopic.EVENT_FIRE_ALARM, // fire_alarm事件(机库状态数据)
SubscriptionTopic.EVENT_MSG_ALARM // msg_alarm事件(无人机遥测数据)
);
log.info("设备 {} 订阅成功(景区: {})", deviceSn, scenicId);
@@ -234,6 +236,7 @@ public class DeviceSubscriptionManager {
/**
* 订阅单个设备(v3.0新增)
* 用于SSE懒加载模式,只订阅用户请求的设备
* 【优化】只订阅机库状态数据(fire_alarm),无人机遥测数据(msg_alarm)在进入操控台时单独订阅
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
@@ -248,21 +251,21 @@ public class DeviceSubscriptionManager {
try {
// 添加设备到数据Map(scenicId使用0表示单设备订阅)
// log.info("准备添加设备到数据Map: deviceSn={}, tenantId={}", deviceSn, tenantId);
messageHandler.addDevice(deviceSn, 0L, tenantId);
// log.info("设备已添加到数据Map");
// 通过全局WebSocket客户端订阅设备(会自动触发懒加载连接)
// 只订阅关键主题:上线、离线、fire_alarm(包含设备完整状态数据)
log.info("准备订阅WebSocket主题: deviceSn={}", deviceSn);
// 【优化】只订阅机库相关主题:上线、离线、fire_alarm(机库状态)
// 无人机遥测数据(msg_alarm)在进入操控台时单独订阅,因为大部分时间无人机不在线
log.info("准备订阅WebSocket主题(机库数据): deviceSn={}", deviceSn);
jetLinksWebSocketClient.subscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE, // 设备上线
SubscriptionTopic.OFFLINE, // 设备离线
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(最重要,包含电池、GPS等完整数据)
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(机库状态数据)
// 【移除】SubscriptionTopic.EVENT_MSG_ALARM - 无人机遥测数据在操控台单独订阅
);
log.info("设备 {} 订阅成功(包括WebSocket订阅)", deviceSn);
log.info("设备 {} 订阅成功(机库数据)", deviceSn);
} catch (Exception e) {
log.error("设备 {} 订阅失败: {}", deviceSn, e.getMessage(), e);
@@ -288,7 +291,8 @@ public class DeviceSubscriptionManager {
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
SubscriptionTopic.EVENT_FIRE_ALARM,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
// 移除设备数据
@@ -300,4 +304,60 @@ public class DeviceSubscriptionManager {
log.error("取消订阅设备 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,只订阅无人机遥测数据,不影响机库状态订阅
*
* @param deviceSn 设备SN
*/
public void subscribeDroneTelemetry(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("设备SN为空,无法订阅无人机遥测");
return;
}
log.info("订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
// 只订阅 msg_alarm 主题
jetLinksWebSocketClient.subscribeDevice(
deviceSn,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
log.info("无人机遥测数据 {} 订阅成功", deviceSn);
} catch (Exception e) {
log.error("订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 取消订阅无人机遥测数据(msg_alarm)
* 退出操控台时调用,只取消无人机遥测数据订阅,不影响机库状态订阅
*
* @param deviceSn 设备SN
*/
public void unsubscribeDroneTelemetry(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("设备SN为空,无法取消订阅无人机遥测");
return;
}
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
// 只取消 msg_alarm 主题
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
log.info("无人机遥测数据 {} 订阅已取消", deviceSn);
} catch (Exception e) {
log.error("取消订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ REACT_APP_AMAP_KEY=7df3685709e341daed76e877e417e5be
# 如需使用Cesium Ion的高级功能(如全球地形、卫星影像),可申请Token
# 申请地址: https://cesium.com/ion/signup (国内可访问)
# 注意: 不配置此项不影响3D地图基本功能
# REACT_APP_CESIUM_TOKEN= eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5NjhjNDBlMS02OTBiLTQ5OWMtYjk3Mi04NjdiM2I4N2E4NDYiLCJpZCI6MzYxMzMzLCJpYXQiOjE3NjM0NDIxOTh9.PxIgncOzYVrDY17SWVJWD7U-9A1Wnomac8GEdcAYOeM
REACT_APP_CESIUM_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5NjhjNDBlMS02OTBiLTQ5OWMtYjk3Mi04NjdiM2I4N2E4NDYiLCJpZCI6MzYxMzMzLCJpYXQiOjE3NjM0NDIxOTh9.PxIgncOzYVrDY17SWVJWD7U-9A1Wnomac8GEdcAYOeM
# ========== WebSocket服务配置 ==========
@@ -14,6 +14,42 @@
margin-bottom: 12px;
}
.terrainSection {
display: flex;
align-items: center;
margin-bottom: 16px;
padding: 12px 16px;
background: #fff;
border-radius: 6px;
border: 1px solid #d9d9d9;
flex-wrap: wrap;
gap: 12px;
.terrainSwitch {
display: flex;
align-items: center;
gap: 12px;
.label {
color: #666;
font-size: 13px;
white-space: nowrap;
}
}
.savedHeights {
display: flex;
align-items: center;
gap: 12px;
.label {
color: #666;
font-size: 13px;
white-space: nowrap;
}
}
}
.modelHeightInfo {
display: flex;
gap: 24px;
@@ -44,6 +80,12 @@
color: #52c41a;
font-size: 15px;
}
.tipText {
font-size: 12px;
color: #999;
font-style: italic;
}
}
}
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Spin, Alert, Typography, Descriptions, Tag, Slider, InputNumber, Button, Space, message } from 'antd';
import { Modal, Spin, Alert, Typography, Descriptions, Tag, Slider, InputNumber, Button, Space, message, Radio, Divider } from 'antd';
import { ThreeDModelVO, updateModel } from '@/services/threeDModel';
import styles from './ModelPreviewModal.less';
@@ -34,6 +34,8 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
const [saving, setSaving] = useState(false);
const [modelHeight, setModelHeight] = useState<number | null>(null); // 模型原始高度
const [suggestedOffset, setSuggestedOffset] = useState<number>(0); // 建议的偏移值
const [currentTerrainType, setCurrentTerrainType] = useState<string>('cesium_ion'); // 当前使用的地形类型
const [terrainSwitching, setTerrainSwitching] = useState(false); // 是否正在切换地形
// 清理函数
const cleanup = useCallback(() => {
@@ -104,12 +106,39 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
setSaving(true);
try {
await updateModel({
// 根据当前地形类型,保存到对应的高度字段
const updateData: any = {
id: model.id,
modelName: model.modelName,
offsetHeight: heightOffset,
});
message.success(`高度偏移已保存: ${heightOffset}米`);
offsetHeight: heightOffset, // 同时更新通用高度字段
terrainType: currentTerrainType,
// 保留原有的 LOD 精度配置,避免被默认值覆盖
maxScreenSpaceError: model.style?.maximumScreenSpaceError || 1,
maxMemoryUsage: model.style?.maximumMemoryUsage || 2048,
skipLod: model.style?.skipLevelOfDetail ? 1 : 0,
preferLeaves: model.style?.preferLeaves ? 1 : 0,
};
// 根据当前地形类型保存到对应字段
if (currentTerrainType === 'cesium_ion') {
updateData.cesiumHeight = heightOffset;
// 保留已有的 ArcGIS 高度
if (model.position?.arcgisHeight !== undefined) {
updateData.arcgisHeight = model.position.arcgisHeight;
}
} else if (currentTerrainType === 'arcgis') {
updateData.arcgisHeight = heightOffset;
// 保留已有的 Cesium 高度
if (model.position?.cesiumHeight !== undefined) {
updateData.cesiumHeight = model.position.cesiumHeight;
}
}
await updateModel(updateData);
const terrainName = currentTerrainType === 'cesium_ion' ? 'Cesium Ion' :
currentTerrainType === 'arcgis' ? 'ArcGIS' : '椭球';
message.success(`高度偏移已保存: ${heightOffset}米 (${terrainName}地形)`);
onHeightUpdated?.();
} catch (err: any) {
message.error('保存失败: ' + (err.message || '未知错误'));
@@ -118,6 +147,63 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
}
};
/**
* 切换地形类型
* 重新加载指定类型的地形,并应用对应的高度偏移值
*/
const switchTerrain = useCallback(async (terrainType: string) => {
if (!viewerRef.current || !Cesium || terrainSwitching) return;
if (terrainType === currentTerrainType) return;
setTerrainSwitching(true);
console.log('切换地形到:', terrainType);
try {
let terrainProvider;
if (terrainType === 'cesium_ion') {
terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: false,
});
console.log('地形切换成功: Cesium Ion');
} else if (terrainType === 'arcgis') {
terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
console.log('地形切换成功: ArcGIS');
} else {
terrainProvider = new Cesium.EllipsoidTerrainProvider();
console.log('地形切换成功: 椭球(无高程)');
}
// 切换地形
viewerRef.current.terrainProvider = terrainProvider;
setCurrentTerrainType(terrainType);
// 切换到对应地形的高度偏移值
let newHeight = model?.position?.height || 0;
if (terrainType === 'cesium_ion' && model?.position?.cesiumHeight !== undefined && model?.position?.cesiumHeight !== null) {
newHeight = model.position.cesiumHeight;
} else if (terrainType === 'arcgis' && model?.position?.arcgisHeight !== undefined && model?.position?.arcgisHeight !== null) {
newHeight = model.position.arcgisHeight;
}
setHeightOffset(newHeight);
// 应用新的高度偏移
if (tilesetRef.current && originalCenterRef.current) {
adjustHeight(newHeight);
}
message.success(`已切换到 ${terrainType === 'cesium_ion' ? 'Cesium Ion' : terrainType === 'arcgis' ? 'ArcGIS' : '椭球'} 地形`);
} catch (err: any) {
console.error('切换地形失败:', err);
message.error(`切换地形失败: ${err.message || '未知错误'}`);
} finally {
setTerrainSwitching(false);
}
}, [currentTerrainType, terrainSwitching, model, adjustHeight]);
// 初始化Viewer和加载模型
const initViewer = useCallback(async () => {
if (!model?.tilesetUrl || !containerRef.current) return;
@@ -128,10 +214,6 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
setLoading(true);
setError(null);
// 初始化高度偏移为模型当前配置的值
const initialHeight = model.position?.height || 0;
setHeightOffset(initialHeight);
try {
// 动态加载Cesium
if (!Cesium) {
@@ -139,15 +221,98 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
Cesium = cesiumModule;
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
// 设置 Cesium Ion Access Token(用于加载 Cesium World Terrain)
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
if (cesiumToken) {
Cesium.Ion.defaultAccessToken = cesiumToken;
}
}
if (!containerRef.current) {
throw new Error('容器未就绪');
}
// 使用高程地形,让3D模型与地形配合显示
// 如果模型已有记录的地形类型,优先使用该类型;否则按优先级尝试加载
const savedTerrainType = model.position?.terrainType;
let terrainProvider;
let loadedTerrainType = 'ellipsoid';
// 根据保存的地形类型或默认优先级加载地形
if (savedTerrainType === 'arcgis') {
// 优先尝试 ArcGIS(如果之前用 ArcGIS 标定的)
try {
terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
loadedTerrainType = 'arcgis';
console.log('ModelPreview: 高程地形加载成功 (ArcGIS World Elevation - 根据保存的地形类型)');
} catch (arcgisError) {
console.warn('ModelPreview: ArcGIS 加载失败,尝试 Cesium Ion:', arcgisError);
try {
terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: false,
});
loadedTerrainType = 'cesium_ion';
console.log('ModelPreview: 高程地形加载成功 (Cesium World Terrain - 备用)');
message.warning('ArcGIS地形加载失败,已切换到Cesium Ion,高度可能需要重新调整');
} catch (cesiumError) {
console.warn('ModelPreview: Cesium Ion 也加载失败,使用椭球地形:', cesiumError);
terrainProvider = new Cesium.EllipsoidTerrainProvider();
loadedTerrainType = 'ellipsoid';
message.warning('地形加载失败,使用椭球地形,高度需要重新调整');
}
}
} else {
// 默认优先使用 Cesium Ion
try {
terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: false,
});
loadedTerrainType = 'cesium_ion';
console.log('ModelPreview: 高程地形加载成功 (Cesium World Terrain)');
} catch (cesiumError) {
console.warn('ModelPreview: Cesium World Terrain 加载失败,尝试 ArcGIS:', cesiumError);
try {
terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
loadedTerrainType = 'arcgis';
console.log('ModelPreview: 高程地形加载成功 (ArcGIS World Elevation)');
if (savedTerrainType === 'cesium_ion') {
message.warning('Cesium Ion地形加载失败,已切换到ArcGIS,高度可能需要重新调整');
}
} catch (arcgisError) {
console.warn('ModelPreview: ArcGIS 也加载失败,使用椭球地形:', arcgisError);
terrainProvider = new Cesium.EllipsoidTerrainProvider();
loadedTerrainType = 'ellipsoid';
message.warning('地形加载失败,使用椭球地形,高度需要重新调整');
}
}
}
// 记录当前加载的地形类型
setCurrentTerrainType(loadedTerrainType);
// 根据实际加载的地形类型,选择对应的高度偏移值
let initialHeight = model.position?.height || 0; // 默认使用通用高度
if (loadedTerrainType === 'cesium_ion' && model.position?.cesiumHeight !== undefined && model.position?.cesiumHeight !== null) {
initialHeight = model.position.cesiumHeight;
console.log('使用 Cesium Ion 高度偏移:', initialHeight);
} else if (loadedTerrainType === 'arcgis' && model.position?.arcgisHeight !== undefined && model.position?.arcgisHeight !== null) {
initialHeight = model.position.arcgisHeight;
console.log('使用 ArcGIS 高度偏移:', initialHeight);
} else {
console.log('使用通用高度偏移:', initialHeight);
}
setHeightOffset(initialHeight);
// 创建Viewer
const viewer = new Cesium.Viewer(containerRef.current, {
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
terrainProvider: terrainProvider,
scene3DOnly: true,
animation: false,
timeline: false,
@@ -169,7 +334,10 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
creditContainer.style.display = 'none';
}
// 添加影像图层
// 启用地形深度测试,确保模型与地形正确交互
viewer.scene.globe.depthTestAgainstTerrain = true;
// 添加 ArcGIS 高清卫星影像底图
const arcgisImagery = new Cesium.UrlTemplateImageryProvider({
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0,
@@ -194,17 +362,17 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
// 保存原始中心点(用于高度调整计算)
originalCenterRef.current = Cesium.Cartesian3.clone(tileset.boundingSphere.center);
// 计算模型的WGS84高度,并给出建议的偏移值
// 计算模型的WGS84高度(海拔)
const cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
const heightInMeters = cartographic.height;
setModelHeight(Math.round(heightInMeters));
// 建议的偏移值:取负值让模型下降到地面
// 保留一点高度(约50米)避免模型陷入地面
const suggested = -Math.round(heightInMeters) + 50;
setSuggestedOffset(suggested);
// 使用高程地形后,模型与地形的位置已经比较接近
// 由于 Cesium World Terrain 精度约30m,与大疆模型可能存在一定偏差
// 建议偏移值默认为 0,用户根据实际显示效果微调
setSuggestedOffset(0);
console.log(`模型高度: ${heightInMeters.toFixed(2)}米, 建议偏移: ${suggested}米`);
console.log(`模型海拔高度: ${heightInMeters.toFixed(2)}米,使用高程地形,建议微调偏移`);
// 如果有初始高度偏移,立即应用
if (initialHeight !== 0) {
@@ -302,26 +470,67 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
{initialized && (
<div className={styles.heightControl}>
<div className={styles.heightControlTitle}>
<span>🎚️ 高度调整(模型在空中飘着?向下调整;模型陷入地面?向上调整)</span>
<span>高度偏移调整(微调模型高度以匹配地形,正值上移、负值下移)</span>
</div>
{/* 地形切换和已保存高度信息 */}
<div className={styles.terrainSection}>
<div className={styles.terrainSwitch}>
<span className={styles.label}>选择地形:</span>
<Radio.Group
value={currentTerrainType}
onChange={(e) => switchTerrain(e.target.value)}
disabled={terrainSwitching}
optionType="button"
buttonStyle="solid"
size="small"
>
<Radio.Button value="cesium_ion">Cesium Ion</Radio.Button>
<Radio.Button value="arcgis">ArcGIS</Radio.Button>
</Radio.Group>
{terrainSwitching && <Spin size="small" style={{ marginLeft: 8 }} />}
</div>
<Divider type="vertical" style={{ height: 'auto', margin: '0 16px' }} />
<div className={styles.savedHeights}>
<span className={styles.label}>已保存高度:</span>
<Space size="middle">
<span>
<Tag color={currentTerrainType === 'cesium_ion' ? 'blue' : 'default'}>Cesium Ion</Tag>
<span style={{ fontWeight: currentTerrainType === 'cesium_ion' ? 'bold' : 'normal' }}>
{model?.position?.cesiumHeight !== undefined && model?.position?.cesiumHeight !== null
? `${model.position.cesiumHeight}米`
: '未设置'}
</span>
</span>
<span>
<Tag color={currentTerrainType === 'arcgis' ? 'green' : 'default'}>ArcGIS</Tag>
<span style={{ fontWeight: currentTerrainType === 'arcgis' ? 'bold' : 'normal' }}>
{model?.position?.arcgisHeight !== undefined && model?.position?.arcgisHeight !== null
? `${model.position.arcgisHeight}米`
: '未设置'}
</span>
</span>
</Space>
</div>
</div>
{/* 模型高度信息 */}
{modelHeight !== null && (
<div className={styles.modelHeightInfo}>
<div className={styles.heightInfoItem}>
<span className={styles.label}>模型原始高度:</span>
<span className={styles.label}>模型海拔高度:</span>
<span className={styles.value}>{modelHeight} 米</span>
</div>
<div className={styles.heightInfoItem}>
<span className={styles.label}>建议偏移值:</span>
<span className={styles.suggestedValue}>{suggestedOffset} 米</span>
<Button
type="link"
size="small"
onClick={() => setHeightOffset(suggestedOffset)}
>
应用建议值
</Button>
<span className={styles.label}>当前偏移:</span>
<span className={styles.suggestedValue}>{heightOffset} 米</span>
</div>
<div className={styles.heightInfoItem}>
<span className={styles.tipText}>
提示: 分别切换到两种地形调整并保存高度,这样两种地形服务都能正确显示模型
</span>
</div>
</div>
)}
@@ -361,11 +570,17 @@ const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
<Button size="small" onClick={() => setHeightOffset(0)}>
重置为0
</Button>
<Button
size="small"
onClick={() => setHeightOffset(suggestedOffset)}
>
应用建议值
<Button size="small" onClick={() => setHeightOffset(heightOffset + 10)}>
+10米
</Button>
<Button size="small" onClick={() => setHeightOffset(heightOffset - 10)}>
-10米
</Button>
<Button size="small" onClick={() => setHeightOffset(heightOffset + 30)}>
+30米
</Button>
<Button size="small" onClick={() => setHeightOffset(heightOffset - 30)}>
-30米
</Button>
<Button
type="primary"
@@ -415,21 +415,79 @@ const TourismDeviceDetail: React.FC<TourismDeviceDetailProps> = (props) => {
setSelectedDeviceSn(device.deviceSn || '');
};
// 处理一键起飞
// 一键起飞弹窗状态
const [takeoffModalVisible, setTakeoffModalVisible] = useState(false);
const [takeoffLoading, setTakeoffLoading] = useState(false);
const [takeoffForm] = useState({
targetLatitude: 0,
targetLongitude: 0,
targetHeight: 100,
securityTakeoffHeight: 50,
rthAltitude: 50,
maxSpeed: 5,
});
// 处理一键起飞 - 打开确认弹窗
const handleTakeoff = () => {
// 再次确认机库状态
// 检查机库状态
if (realtimeData?.rawData?.dockData?.mode_code === 1) {
message.warning('机库正在执行任务,无法起飞');
return;
}
if (realtimeData?.rawData?.dockData?.drone_in_dock !== 1) {
// 只有明确知道无人机不在库时才阻止(值为0时)
if (realtimeData?.rawData?.dockData?.drone_in_dock === 0) {
message.warning('无人机不在库,无法起飞');
return;
}
// TODO: 调用后端API执行一键起飞(会自动开机)
message.info('一键起飞功能开发中');
// 使用机库当前位置作为默认目标点
const dockLatitude = realtimeData?.rawData?.dockData?.latitude || realtimeData?.gps?.latitude || 0;
const dockLongitude = realtimeData?.rawData?.dockData?.longitude || realtimeData?.gps?.longitude || 0;
const dockHeight = realtimeData?.rawData?.dockData?.height || realtimeData?.gps?.altitude || 0;
takeoffForm.targetLatitude = dockLatitude;
takeoffForm.targetLongitude = dockLongitude;
takeoffForm.targetHeight = dockHeight + 30; // 机库高度 + 30米
setTakeoffModalVisible(true);
};
// 执行一键起飞(弹窗确认后调用)
const doTakeoff = async () => {
if (!selectedDeviceSn) {
message.error('未选择设备');
return;
}
if (!takeoffForm.targetLatitude || !takeoffForm.targetLongitude) {
message.error('无法获取机库位置信息');
return;
}
setTakeoffLoading(true);
try {
const res = await deviceApi.takeoff({
deviceSn: selectedDeviceSn,
targetLatitude: takeoffForm.targetLatitude,
targetLongitude: takeoffForm.targetLongitude,
targetHeight: takeoffForm.targetHeight,
securityTakeoffHeight: takeoffForm.securityTakeoffHeight,
rthAltitude: takeoffForm.rthAltitude,
maxSpeed: takeoffForm.maxSpeed,
});
if (res.code === 0) {
message.success('起飞命令已发送,无人机将自动开机并起飞');
setTakeoffModalVisible(false);
} else {
message.error(res.msg || '起飞命令发送失败');
}
} catch (error: any) {
message.error(error.message || '起飞命令发送失败');
} finally {
setTakeoffLoading(false);
}
};
// 初始加载
@@ -718,8 +776,13 @@ const TourismDeviceDetail: React.FC<TourismDeviceDetailProps> = (props) => {
disabled={
// 机库正在工作中
realtimeData?.rawData?.dockData?.mode_code === 1 ||
// 无人机不在库
realtimeData?.rawData?.dockData?.drone_in_dock !== 1
// 无人机不在库(明确为0时禁用,undefined或1时允许)
realtimeData?.rawData?.dockData?.drone_in_dock === 0
}
title={
realtimeData?.rawData?.dockData?.sub_device?.device_online_status !== 1
? '无人机未开机,点击后将自动开机并起飞'
: '一键起飞'
}
>
一键起飞
@@ -1253,6 +1316,95 @@ const TourismDeviceDetail: React.FC<TourismDeviceDetailProps> = (props) => {
</Col>
</Row>
</Modal>
{/* 一键起飞弹窗 */}
<Modal
title={
<span style={{ color: '#1890ff' }}>
<RocketOutlined style={{ marginRight: 8 }} />
一键起飞设置
{realtimeData?.rawData?.dockData?.sub_device?.device_online_status !== 1 && (
<Tag color="orange" style={{ marginLeft: 8 }}>无人机将自动开机</Tag>
)}
</span>
}
open={takeoffModalVisible}
onCancel={() => setTakeoffModalVisible(false)}
onOk={doTakeoff}
confirmLoading={takeoffLoading}
okText="确认起飞"
cancelText="取消"
width={500}
>
<div style={{ marginTop: 16 }}>
<Row gutter={[16, 16]}>
<Col span={12}>
<div style={{ marginBottom: 8 }}>目标纬度</div>
<input
type="number"
value={takeoffForm.targetLatitude}
onChange={(e) => takeoffForm.targetLatitude = parseFloat(e.target.value) || 0}
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
step="0.000001"
/>
</Col>
<Col span={12}>
<div style={{ marginBottom: 8 }}>目标经度</div>
<input
type="number"
value={takeoffForm.targetLongitude}
onChange={(e) => takeoffForm.targetLongitude = parseFloat(e.target.value) || 0}
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
step="0.000001"
/>
</Col>
<Col span={12}>
<div style={{ marginBottom: 8 }}>目标高度 (m)</div>
<input
type="number"
value={takeoffForm.targetHeight}
onChange={(e) => takeoffForm.targetHeight = parseInt(e.target.value) || 100}
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
min={2}
max={1500}
/>
</Col>
<Col span={12}>
<div style={{ marginBottom: 8 }}>安全起飞高度 (m)</div>
<input
type="number"
value={takeoffForm.securityTakeoffHeight}
onChange={(e) => takeoffForm.securityTakeoffHeight = parseInt(e.target.value) || 50}
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
min={20}
max={1500}
/>
</Col>
<Col span={12}>
<div style={{ marginBottom: 8 }}>返航高度 (m)</div>
<input
type="number"
value={takeoffForm.rthAltitude}
onChange={(e) => takeoffForm.rthAltitude = parseInt(e.target.value) || 50}
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
min={2}
max={1500}
/>
</Col>
<Col span={12}>
<div style={{ marginBottom: 8 }}>最大飞行速度 (m/s)</div>
<input
type="number"
value={takeoffForm.maxSpeed}
onChange={(e) => takeoffForm.maxSpeed = parseInt(e.target.value) || 5}
style={{ width: '100%', padding: '8px', border: '1px solid #d9d9d9', borderRadius: 4 }}
min={1}
max={15}
/>
</Col>
</Row>
</div>
</Modal>
</PageContainer>
);
};
@@ -1,7 +1,6 @@
import React from 'react';
import React, { useMemo, useState, useCallback, useEffect, useRef } from 'react';
import {
CloseOutlined,
RocketOutlined,
VideoCameraOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
@@ -14,10 +13,20 @@ import {
RotateRightOutlined,
VerticalAlignTopOutlined,
VerticalAlignBottomOutlined,
DashboardOutlined,
CompassOutlined
CompassOutlined,
WifiOutlined,
LoadingOutlined,
PlayCircleOutlined,
PauseCircleOutlined,
LinkOutlined,
DisconnectOutlined,
CaretRightOutlined,
SwapOutlined,
AimOutlined
} from '@ant-design/icons';
import { message } from 'antd';
import { message, Tooltip, Modal, Switch, Tag } from 'antd';
import { deviceApi } from '@/services/device';
import { deviceControlWs } from '@/services/deviceControlWs';
import styles from './LeftControlPanel.less';
interface LeftControlPanelProps {
@@ -27,6 +36,18 @@ interface LeftControlPanelProps {
realtimeData: any;
}
// 飞行模式映射
const FLIGHT_MODE_MAP: Record<number, string> = {
0: '待机',
1: '起飞',
2: '降落',
3: '悬停',
4: '航点飞行',
5: '返航',
6: '手动控制',
7: '紧急制动',
};
const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
visible,
onClose,
@@ -34,26 +55,471 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
realtimeData
}) => {
const dockData = realtimeData?.rawData?.dockData;
// 模拟详细飞行数据 (Placeholder Data)
const flightData = {
pitch: -2.5,
roll: 0.1,
yaw: 125.4,
hSpeed: 0.0,
vSpeed: 0.0,
altitude: realtimeData?.gps?.altitude?.toFixed(1) || '0.0',
distance: 12.5, // 离家距离
homeAlt: 0,
satellites: dockData?.position_state?.gps_number || 12,
rtkStatus: 'FIX',
signal: 95,
rcSignal: 100
};
const droneData = realtimeData?.rawData?.droneData;
const handleControl = (action: string) => {
message.info(`发送指令: ${action}`);
};
// 从 droneData (msg_alarm) 获取无人机实时飞行数据
// droneData 结构: 根级别有 latitude, longitude, height, attitude_pitch 等
// 云台数据在 payload 索引下,如 droneData["98-0-0"]
const flightData = useMemo(() => {
// 调试日志 - 查看 droneData 的实际结构
if (droneData) {
console.log('[FlightData] droneData keys:', Object.keys(droneData));
console.log('[FlightData] droneData.latitude:', droneData?.latitude);
console.log('[FlightData] droneData.longitude:', droneData?.longitude);
}
// 获取云台payload数据 - 遍历查找带有 gimbal_pitch 的子对象
let gimbalPayload: any = {};
if (droneData) {
// 常见的 payload 索引
const payloadKeys = ['98-0-0', '39-0-0', '42-0-0', '43-0-0', '52-0-0', '53-0-0', '165-0-0'];
for (const key of payloadKeys) {
if (droneData[key] && (droneData[key].gimbal_pitch !== undefined || droneData[key].gimbal_yaw !== undefined)) {
gimbalPayload = droneData[key];
console.log('[FlightData] 找到云台数据在 key:', key, gimbalPayload);
break;
}
}
// 如果常见索引没找到,遍历所有数字格式的key
if (!gimbalPayload.gimbal_pitch && !gimbalPayload.gimbal_yaw) {
for (const key of Object.keys(droneData)) {
if (/^\d+-\d+-\d+$/.test(key) && droneData[key]?.gimbal_pitch !== undefined) {
gimbalPayload = droneData[key];
console.log('[FlightData] 遍历找到云台数据在 key:', key);
break;
}
}
}
}
const pitch = droneData?.attitude_pitch ?? 0;
const roll = droneData?.attitude_roll ?? 0;
const yaw = droneData?.attitude_head ?? 0;
const hSpeed = droneData?.horizontal_speed ?? droneData?.ground_speed ?? 0;
const vSpeed = droneData?.vertical_speed ?? 0;
const altitude = droneData?.height ?? droneData?.elevation ?? realtimeData?.gps?.altitude ?? 0;
const distance = droneData?.home_distance ?? 0;
// GPS/RTK卫星数据
const satellites = droneData?.position_state?.gps_number ?? dockData?.position_state?.gps_number ?? 0;
const rtkSatellites = droneData?.position_state?.rtk_number ?? dockData?.position_state?.rtk_number ?? 0;
const isFixed = droneData?.position_state?.is_fixed ?? dockData?.position_state?.is_fixed ?? 0;
const rtkStatus = isFixed === 2 ? 'FIX' : (isFixed === 1 ? 'FLOAT' : (rtkSatellites > 0 ? 'FLOAT' : 'NONE'));
// 电池数据
const batteryPercent = droneData?.battery?.capacity_percent ?? realtimeData?.battery ?? 0;
const batteryVoltage = droneData?.battery?.voltage ?? 0;
const batteryTemp = droneData?.battery?.temperature ?? 0;
const remainFlightTime = droneData?.battery?.remain_flight_time ?? 0;
// 信号强度
const signal = dockData?.wireless_link?.dongle_number ?? dockData?.sdr?.upward_quality ?? 0;
// 飞行模式
const modeCode = droneData?.mode_code ?? 0;
const flightMode = FLIGHT_MODE_MAP[modeCode] || `模式${modeCode}`;
// 云台角度 - 优先从 payload 中获取,否则从根级别获取
const gimbalPitch = gimbalPayload?.gimbal_pitch ?? droneData?.gimbal_pitch ?? 0;
const gimbalYaw = gimbalPayload?.gimbal_yaw ?? droneData?.gimbal_yaw ?? 0;
const windSpeed = droneData?.wind_speed ?? 0;
// 无人机实时经纬度 - 直接从 droneData 根级别获取
const droneLat = droneData?.latitude ?? 0;
const droneLng = droneData?.longitude ?? 0;
return {
pitch: Number(pitch).toFixed(1),
roll: Number(roll).toFixed(1),
yaw: Number(yaw).toFixed(1),
hSpeed: Number(hSpeed).toFixed(1),
vSpeed: Number(vSpeed).toFixed(1),
altitude: Number(altitude).toFixed(1),
distance: Number(distance).toFixed(1),
satellites,
rtkSatellites,
rtkStatus,
signal,
batteryPercent,
batteryVoltage: (batteryVoltage / 1000).toFixed(2),
batteryTemp,
remainFlightTime: Math.floor(remainFlightTime / 60),
flightMode,
modeCode,
gimbalPitch: Number(gimbalPitch).toFixed(1),
gimbalYaw: Number(gimbalYaw).toFixed(1),
windSpeed: Number(windSpeed).toFixed(1),
// 无人机实时位置
latitude: Number(droneLat).toFixed(6),
longitude: Number(droneLng).toFixed(6),
};
}, [droneData, dockData, realtimeData]);
// 指令发送状态
const [loading, setLoading] = useState<string | null>(null);
const [isRecording, setIsRecording] = useState(false);
const [cameraMode, setCameraMode] = useState<'photo' | 'video'>('photo'); // 相机模式
// WebSocket连接状态
const [wsConnected, setWsConnected] = useState(false);
// DRC模式状态 - 只需进入一次即可持续控制
const [drcMode, setDrcMode] = useState(false);
const drcModeRef = useRef(false); // 用于在回调中访问最新状态
// 获取设备SN
const deviceSn = device?.deviceSn;
// WebSocket连接管理 + 无人机遥测数据订阅
useEffect(() => {
if (visible && deviceSn) {
// 1. 连接实时控制WebSocket
deviceControlWs.connect(deviceSn);
// 2. 订阅无人机遥测数据(msg_alarm)
// 只有进入操控台时才订阅,因为大部分时间无人机不在线
console.log('[LeftControlPanel] 订阅无人机遥测数据:', deviceSn);
deviceApi.subscribeDroneTelemetry(deviceSn).then((res) => {
if (res.success) {
console.log('[LeftControlPanel] 无人机遥测数据订阅成功');
} else {
console.warn('[LeftControlPanel] 无人机遥测数据订阅失败:', res.message);
}
});
const unsubscribe = deviceControlWs.onStatusChange((connected) => {
setWsConnected(connected);
if (connected) {
console.log('[LeftControlPanel] 实时控制WebSocket已连接');
} else {
console.log('[LeftControlPanel] 实时控制WebSocket已断开');
// 断开时重置DRC模式状态
setDrcMode(false);
drcModeRef.current = false;
}
});
return () => {
unsubscribe();
deviceControlWs.disconnect();
// 清理DRC模式状态
setDrcMode(false);
drcModeRef.current = false;
// 3. 取消订阅无人机遥测数据
console.log('[LeftControlPanel] 取消订阅无人机遥测数据:', deviceSn);
deviceApi.unsubscribeDroneTelemetry(deviceSn).then((res) => {
if (res.success) {
console.log('[LeftControlPanel] 无人机遥测数据已取消订阅');
}
});
};
}
}, [visible, deviceSn]);
// 进入DRC模式(只需调用一次)
const enterDrcMode = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return false;
}
if (drcModeRef.current) {
return true; // 已经在DRC模式中
}
setLoading('drc');
try {
const res = await deviceApi.enterDrcMode(deviceSn);
if (res.code === 0) {
setDrcMode(true);
drcModeRef.current = true;
message.success('已进入指令飞行模式');
return true;
} else {
message.error(res.msg || '进入指令飞行模式失败');
return false;
}
} catch (error: any) {
message.error(error.message || '进入指令飞行模式失败');
return false;
} finally {
setLoading(null);
}
}, [deviceSn]);
// 一键返航
const handleReturnHome = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
Modal.confirm({
title: '确认返航',
content: '确定要让无人机执行一键返航吗?',
onOk: async () => {
setLoading('return');
try {
const res = await deviceApi.returnHome(deviceSn);
if (res.code === 0) {
message.success('返航命令已发送');
} else {
message.error(res.msg || '返航命令发送失败');
}
} catch (error: any) {
message.error(error.message || '返航命令发送失败');
} finally {
setLoading(null);
}
},
});
}, [deviceSn]);
// 取消返航
const handleCancelReturn = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
setLoading('cancelReturn');
try {
const res = await deviceApi.cancelReturnHome(deviceSn);
if (res.code === 0) {
message.success('取消返航命令已发送');
} else {
message.error(res.msg || '取消返航命令发送失败');
}
} catch (error: any) {
message.error(error.message || '取消返航命令发送失败');
} finally {
setLoading(null);
}
}, [deviceSn]);
// 航线暂停(紧急悬停)
const handlePause = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
setLoading('pause');
try {
const res = await deviceApi.pause(deviceSn);
if (res.code === 0) {
message.success('航线暂停/悬停命令已发送');
} else {
message.error(res.msg || '暂停命令发送失败');
}
} catch (error: any) {
message.error(error.message || '暂停命令发送失败');
} finally {
setLoading(null);
}
}, [deviceSn]);
// 航线恢复
const handleResume = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
setLoading('resume');
try {
const res = await deviceApi.resume(deviceSn);
if (res.code === 0) {
message.success('航线恢复命令已发送');
} else {
message.error(res.msg || '恢复命令发送失败');
}
} catch (error: any) {
message.error(error.message || '恢复命令发送失败');
} finally {
setLoading(null);
}
}, [deviceSn]);
// 切换相机模式
const handleSwitchCameraMode = useCallback(async (mode: 'photo' | 'video') => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
setLoading('switchMode');
try {
// camera_mode: 0=拍照模式, 1=录像模式
const cameraModeValue = mode === 'photo' ? 0 : 1;
const res = await deviceApi.switchCameraMode(deviceSn, cameraModeValue);
if (res?.code === 0) {
setCameraMode(mode);
message.success(`已切换到${mode === 'photo' ? '拍照' : '录像'}模式`);
} else {
message.error(res?.msg || '切换相机模式失败');
}
} catch (error: any) {
message.error(error.message || '切换相机模式失败');
} finally {
setLoading(null);
}
}, [deviceSn]);
// 拍照
const handleTakePhoto = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
// 如果当前是录像模式,先切换到拍照模式
if (cameraMode !== 'photo') {
await handleSwitchCameraMode('photo');
}
setLoading('photo');
try {
const res = await deviceApi.takePhoto(deviceSn);
if (res.code === 0) {
message.success('拍照命令已发送');
} else {
message.error(res.msg || '拍照命令发送失败');
}
} catch (error: any) {
message.error(error.message || '拍照命令发送失败');
} finally {
setLoading(null);
}
}, [deviceSn, cameraMode, handleSwitchCameraMode]);
// 开始录像
const handleStartRecording = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
// 先切换到录像模式
if (cameraMode !== 'video') {
await handleSwitchCameraMode('video');
}
setLoading('recording');
try {
const res = await deviceApi.startRecording(deviceSn);
if (res.code === 0) {
setIsRecording(true);
message.success('开始录像命令已发送');
} else {
message.error(res.msg || '开始录像命令发送失败');
}
} catch (error: any) {
message.error(error.message || '开始录像命令发送失败');
} finally {
setLoading(null);
}
}, [deviceSn, cameraMode, handleSwitchCameraMode]);
// 停止录像
const handleStopRecording = useCallback(async () => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
setLoading('recording');
try {
const res = await deviceApi.stopRecording(deviceSn);
if (res.code === 0) {
setIsRecording(false);
message.success('停止录像命令已发送');
} else {
message.error(res.msg || '停止录像命令发送失败');
}
} catch (error: any) {
message.error(error.message || '停止录像命令发送失败');
} finally {
setLoading(null);
}
}, [deviceSn]);
// DRC杆量控制 (使用WebSocket实时发送,需先进入DRC模式)
const handleStickControl = useCallback(async (direction: string) => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
if (!wsConnected) {
message.warning('实时控制通道未连接,正在重连...');
deviceControlWs.connect(deviceSn);
return;
}
// 检查是否已进入DRC模式,如果没有则先进入
if (!drcModeRef.current) {
const entered = await enterDrcMode();
if (!entered) return;
}
const offset = 300;
let params = { roll: 1024, pitch: 1024, throttle: 1024, yaw: 1024 };
switch (direction) {
case 'up': params.throttle = 1024 + offset; break;
case 'down': params.throttle = 1024 - offset; break;
case 'left': params.yaw = 1024 - offset; break;
case 'right': params.yaw = 1024 + offset; break;
case 'forward': params.pitch = 1024 + offset; break;
case 'backward': params.pitch = 1024 - offset; break;
case 'moveLeft': params.roll = 1024 - offset; break;
case 'moveRight': params.roll = 1024 + offset; break;
default: break;
}
const success = deviceControlWs.sendStickControl(params);
if (!success) {
message.error('摇杆指令发送失败');
}
}, [deviceSn, wsConnected, enterDrcMode]);
// 云台控制 (使用WebSocket实时发送,需先进入DRC模式)
const handleGimbalControl = useCallback(async (direction: string) => {
if (!deviceSn) {
message.error('未选择设备');
return;
}
if (!wsConnected) {
message.warning('实时控制通道未连接,正在重连...');
deviceControlWs.connect(deviceSn);
return;
}
// 检查是否已进入DRC模式,如果没有则先进入
if (!drcModeRef.current) {
const entered = await enterDrcMode();
if (!entered) return;
}
const speed = 20;
let params = { pitchSpeed: 0, yawSpeed: 0, locked: false };
switch (direction) {
case 'up': params.pitchSpeed = speed; break;
case 'down': params.pitchSpeed = -speed; break;
case 'left': params.yawSpeed = -speed; break;
case 'right': params.yawSpeed = speed; break;
default: break;
}
const success = deviceControlWs.sendGimbalControl(params);
if (!success) {
message.error('云台指令发送失败');
}
}, [deviceSn, wsConnected, enterDrcMode]);
return (
<div className={`${styles.leftPanel} ${visible ? styles.visible : ''}`}>
@@ -76,12 +542,32 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
</div>
<div className={styles.hudOverlay}>
<div className={styles.crosshair} />
{/* HUD左上角 - 飞行模式和状态 */}
<div style={{position: 'absolute', top: 10, left: 10, color: '#0f0', fontSize: 12, fontFamily: 'monospace'}}>
CAM: Main<br/>ISO: Auto<br/>EXP: 0.0
MODE: {flightData.flightMode}<br/>
<span style={{color: droneData ? '#0f0' : '#f00'}}>
{droneData ? '● 遥测正常' : '○ 等待遥测'}
</span><br/>
GIMBAL: P{flightData.gimbalPitch}° Y{flightData.gimbalYaw}°
</div>
{/* HUD左下角 - 无人机GPS坐标和高度 */}
<div style={{position: 'absolute', bottom: 30, left: 10, color: '#0ff', fontSize: 11, fontFamily: 'monospace'}}>
<AimOutlined style={{marginRight: 4}} />
LAT: {flightData.latitude}°<br/>
<span style={{marginLeft: 16}}>LNG: {flightData.longitude}°</span><br/>
<span style={{marginLeft: 16}}>ALT: {flightData.altitude}m</span>
</div>
{/* HUD右上角 - 电池信息 */}
<div style={{position: 'absolute', top: 10, right: 10, color: '#fff', fontSize: 12, fontFamily: 'monospace', textAlign: 'right'}}>
<span style={{color: Number(flightData.batteryPercent) > 30 ? '#0f0' : '#f00'}}>
BAT: {flightData.batteryPercent}%
</span><br/>
{flightData.batteryVoltage}V / {flightData.batteryTemp}°C<br/>
<span style={{color: '#0ff'}}>剩余: {flightData.remainFlightTime}min</span>
</div>
{/* HUD底部状态条 */}
<div style={{
position: 'absolute', bottom: 10, left: 10, right: 10,
position: 'absolute', bottom: 10, left: 10, right: 10,
display: 'flex', justifyContent: 'space-between',
color: '#fff', fontSize: 12, textShadow: '0 0 2px #000'
}}>
@@ -89,73 +575,139 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
<span>D: {flightData.distance}m</span>
<span>H.S: {flightData.hSpeed}m/s</span>
<span>V.S: {flightData.vSpeed}m/s</span>
<span>WIND: {flightData.windSpeed}m/s</span>
</div>
</div>
</div>
{/* 飞行仪表盘区域 */}
<div className={styles.flightDashboard}>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> PITCH</div>
<div className={styles.dashValue}>{flightData.pitch}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> ROLL</div>
<div className={styles.dashValue}>{flightData.roll}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> YAW</div>
<div className={styles.dashValue}>{flightData.yaw}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>RTK</div>
<div className={styles.dashValue} style={{color: '#00ff88'}}>{flightData.rtkStatus}</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>SAT</div>
<div className={styles.dashValue}>{flightData.satellites}</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>LINK</div>
<div className={styles.dashValue}>{flightData.signal}%</div>
</div>
<Tooltip title="俯仰角 - 无人机前后倾斜角度">
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> PITCH</div>
<div className={styles.dashValue}>{flightData.pitch}°</div>
</div>
</Tooltip>
<Tooltip title="横滚角 - 无人机左右倾斜角度">
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> ROLL</div>
<div className={styles.dashValue}>{flightData.roll}°</div>
</div>
</Tooltip>
<Tooltip title="偏航角 - 无人机航向角度">
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> YAW</div>
<div className={styles.dashValue}>{flightData.yaw}°</div>
</div>
</Tooltip>
<Tooltip title={`RTK定位状态 (RTK卫星数: ${flightData.rtkSatellites})`}>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>RTK</div>
<div className={styles.dashValue} style={{
color: flightData.rtkStatus === 'FIX' ? '#00ff88' :
flightData.rtkStatus === 'FLOAT' ? '#ffaa00' : '#ff4444'
}}>
{flightData.rtkStatus}
</div>
</div>
</Tooltip>
<Tooltip title="GPS卫星数量">
<div className={styles.dashItem}>
<div className={styles.dashLabel}>SAT</div>
<div className={styles.dashValue} style={{
color: flightData.satellites >= 10 ? '#00ff88' :
flightData.satellites >= 6 ? '#ffaa00' : '#ff4444'
}}>
{flightData.satellites}
</div>
</div>
</Tooltip>
<Tooltip title="图传信号质量">
<div className={styles.dashItem}>
<div className={styles.dashLabel}><WifiOutlined /> LINK</div>
<div className={styles.dashValue} style={{
color: flightData.signal >= 70 ? '#00ff88' :
flightData.signal >= 40 ? '#ffaa00' : '#ff4444'
}}>
{flightData.signal}%
</div>
</div>
</Tooltip>
</div>
<div className={styles.controlsContent}>
{/* 主要动作 */}
{/* 飞行控制指令 */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>快捷指令 / ACTIONS</div>
<div className={styles.groupTitle}>飞行控制 / FLIGHT CONTROL</div>
<div className={styles.flightActions}>
<button
onClick={() => handleControl('一键起飞')}
disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1}
>
<RocketOutlined /> 一键起飞
<button onClick={handleReturnHome} disabled={loading === 'return'}>
{loading === 'return' ? <LoadingOutlined /> : <HomeOutlined />} 一键返航
</button>
<button onClick={() => handleControl('一键返航')}>
<HomeOutlined /> 一键返航
<button onClick={handleCancelReturn} disabled={loading === 'cancelReturn'}>
{loading === 'cancelReturn' ? <LoadingOutlined /> : <StopOutlined />} 取消返航
</button>
<button className={styles.danger} onClick={() => handleControl('紧急悬停')}>
<StopOutlined /> 紧急悬停
<button className={styles.danger} onClick={handlePause} disabled={loading === 'pause'}>
{loading === 'pause' ? <LoadingOutlined /> : <PauseCircleOutlined />} 航线暂停
</button>
<button onClick={() => handleControl('拍照')}>
<CameraOutlined /> 拍照
<button onClick={handleResume} disabled={loading === 'resume'}>
{loading === 'resume' ? <LoadingOutlined /> : <CaretRightOutlined />} 航线恢复
</button>
</div>
</div>
{/* 相机控制 */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>
相机控制 / CAMERA
<Tag color={cameraMode === 'photo' ? 'blue' : 'red'} style={{ marginLeft: 8 }}>
{cameraMode === 'photo' ? '拍照模式' : '录像模式'}
</Tag>
</div>
<div className={styles.flightActions}>
<button onClick={handleTakePhoto} disabled={loading === 'photo'}>
{loading === 'photo' ? <LoadingOutlined /> : <CameraOutlined />} 拍照
</button>
{!isRecording ? (
<button onClick={handleStartRecording} disabled={loading === 'recording'}>
{loading === 'recording' ? <LoadingOutlined /> : <PlayCircleOutlined />} 开始录像
</button>
) : (
<button className={styles.danger} onClick={handleStopRecording} disabled={loading === 'recording'}>
{loading === 'recording' ? <LoadingOutlined /> : <StopOutlined />} 停止录像
</button>
)}
<button onClick={() => handleSwitchCameraMode(cameraMode === 'photo' ? 'video' : 'photo')} disabled={loading === 'switchMode'}>
{loading === 'switchMode' ? <LoadingOutlined /> : <SwapOutlined />} 切换模式
</button>
</div>
</div>
{/* 飞行姿态控制 (模拟双摇杆) */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>姿态控制 / ATTITUDE CONTROL</div>
<div className={styles.groupTitle}>
姿态控制 / ATTITUDE CONTROL
<Tooltip title={wsConnected ? '实时控制通道已连接' : '实时控制通道未连接'}>
<span style={{ marginLeft: 8, fontSize: 12 }}>
{wsConnected ? (
<LinkOutlined style={{ color: '#00ff88' }} />
) : (
<DisconnectOutlined style={{ color: '#ff4444' }} />
)}
</span>
</Tooltip>
{drcMode && (
<Tag color="green" style={{ marginLeft: 8 }}>DRC模式</Tag>
)}
</div>
<div className={styles.joystickArea}>
{/* 左手:升降 + 转向 */}
<div className={styles.joystickGroup}>
<div className={styles.joystickLabel}>升降 & 偏航 (Left)</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('上升')} title="上升"><VerticalAlignTopOutlined /></button>
<button className={styles.left} onClick={() => handleControl('左转')} title="左转"><RotateLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('右转')} title="右转"><RotateRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('下降')} title="下降"><VerticalAlignBottomOutlined /></button>
<button className={styles.up} onClick={() => handleStickControl('up')} title="上升"><VerticalAlignTopOutlined /></button>
<button className={styles.left} onClick={() => handleStickControl('left')} title="左转"><RotateLeftOutlined /></button>
<button className={styles.right} onClick={() => handleStickControl('right')} title="右转"><RotateRightOutlined /></button>
<button className={styles.down} onClick={() => handleStickControl('down')} title="下降"><VerticalAlignBottomOutlined /></button>
</div>
</div>
@@ -163,10 +715,10 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
<div className={styles.joystickGroup}>
<div className={styles.joystickLabel}>水平移动 (Right)</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('前进')} title="前进"><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleControl('向左飞')} title="向左"><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('向右飞')} title="向右"><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('后退')} title="后退"><ArrowDownOutlined /></button>
<button className={styles.up} onClick={() => handleStickControl('forward')} title="前进"><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleStickControl('moveLeft')} title="向左"><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleStickControl('moveRight')} title="向右"><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleStickControl('backward')} title="后退"><ArrowDownOutlined /></button>
</div>
</div>
</div>
@@ -174,15 +726,20 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
{/* 云台控制 */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>云台控制 / GIMBAL</div>
<div className={styles.groupTitle}>
云台控制 / GIMBAL
{drcMode && (
<Tag color="green" style={{ marginLeft: 8 }}>DRC模式</Tag>
)}
</div>
<div className={styles.joystickArea}>
<div className={styles.joystickGroup} style={{flex: 1}}>
<div className={styles.joystickLabel}>云台方向</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('云台向上')}><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleControl('云台向左')}><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('云台向右')}><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('云台向下')}><ArrowDownOutlined /></button>
<button className={styles.up} onClick={() => handleGimbalControl('up')} title="云台上仰"><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleGimbalControl('left')} title="云台左转"><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleGimbalControl('right')} title="云台右转"><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleGimbalControl('down')} title="云台下俯"><ArrowDownOutlined /></button>
</div>
</div>
</div>
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Spin, Empty, message, Tooltip, Tabs, Progress } from 'antd';
import { Spin, Empty, message, Tooltip, Tabs, Progress, Modal } from 'antd';
import {
CloseOutlined,
EnvironmentOutlined,
@@ -9,6 +9,7 @@ import {
ThunderboltOutlined,
DashboardOutlined,
SignalFilled,
LoadingOutlined,
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { ordersApi } from '@/services/orders';
@@ -24,15 +25,16 @@ interface RightPanelProps {
onControlClick: (device: any, realtimeData: any) => void;
}
const RightPanel: React.FC<RightPanelProps> = ({
visible,
tourism,
const RightPanel: React.FC<RightPanelProps> = ({
visible,
tourism,
onClose,
onControlClick
onControlClick
}) => {
const [deviceList, setDeviceList] = useState<any[]>([]);
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
const [loading, setLoading] = useState(false);
const [takeoffLoading, setTakeoffLoading] = useState(false);
const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE();
@@ -85,6 +87,73 @@ const RightPanel: React.FC<RightPanelProps> = ({
const formatValue = (val: any, unit: string = '') => (val !== undefined && val !== null ? `${val}${unit}` : '-');
// 一键起飞
const handleTakeoff = () => {
const dockData = realtimeData?.rawData?.dockData;
// 检查机库状态
if (dockData?.mode_code === 1) {
message.warning('机库正在执行任务,无法起飞');
return;
}
// 只有明确知道无人机不在库时才阻止(值为0时)
if (dockData?.drone_in_dock === 0) {
message.warning('无人机不在库,无法起飞');
return;
}
// 获取机库位置信息
const dockLatitude = dockData?.latitude || realtimeData?.gps?.latitude;
const dockLongitude = dockData?.longitude || realtimeData?.gps?.longitude;
const dockHeight = dockData?.height || realtimeData?.gps?.altitude || 0;
if (!dockLatitude || !dockLongitude) {
message.error('无法获取机库位置信息');
return;
}
// 弹窗确认
Modal.confirm({
title: '确认一键起飞',
content: (
<div>
<p>无人机将自动开机并起飞到指定位置</p>
<p style={{ fontSize: 12, color: '#666' }}>
目标坐标: {dockLatitude.toFixed(6)}, {dockLongitude.toFixed(6)}<br />
目标高度: {(dockHeight + 30).toFixed(1)}m (机库高度+30m)
</p>
</div>
),
okText: '确认起飞',
cancelText: '取消',
onOk: async () => {
setTakeoffLoading(true);
try {
const res = await deviceApi.takeoff({
deviceSn: selectedDeviceSn,
targetLatitude: dockLatitude,
targetLongitude: dockLongitude,
targetHeight: dockHeight + 30,
securityTakeoffHeight: 50,
rthAltitude: 50,
maxSpeed: 5,
});
if (res.code === 0) {
message.success('起飞命令已发送,无人机将自动开机并起飞');
} else {
message.error(res.msg || '起飞命令发送失败');
}
} catch (error: any) {
message.error(error.message || '起飞命令发送失败');
} finally {
setTakeoffLoading(false);
}
},
});
};
const renderItem = (label: string, value: any, unit: string = '', status: 'normal'|'warning'|'error'|'success' = 'normal') => (
<div className={styles.hudItem}>
<div className={styles.label}>{label}</div>
@@ -190,8 +259,11 @@ const RightPanel: React.FC<RightPanelProps> = ({
<button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}>
<VideoCameraOutlined /> 进入操控台
</button>
<button disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1} onClick={() => message.info('一键起飞指令发送')}>
<RocketOutlined /> 一键起飞
<button
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0}
onClick={handleTakeoff}
>
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞
</button>
</div>
</div>
@@ -14,6 +14,60 @@ export interface DockData {
[key: string]: any;
}
// 无人机遥测数据接口定义
export interface DroneData {
// 飞行姿态
attitude_pitch?: number; // 俯仰角 (度)
attitude_roll?: number; // 横滚角 (度)
attitude_head?: number; // 偏航角/航向 (度)
// 速度
horizontal_speed?: number; // 水平速度 (m/s)
vertical_speed?: number; // 垂直速度 (m/s)
ground_speed?: number; // 地面速度 (m/s)
// 位置
latitude?: number; // 纬度
longitude?: number; // 经度
height?: number; // 高度 (m)
elevation?: number; // 海拔高度 (m)
home_distance?: number; // 距Home点距离 (m)
// 电池
battery?: {
capacity_percent?: number; // 电量百分比
voltage?: number; // 电压 (mV)
temperature?: number; // 温度 (°C)
remain_flight_time?: number; // 剩余飞行时间 (s)
};
// 飞行模式
mode_code?: number; // 飞行模式代码
gear?: number; // 档位
// RTK/GPS
position_state?: {
rtk_number?: number; // RTK 卫星数
gps_number?: number; // GPS 卫星数
is_fixed?: number; // 是否固定 (1=FIX)
};
// 云台
gimbal_pitch?: number; // 云台俯仰角
gimbal_roll?: number; // 云台横滚角
gimbal_yaw?: number; // 云台偏航角
// 其他
wind_speed?: number; // 风速 (m/s)
wind_direction?: number; // 风向 (度)
storage?: {
total?: number; // 存储总容量
used?: number; // 已使用容量
};
[key: string]: any;
}
// 实时数据
export interface RealtimeData {
deviceSn: string;
@@ -26,7 +80,9 @@ export interface RealtimeData {
flightStatus?: string;
timestamp?: number;
rawData?: {
dockData?: any;
dockData?: any; // 机库状态数据 (fire_alarm)
droneData?: DroneData; // 无人机遥测数据 (msg_alarm)
msgAlarmData?: any; // msg_alarm 完整数据
[key: string]: any;
};
}
@@ -13,7 +13,10 @@ export interface TilesetConfig {
position?: { // 模型位置调整
longitude?: number; // 经度偏移
latitude?: number; // 纬度偏移
height?: number; // 高度偏移
height?: number; // 高度偏移(通用)
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移
arcgisHeight?: number; // ArcGIS地形对应的高度偏移
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
};
transform?: { // 模型变换
scale?: number; // 缩放比例
@@ -42,7 +45,7 @@ export interface TilesetState {
// Hook返回类型
export interface UseTilesetLoaderResult {
tilesets: Map<string, TilesetState>;
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any) => Promise<any>;
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any, currentTerrainType?: string) => Promise<any>;
unloadTileset: (id: string, viewer: any) => void;
unloadAllTilesets: (viewer: any) => void;
flyToTileset: (id: string, viewer: any, Cesium: any) => void;
@@ -56,11 +59,16 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
/**
* 加载3D Tiles模型
* @param config 模型配置
* @param viewer Cesium Viewer实例
* @param Cesium Cesium模块
* @param currentTerrainType 当前使用的地形类型,用于选择对应的高度偏移
*/
const loadTileset = useCallback(async (
config: TilesetConfig,
viewer: any,
Cesium: any
Cesium: any,
currentTerrainType?: string
): Promise<any> => {
if (!viewer || !Cesium) {
console.error('Viewer或Cesium未初始化');
@@ -138,9 +146,22 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
});
});
// 模型位置调整 - 只有当位置偏移不为0时才调整
// 模型位置调整 - 根据当前地形类型选择对应的高度偏移
if (config.position) {
const { longitude = 0, latitude = 0, height = 0 } = config.position;
const { longitude = 0, latitude = 0, cesiumHeight, arcgisHeight } = config.position;
// 根据当前地形类型选择对应的高度偏移
let height = config.position.height || 0; // 默认使用通用高度
if (currentTerrainType === 'cesium_ion' && cesiumHeight !== undefined && cesiumHeight !== null) {
height = cesiumHeight;
console.log(`模型 [${config.name}] 使用 Cesium Ion 高度偏移: ${height}`);
} else if (currentTerrainType === 'arcgis' && arcgisHeight !== undefined && arcgisHeight !== null) {
height = arcgisHeight;
console.log(`模型 [${config.name}] 使用 ArcGIS 高度偏移: ${height}`);
} else {
console.log(`模型 [${config.name}] 使用通用高度偏移: ${height}`);
}
// 只有当有非零偏移时才应用位置调整
if (longitude !== 0 || latitude !== 0 || height !== 0) {
const boundingSphere = tileset.boundingSphere;
@@ -33,8 +33,10 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 3D Tiles 模型管理
const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false);
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的模型
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的所有模型配置
const [modelLoading, setModelLoading] = useState(false);
const [terrainLoading, setTerrainLoading] = useState(false); // 是否正在加载高程地形
const terrainLoadedRef = useRef(false); // 是否已加载高程地形
const {
tilesets,
loadTileset,
@@ -79,7 +81,100 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
});
}, []);
// 加载景区绑定的模型,返回是否有模型
/**
* 动态切换到高程地形
* 在进入景区详情、加载3D模型时调用
* @param preferredTerrainType 优先使用的地形类型(从模型配置中获取)
*/
const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise<string> => {
if (!viewerRef.current || !Cesium) {
return 'ellipsoid';
}
// 如果已加载且地形类型匹配,跳过
if (terrainLoadedRef.current && !preferredTerrainType) {
return 'loaded';
}
setTerrainLoading(true);
console.log('开始加载高程地形...', preferredTerrainType ? `优先使用: ${preferredTerrainType}` : '');
let loadedTerrainType = 'ellipsoid';
// 根据优先地形类型决定加载顺序
if (preferredTerrainType === 'arcgis') {
// 优先尝试 ArcGIS
try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
console.log('高程地形加载成功: ArcGIS World Elevation (根据模型配置)');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'arcgis';
} catch (arcgisError) {
console.warn('ArcGIS 加载失败,尝试 Cesium Ion:', arcgisError);
try {
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: true,
});
console.log('高程地形加载成功: Cesium World Terrain (备用)');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'cesium_ion';
message.warning('ArcGIS地形加载失败,已切换到Cesium Ion,模型高度可能有偏差');
} catch (cesiumError) {
console.warn('Cesium Ion 也加载失败,保持椭球地形:', cesiumError);
loadedTerrainType = 'ellipsoid';
}
}
} else {
// 默认优先尝试 Cesium Ion
try {
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
requestVertexNormals: true,
requestWaterMask: true,
});
console.log('高程地形加载成功: Cesium World Terrain');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'cesium_ion';
} catch (cesiumError) {
console.warn('Cesium World Terrain 加载失败,尝试 ArcGIS:', cesiumError);
try {
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
);
console.log('高程地形加载成功: ArcGIS World Elevation');
viewerRef.current.terrainProvider = terrainProvider;
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
terrainLoadedRef.current = true;
loadedTerrainType = 'arcgis';
if (preferredTerrainType === 'cesium_ion') {
message.warning('Cesium Ion地形加载失败,已切换到ArcGIS,模型高度可能有偏差');
}
} catch (arcgisError) {
console.warn('ArcGIS World Elevation 也加载失败,保持椭球地形:', arcgisError);
loadedTerrainType = 'ellipsoid';
}
}
}
setTerrainLoading(false);
return loadedTerrainType;
}, []);
/**
* 加载景区绑定的模型
* 策略:
* 1. 默认只加载第一个模型(通常是主模型)
* 2. 其他模型存储在 currentTourismModels 中,可通过模型面板手动加载
* 3. 如果模型数量较少(<=2个),自动加载所有模型
*/
const loadTourismModels = useCallback(async (tourismId: number): Promise<boolean> => {
if (!viewerRef.current || !Cesium) {
console.log('Viewer或Cesium未准备好');
@@ -101,39 +196,63 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
if (res.resp_code === 0 && modelList && modelList.length > 0) {
const configs = modelList.map((model: any) => convertToTilesetConfig(model));
console.log('转换后的模型配置:', configs);
// 保存所有模型配置(供模型面板使用)
setCurrentTourismModels(configs);
// 【重要】加载模型前,先切换到高程地形
// 从第一个模型的配置中获取地形类型(用于保持与高度标定时一致的地形)
const firstModelTerrainType = configs[0]?.position?.terrainType;
console.log('第一个模型的地形类型配置:', firstModelTerrainType);
const loadedTerrainType = await switchToElevationTerrain(firstModelTerrainType);
console.log('实际加载的地形类型:', loadedTerrainType);
// 确定要自动加载的模型数量
// 策略:模型数量 <= 2 时全部加载,否则只加载第一个
const autoLoadCount = configs.length <= 2 ? configs.length : 1;
const configsToLoad = configs.slice(0, autoLoadCount);
if (configs.length > autoLoadCount) {
message.info(`景区共有 ${configs.length} 个模型,已自动加载第 1 个,其他可通过模型面板加载`);
}
let loadedCount = 0;
// 加载所有模型
for (const config of configs) {
let firstTileset: any = null;
// 加载指定数量的模型,传入实际加载的地形类型
for (const config of configsToLoad) {
console.log('准备加载模型:', config.name, 'URL:', config.url);
if (config.url) {
const tileset = await loadTileset(config, viewerRef.current, Cesium);
const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType);
if (tileset) {
loadedCount++;
message.success(`模型 [${config.name}] 加载成功`);
// 加载成功后飞到第一个模型位置
if (loadedCount === 1) {
// 使用 viewer.flyTo 自动飞到模型
try {
await viewerRef.current.flyTo(tileset, {
duration: 2.0,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45),
0
),
});
} catch (e) {
console.warn('flyTo 失败,尝试 zoomTo:', e);
await viewerRef.current.zoomTo(tileset);
}
firstTileset = tileset;
}
message.success(`模型 [${config.name}] 加载成功`);
}
} else {
console.warn('模型URL为空,跳过加载:', config.name);
}
}
// 飞到第一个加载成功的模型
if (firstTileset) {
try {
await viewerRef.current.flyTo(firstTileset, {
duration: 2.0,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45),
0
),
});
} catch (e) {
console.warn('flyTo 失败,尝试 zoomTo:', e);
await viewerRef.current.zoomTo(firstTileset);
}
}
setModelLoading(false);
return loadedCount > 0;
} else {
@@ -146,7 +265,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
setModelLoading(false);
return false;
}
}, [loadTileset, unloadAllTilesets]);
}, [loadTileset, unloadAllTilesets, switchToElevationTerrain]);
// 处理景区点击
const handleTourismSelect = useCallback((tourism: any) => {
@@ -234,6 +353,13 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
Cesium = cesiumModule;
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
// 设置 Cesium Ion Access Token(用于加载 Cesium World Terrain)
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
if (cesiumToken) {
Cesium.Ion.defaultAccessToken = cesiumToken;
}
if (!document.querySelector('link[href*="cesium"]')) {
const link = document.createElement('link');
link.rel = 'stylesheet';
@@ -244,8 +370,18 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
if (!containerRef.current) return;
// 【重要】初始化时使用椭球地形(无高程),快速加载
// 原因:
// 1. 全球地形加载较慢,影响首屏体验
// 2. Cesium World Terrain 精度约30m,与大疆建图的厘米级精度差异大
// 会导致模型部分贴合、部分悬浮、部分嵌入地面的问题
// 3. 大疆建图的模型本身包含了高精度的地形信息,不需要额外的地形数据
// 解决方案:使用椭球地形 + 模型高度偏移微调
const terrainProvider = new Cesium.EllipsoidTerrainProvider();
console.log('地图仪表盘: 使用椭球地形(快速加载,模型自带高程)');
viewerRef.current = new Cesium.Viewer(containerRef.current, {
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
terrainProvider: terrainProvider,
scene3DOnly: false,
shouldAnimate: true,
animation: false,
@@ -262,6 +398,9 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
maximumRenderTimeChange: Infinity,
});
// 使用椭球地形时不需要深度测试
// viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
viewerRef.current.imageryLayers.remove(viewerRef.current.imageryLayers.get(0));
viewerRef.current.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b');
@@ -442,8 +581,8 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
</div>
)}
{/* 模型加载中提示 */}
{modelLoading && (
{/* 地形/模型加载中提示 */}
{(terrainLoading || modelLoading) && (
<div
style={{
position: 'absolute',
@@ -458,7 +597,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
zIndex: 800,
}}
>
正在加载3D模型...
{terrainLoading ? '正在加载高程地形...' : '正在加载3D模型...'}
</div>
)}
@@ -16,6 +16,83 @@ export interface DeviceItem {
createTime?: string;
}
// ========== 指令相关接口类型 ==========
/** 一键起飞参数 */
export interface TakeoffParams {
deviceSn: string;
/** 目标点纬度 */
targetLatitude: number;
/** 目标点经度 */
targetLongitude: number;
/** 目标点高度(椭球高),使用 WGS84 模型,默认100 */
targetHeight?: number;
/** 安全起飞高度,相对起飞点的高度,默认50 */
securityTakeoffHeight?: number;
/** 返航模式:0=智能高度,1=设定高度,默认1 */
rthMode?: number;
/** 返航高度,相对起飞点的高度,默认50 */
rthAltitude?: number;
/** 遥控器失控动作:0=悬停,1=降落,2=返航,默认2 */
rcLostAction?: number;
/** 指点飞行失控动作:0=继续执行,1=退出任务,默认1 */
commanderModeLostAction?: number;
/** 指点飞行模式:0=智能高度飞行,1=设定高度飞行,默认1 */
commanderFlightMode?: number;
/** 指点飞行高度,相对起飞点的高度,默认50 */
commanderFlightHeight?: number;
/** 一键起飞任务UUID,不传则自动生成 */
flightId?: string;
/** 最大飞行速度(m/s),范围1-15,默认5 */
maxSpeed?: number;
/** 飞行安全预检查:0=关闭,1=开启,默认0 */
flightSafetyAdvanceCheck?: number;
}
/** DRC杆量控制参数 */
export interface StickControlParams {
deviceSn: string;
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
roll?: number;
/** 俯仰通道(624-1424,1024为中值,控制前后平移) */
pitch?: number;
/** 升降通道(624-1424,1024为悬停,控制升降) */
throttle?: number;
/** 偏航通道(624-1424,1024为中值,控制左右旋转) */
yaw?: number;
}
/** 云台控制参数 */
export interface GimbalControlParams {
deviceSn: string;
/** 云台 pitch 速度(度/秒) */
pitchSpeed?: number;
/** 云台 yaw 速度(度/秒) */
yawSpeed?: number;
/** 是否锁定机头:false=仅云台转,true=机身一起转 */
locked?: boolean;
}
/** 命令响应结果 */
export interface CommandResult {
code: number;
msg: string;
data?: string; // commandId
}
/** 命令状态 */
export interface CommandStatus {
commandId: string;
deviceSn: string;
commandType: string;
status: string;
statusDesc: string;
createTime?: number;
sendTime?: number;
retryCount?: number;
errorMsg?: string;
}
export const deviceApi = {
wayline: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
const { current, pageSize, ...rest } = params || {};
@@ -69,5 +146,210 @@ export const deviceApi = {
const res = await request(`/api-device/device/${deviceSn}`, { method: 'DELETE' });
return (res as any).data || res;
},
// ========== 设备指令控制 ==========
/**
* 一键起飞(飞向指定点)
* @param params 起飞参数
* @returns 命令ID
*/
takeoff: async (params: TakeoffParams): Promise<CommandResult> => {
const res = await request('/api-device/device/command/takeoff', {
method: 'POST',
data: params,
});
return res as CommandResult;
},
/**
* 一键返航
* @param deviceSn 设备SN
* @returns 命令ID
*/
returnHome: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/return', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* 取消返航
* @param deviceSn 设备SN
* @returns 命令ID
*/
cancelReturnHome: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/return/cancel', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* 航线暂停/紧急悬停
* @param deviceSn 设备SN
* @returns 命令ID
*/
pause: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/pause', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* 航线恢复
* @param deviceSn 设备SN
* @returns 命令ID
*/
resume: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/resume', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* 拍照
* @param deviceSn 设备SN
* @returns 命令ID
*/
takePhoto: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/photo', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* 开始录像
* @param deviceSn 设备SN
* @returns 命令ID
*/
startRecording: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/recording/start', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* 停止录像
* @param deviceSn 设备SN
* @returns 命令ID
*/
stopRecording: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/recording/stop', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* 切换相机模式
* @param deviceSn 设备SN
* @param cameraMode 相机模式:0=拍照模式,1=录像模式
* @returns 命令ID
*/
switchCameraMode: async (deviceSn: string, cameraMode: number): Promise<CommandResult> => {
const res = await request('/api-device/device/command/camera/mode', {
method: 'POST',
params: { deviceSn, cameraMode },
});
return res as CommandResult;
},
/**
* 进入指令飞行模式(DRC模式)
* @param deviceSn 设备SN
* @returns 命令ID
*/
enterDrcMode: async (deviceSn: string): Promise<CommandResult> => {
const res = await request('/api-device/device/command/drc/enter', {
method: 'POST',
params: { deviceSn },
});
return res as CommandResult;
},
/**
* DRC杆量控制
* @param params 杆量控制参数
* @returns 命令ID
*/
stickControl: async (params: StickControlParams): Promise<CommandResult> => {
const res = await request('/api-device/device/command/drc/stick', {
method: 'POST',
data: params,
});
return res as CommandResult;
},
/**
* 云台控制
* @param params 云台控制参数
* @returns 命令ID
*/
gimbalControl: async (params: GimbalControlParams): Promise<CommandResult> => {
const res = await request('/api-device/device/command/gimbal', {
method: 'POST',
data: params,
});
return res as CommandResult;
},
/**
* 查询命令状态
* @param commandId 命令ID
* @returns 命令状态
*/
getCommandStatus: async (commandId: string): Promise<{ code: number; data: CommandStatus }> => {
const res = await request(`/api-device/device/command/status/${commandId}`, {
method: 'GET',
});
return res as { code: number; data: CommandStatus };
},
// ========== 无人机遥测数据订阅 ==========
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,开始接收无人机实时遥测数据
* @param deviceSn 设备SN
*/
subscribeDroneTelemetry: async (deviceSn: string): Promise<{ success: boolean; message?: string }> => {
try {
const res = await request(`/api-device/sse/drone-telemetry/${deviceSn}/subscribe`, {
method: 'POST',
});
return { success: true, message: res as string };
} catch (error: any) {
return { success: false, message: error.message };
}
},
/**
* 取消订阅无人机遥测数据(msg_alarm)
* 退出操控台时调用,停止接收无人机实时遥测数据
* @param deviceSn 设备SN
*/
unsubscribeDroneTelemetry: async (deviceSn: string): Promise<{ success: boolean; message?: string }> => {
try {
const res = await request(`/api-device/sse/drone-telemetry/${deviceSn}/unsubscribe`, {
method: 'POST',
});
return { success: true, message: res as string };
} catch (error: any) {
return { success: false, message: error.message };
}
},
};
@@ -0,0 +1,282 @@
/**
* 设备实时控制WebSocket服务
* 用于高频率的云台控制和摇杆控制(5-10Hz)
*/
export interface StickControlData {
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
roll?: number;
/** 俯仰通道(624-1424,1024为中值,控制前后平移) */
pitch?: number;
/** 升降通道(624-1424,1024为悬停,控制升降) */
throttle?: number;
/** 偏航通道(624-1424,1024为中值,控制左右旋转) */
yaw?: number;
}
export interface GimbalControlData {
/** 云台 pitch 速度(度/秒) */
pitchSpeed?: number;
/** 云台 yaw 速度(度/秒) */
yawSpeed?: number;
/** 是否锁定机头:false=仅云台转,true=机身一起转 */
locked?: boolean;
}
export interface ControlMessage {
type: 'stick_control' | 'gimbal_control' | 'heartbeat';
deviceSn: string;
data?: StickControlData | GimbalControlData;
}
export interface ControlResponse {
type: 'response' | 'error' | 'pong';
success?: boolean;
message?: string;
commandId?: string;
}
type MessageHandler = (message: ControlResponse) => void;
type StatusHandler = (connected: boolean) => void;
class DeviceControlWebSocket {
private ws: WebSocket | null = null;
private reconnectTimer: NodeJS.Timeout | null = null;
private heartbeatTimer: NodeJS.Timeout | null = null;
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
private reconnectDelay = 2000;
private heartbeatInterval = 15000;
private messageHandlers: MessageHandler[] = [];
private statusHandlers: StatusHandler[] = [];
private currentDeviceSn: string | null = null;
private manualClose = false;
/**
* 连接WebSocket
* @param deviceSn 设备SN
*/
connect(deviceSn: string): void {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
if (this.currentDeviceSn === deviceSn) {
console.log('[ControlWS] 已连接到该设备');
return;
}
// 切换设备,先断开
this.disconnect();
}
this.currentDeviceSn = deviceSn;
this.reconnectAttempts = 0;
this.manualClose = false;
this.doConnect();
}
private doConnect(): void {
if (!this.currentDeviceSn) return;
try {
// WebSocket地址,通过网关代理到device-center
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
const url = `${protocol}//${host}/api-device/ws/control/${this.currentDeviceSn}`;
console.log('[ControlWS] 连接:', url);
this.ws = new WebSocket(url);
this.ws.onopen = () => {
console.log('[ControlWS] 连接成功');
this.reconnectAttempts = 0;
this.startHeartbeat();
this.notifyStatusHandlers(true);
};
this.ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data) as ControlResponse;
if (message.type !== 'pong') {
console.log('[ControlWS] 收到消息:', message);
}
this.notifyMessageHandlers(message);
} catch (e) {
console.warn('[ControlWS] 解析消息失败:', e);
}
};
this.ws.onclose = (event) => {
console.log('[ControlWS] 断开:', event.code, event.reason);
this.stopHeartbeat();
this.notifyStatusHandlers(false);
// 非手动关闭,尝试重连
if (!this.manualClose && this.currentDeviceSn) {
this.scheduleReconnect();
}
};
this.ws.onerror = (error) => {
console.error('[ControlWS] 错误:', error);
};
} catch (e) {
console.error('[ControlWS] 创建失败:', e);
this.scheduleReconnect();
}
}
private scheduleReconnect(): void {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('[ControlWS] 重连次数超限,停止重连');
return;
}
this.reconnectAttempts++;
const delay = this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1);
console.log(`[ControlWS] ${delay}ms后重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
this.reconnectTimer = setTimeout(() => {
this.doConnect();
}, delay);
}
private startHeartbeat(): void {
this.stopHeartbeat();
this.heartbeatTimer = setInterval(() => {
if (this.currentDeviceSn) {
this.send({ type: 'heartbeat', deviceSn: this.currentDeviceSn });
}
}, this.heartbeatInterval);
}
private stopHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
/**
* 断开连接
*/
disconnect(): void {
this.manualClose = true;
this.currentDeviceSn = null;
this.stopHeartbeat();
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
this.ws.close(1000, 'Manual disconnect');
this.ws = null;
}
}
/**
* 发送消息
*/
private send(message: ControlMessage): boolean {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
console.warn('[ControlWS] 未连接,无法发送');
return false;
}
try {
this.ws.send(JSON.stringify(message));
return true;
} catch (e) {
console.error('[ControlWS] 发送失败:', e);
return false;
}
}
/**
* 发送摇杆控制指令
*/
sendStickControl(data: StickControlData): boolean {
if (!this.currentDeviceSn) {
console.warn('[ControlWS] 未设置设备SN');
return false;
}
return this.send({
type: 'stick_control',
deviceSn: this.currentDeviceSn,
data,
});
}
/**
* 发送云台控制指令
*/
sendGimbalControl(data: GimbalControlData): boolean {
if (!this.currentDeviceSn) {
console.warn('[ControlWS] 未设置设备SN');
return false;
}
return this.send({
type: 'gimbal_control',
deviceSn: this.currentDeviceSn,
data,
});
}
/**
* 检查是否已连接
*/
isConnected(): boolean {
return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
}
/**
* 获取当前设备SN
*/
getCurrentDeviceSn(): string | null {
return this.currentDeviceSn;
}
/**
* 添加消息处理器
*/
onMessage(handler: MessageHandler): () => void {
this.messageHandlers.push(handler);
return () => {
this.messageHandlers = this.messageHandlers.filter(h => h !== handler);
};
}
/**
* 添加状态处理器
*/
onStatusChange(handler: StatusHandler): () => void {
this.statusHandlers.push(handler);
return () => {
this.statusHandlers = this.statusHandlers.filter(h => h !== handler);
};
}
private notifyMessageHandlers(message: ControlResponse): void {
this.messageHandlers.forEach(handler => {
try {
handler(message);
} catch (e) {
console.error('[ControlWS] 消息处理器错误:', e);
}
});
}
private notifyStatusHandlers(connected: boolean): void {
this.statusHandlers.forEach(handler => {
try {
handler(connected);
} catch (e) {
console.error('[ControlWS] 状态处理器错误:', e);
}
});
}
}
// 导出单例
export const deviceControlWs = new DeviceControlWebSocket();
@@ -47,6 +47,9 @@ export interface ThreeDModelVO {
longitude: number;
latitude: number;
height: number;
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移
arcgisHeight?: number; // ArcGIS地形对应的高度偏移
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
};
transform: {
scale: number;
@@ -84,6 +87,9 @@ export interface ThreeDModelDTO {
offsetLongitude?: number;
offsetLatitude?: number;
offsetHeight?: number;
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移
arcgisHeight?: number; // ArcGIS地形对应的高度偏移
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
scale?: number;
rotationX?: number;
rotationY?: number;
@@ -306,6 +312,9 @@ export function convertToTilesetConfig(model: ThreeDModelVO) {
longitude: model.position.longitude || 0,
latitude: model.position.latitude || 0,
height: model.position.height || 0,
cesiumHeight: model.position.cesiumHeight,
arcgisHeight: model.position.arcgisHeight,
terrainType: model.position.terrainType || 'cesium_ion', // 默认使用 Cesium Ion
} : undefined,
transform: model.transform ? {
scale: model.transform.scale || 1,