From 4921ab15ce10397c74ab7a0d5ef57557790570d4 Mon Sep 17 00:00:00 2001 From: duzhichao <1098974448@qq.com> Date: Thu, 11 Dec 2025 12:11:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=203d=E6=8E=A7=E5=88=B6=E6=8C=87=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/settings.local.json | 4 +- zlt-business/device-center/doc/指令飞行.md | 307 ++++++++ .../device-center/sql/3d_model_file.sql | 24 + .../controller/DeviceCommandController.java | 326 +++++++- .../central/device/model/ThreeDModelFile.java | 11 +- .../device/model/dto/ThreeDModelFileDTO.java | 11 +- .../device/model/vo/ThreeDModelFileVO.java | 11 +- .../impl/ThreeDModelFileServiceImpl.java | 15 + .../controller/DeviceStatusSseController.java | 48 ++ .../device/sse/manager/SseEmitterManager.java | 22 + .../client/JetLinksWebSocketClient.java | 85 ++- .../config/DeviceControlWebSocketConfig.java | 30 + .../websocket/config/WebSocketProperties.java | 2 +- .../DeviceControlWebSocketHandler.java | 309 ++++++++ .../handler/DeviceMessageHandler.java | 24 +- .../manager/DeviceCommandManager.java | 137 +++- .../manager/DeviceSubscriptionManager.java | 78 +- zlt-web/react-web-next/.env.local | 2 +- .../components/ModelPreviewModal.less | 42 ++ .../components/ModelPreviewModal.tsx | 281 ++++++- .../mapDashboard/TourismDeviceDetail.tsx | 166 +++- .../3d/BottomPanel/LeftControlPanel.tsx | 713 ++++++++++++++++-- .../3d/BottomPanel/RightPanel.tsx | 86 ++- .../MapContainer/3d/hooks/useDeviceSSE.ts | 58 +- .../MapContainer/3d/hooks/useTilesetLoader.ts | 31 +- .../MapContainer/CesiumContainer.tsx | 191 ++++- zlt-web/react-web-next/src/services/device.ts | 282 +++++++ .../src/services/deviceControlWs.ts | 282 +++++++ .../src/services/threeDModel.ts | 9 + 29 files changed, 3383 insertions(+), 204 deletions(-) create mode 100644 zlt-business/device-center/doc/指令飞行.md create mode 100644 zlt-business/device-center/src/main/java/com/central/device/websocket/config/DeviceControlWebSocketConfig.java create mode 100644 zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceControlWebSocketHandler.java create mode 100644 zlt-web/react-web-next/src/services/deviceControlWs.ts diff --git a/.claude/settings.local.json b/.claude/settings.local.json index cdcf4c2b..cf025029 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -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": [] diff --git a/zlt-business/device-center/doc/指令飞行.md b/zlt-business/device-center/doc/指令飞行.md new file mode 100644 index 00000000..114ad2b8 --- /dev/null +++ b/zlt-business/device-center/doc/指令飞行.md @@ -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 | | 可选字段,用于在室内进行模拟任务调试。
注意:进行模拟飞行前,请务必取下桨叶,以防舱盖关闭时夹断桨叶。 | +| »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" +} \ No newline at end of file diff --git a/zlt-business/device-center/sql/3d_model_file.sql b/zlt-business/device-center/sql/3d_model_file.sql index 10af1fed..f0cee5dd 100644 --- a/zlt-business/device-center/sql/3d_model_file.sql +++ b/zlt-business/device-center/sql/3d_model_file.sql @@ -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`; diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java index 48e48d13..da4a7c93 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java @@ -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 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 land(@RequestParam String deviceSn) { - log.info("收到降落命令: device={}", deviceSn); + @Operation(summary = "取消返航") + @PostMapping("/return/cancel") + public Result 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 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 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 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 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 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 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 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 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 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 diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/ThreeDModelFile.java b/zlt-business/device-center/src/main/java/com/central/device/model/ThreeDModelFile.java index 773279ee..6c21a89b 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/ThreeDModelFile.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/ThreeDModelFile.java @@ -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 = "缩放比例") diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/dto/ThreeDModelFileDTO.java b/zlt-business/device-center/src/main/java/com/central/device/model/dto/ThreeDModelFileDTO.java index a61e15d6..fefdf0ce 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/dto/ThreeDModelFileDTO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/dto/ThreeDModelFileDTO.java @@ -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") diff --git a/zlt-business/device-center/src/main/java/com/central/device/model/vo/ThreeDModelFileVO.java b/zlt-business/device-center/src/main/java/com/central/device/model/vo/ThreeDModelFileVO.java index c0f8a88a..6300ed47 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/model/vo/ThreeDModelFileVO.java +++ b/zlt-business/device-center/src/main/java/com/central/device/model/vo/ThreeDModelFileVO.java @@ -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; } /** diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/impl/ThreeDModelFileServiceImpl.java b/zlt-business/device-center/src/main/java/com/central/device/service/impl/ThreeDModelFileServiceImpl.java index 7e19af55..a42d29f5 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/impl/ThreeDModelFileServiceImpl.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/impl/ThreeDModelFileServiceImpl.java @@ -149,6 +149,18 @@ public class ThreeDModelFileServiceImpl extends SuperServiceImpl 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 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()); + } + } } diff --git a/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java b/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java index 2e83874a..3c3826fe 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java +++ b/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java @@ -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); + } } diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java index 29baf3e3..afc64cf3 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java @@ -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(无人机遥测数据) ); }); } diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/config/DeviceControlWebSocketConfig.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/config/DeviceControlWebSocketConfig.java new file mode 100644 index 00000000..7f9d2a19 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/config/DeviceControlWebSocketConfig.java @@ -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("*"); // 生产环境应配置具体域名 + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/config/WebSocketProperties.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/config/WebSocketProperties.java index d5ec4cd1..c41ef9c6 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/config/WebSocketProperties.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/config/WebSocketProperties.java @@ -7,7 +7,7 @@ import org.springframework.stereotype.Component; /** * WebSocket配置属性 * - * @author lishilin + * @author dzc * @date 2025-01-01 */ @Data diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceControlWebSocketHandler.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceControlWebSocketHandler.java new file mode 100644 index 00000000..5e7e2960 --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceControlWebSocketHandler.java @@ -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 activeSessions = new ConcurrentHashMap<>(); + + /** + * 会话对应的设备SN: sessionId -> deviceSn + */ + private final Map 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(); + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java index c92fc0cb..2ec49727 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java @@ -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 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) { diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java index f7d8e2e7..307131b8 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java @@ -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; + } + /** * 加入队列 */ diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceSubscriptionManager.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceSubscriptionManager.java index e4a7c0af..db0453dd 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceSubscriptionManager.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceSubscriptionManager.java @@ -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); + } + } } diff --git a/zlt-web/react-web-next/.env.local b/zlt-web/react-web-next/.env.local index 910fdd77..3b2333f2 100644 --- a/zlt-web/react-web-next/.env.local +++ b/zlt-web/react-web-next/.env.local @@ -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服务配置 ========== diff --git a/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.less b/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.less index 507a0812..b4530ec6 100644 --- a/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.less +++ b/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.less @@ -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; + } } } diff --git a/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.tsx b/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.tsx index 848f4b3f..30c5817f 100644 --- a/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.tsx +++ b/zlt-web/react-web-next/src/pages/device/ThreeDModel/components/ModelPreviewModal.tsx @@ -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 = ({ const [saving, setSaving] = useState(false); const [modelHeight, setModelHeight] = useState(null); // 模型原始高度 const [suggestedOffset, setSuggestedOffset] = useState(0); // 建议的偏移值 + const [currentTerrainType, setCurrentTerrainType] = useState('cesium_ion'); // 当前使用的地形类型 + const [terrainSwitching, setTerrainSwitching] = useState(false); // 是否正在切换地形 // 清理函数 const cleanup = useCallback(() => { @@ -104,12 +106,39 @@ const ModelPreviewModal: React.FC = ({ 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 = ({ } }; + /** + * 切换地形类型 + * 重新加载指定类型的地形,并应用对应的高度偏移值 + */ + 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 = ({ setLoading(true); setError(null); - // 初始化高度偏移为模型当前配置的值 - const initialHeight = model.position?.height || 0; - setHeightOffset(initialHeight); - try { // 动态加载Cesium if (!Cesium) { @@ -139,15 +221,98 @@ const ModelPreviewModal: React.FC = ({ 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 = ({ 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 = ({ // 保存原始中心点(用于高度调整计算) 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 = ({ {initialized && (
- 🎚️ 高度调整(模型在空中飘着?向下调整;模型陷入地面?向上调整) + 高度偏移调整(微调模型高度以匹配地形,正值上移、负值下移) +
+ + {/* 地形切换和已保存高度信息 */} +
+
+ 选择地形: + switchTerrain(e.target.value)} + disabled={terrainSwitching} + optionType="button" + buttonStyle="solid" + size="small" + > + Cesium Ion + ArcGIS + + {terrainSwitching && } +
+ + + +
+ 已保存高度: + + + Cesium Ion + + {model?.position?.cesiumHeight !== undefined && model?.position?.cesiumHeight !== null + ? `${model.position.cesiumHeight}米` + : '未设置'} + + + + ArcGIS + + {model?.position?.arcgisHeight !== undefined && model?.position?.arcgisHeight !== null + ? `${model.position.arcgisHeight}米` + : '未设置'} + + + +
{/* 模型高度信息 */} {modelHeight !== null && (
- 模型原始高度: + 模型海拔高度: {modelHeight} 米
- 建议偏移值: - {suggestedOffset} 米 - + 当前偏移: + {heightOffset} 米 +
+
+ + 提示: 分别切换到两种地形调整并保存高度,这样两种地形服务都能正确显示模型 +
)} @@ -361,11 +570,17 @@ const ModelPreviewModal: React.FC = ({ - + + + - - - +
+ + + {/* 相机控制 */} +
+
+ 相机控制 / CAMERA + + {cameraMode === 'photo' ? '拍照模式' : '录像模式'} + +
+
+ + {!isRecording ? ( + + ) : ( + + )} +
{/* 飞行姿态控制 (模拟双摇杆) */}
-
姿态控制 / ATTITUDE CONTROL
+
+ 姿态控制 / ATTITUDE CONTROL + + + {wsConnected ? ( + + ) : ( + + )} + + + {drcMode && ( + DRC模式 + )} +
{/* 左手:升降 + 转向 */}
升降 & 偏航 (Left)
- - - - + + + +
@@ -163,10 +715,10 @@ const LeftControlPanel: React.FC = ({
水平移动 (Right)
- - - - + + + +
@@ -174,15 +726,20 @@ const LeftControlPanel: React.FC = ({ {/* 云台控制 */}
-
云台控制 / GIMBAL
+
+ 云台控制 / GIMBAL + {drcMode && ( + DRC模式 + )} +
云台方向
- - - - + + + +
diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx index eac9da0b..50a3ada9 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx @@ -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 = ({ - visible, - tourism, +const RightPanel: React.FC = ({ + visible, + tourism, onClose, - onControlClick + onControlClick }) => { const [deviceList, setDeviceList] = useState([]); const [selectedDeviceSn, setSelectedDeviceSn] = useState(''); const [loading, setLoading] = useState(false); + const [takeoffLoading, setTakeoffLoading] = useState(false); const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE(); @@ -85,6 +87,73 @@ const RightPanel: React.FC = ({ 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: ( +
+

无人机将自动开机并起飞到指定位置

+

+ 目标坐标: {dockLatitude.toFixed(6)}, {dockLongitude.toFixed(6)}
+ 目标高度: {(dockHeight + 30).toFixed(1)}m (机库高度+30m) +

+
+ ), + 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') => (
{label}
@@ -190,8 +259,11 @@ const RightPanel: React.FC = ({ -
diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts index 50769ab6..682c8572 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts @@ -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; }; } diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts index f48b7485..23d858d3 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useTilesetLoader.ts @@ -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; - loadTileset: (config: TilesetConfig, viewer: any, Cesium: any) => Promise; + loadTileset: (config: TilesetConfig, viewer: any, Cesium: any, currentTerrainType?: string) => Promise; 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 => { 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; diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx index 5f7191c6..d8677e48 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx @@ -33,8 +33,10 @@ const CesiumContainer: React.FC = (props) => { // 3D Tiles 模型管理 const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false); - const [currentTourismModels, setCurrentTourismModels] = useState([]); // 当前景区的模型 + const [currentTourismModels, setCurrentTourismModels] = useState([]); // 当前景区的所有模型配置 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 = (props) => { }); }, []); - // 加载景区绑定的模型,返回是否有模型 + /** + * 动态切换到高程地形 + * 在进入景区详情、加载3D模型时调用 + * @param preferredTerrainType 优先使用的地形类型(从模型配置中获取) + */ + const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise => { + 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 => { if (!viewerRef.current || !Cesium) { console.log('Viewer或Cesium未准备好'); @@ -101,39 +196,63 @@ const CesiumContainer: React.FC = (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 = (props) => { setModelLoading(false); return false; } - }, [loadTileset, unloadAllTilesets]); + }, [loadTileset, unloadAllTilesets, switchToElevationTerrain]); // 处理景区点击 const handleTourismSelect = useCallback((tourism: any) => { @@ -234,6 +353,13 @@ const CesiumContainer: React.FC = (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 = (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 = (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 = (props) => {
)} - {/* 模型加载中提示 */} - {modelLoading && ( + {/* 地形/模型加载中提示 */} + {(terrainLoading || modelLoading) && (
= (props) => { zIndex: 800, }} > - 正在加载3D模型... + {terrainLoading ? '正在加载高程地形...' : '正在加载3D模型...'}
)} diff --git a/zlt-web/react-web-next/src/services/device.ts b/zlt-web/react-web-next/src/services/device.ts index 295547d5..761b4d98 100644 --- a/zlt-web/react-web-next/src/services/device.ts +++ b/zlt-web/react-web-next/src/services/device.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 }; + } + }, }; diff --git a/zlt-web/react-web-next/src/services/deviceControlWs.ts b/zlt-web/react-web-next/src/services/deviceControlWs.ts new file mode 100644 index 00000000..1159c13e --- /dev/null +++ b/zlt-web/react-web-next/src/services/deviceControlWs.ts @@ -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(); diff --git a/zlt-web/react-web-next/src/services/threeDModel.ts b/zlt-web/react-web-next/src/services/threeDModel.ts index 82b6d110..4cc7e643 100644 --- a/zlt-web/react-web-next/src/services/threeDModel.ts +++ b/zlt-web/react-web-next/src/services/threeDModel.ts @@ -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,