feat: 3d控制指令

This commit is contained in:
2025-12-11 12:11:48 +08:00
parent 358639a8ac
commit 4921ab15ce
29 changed files with 3383 additions and 204 deletions
@@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.*;
* 设备命令控制器
* 提供HTTP接口接收前端命令请求,发送命令到设备
*
* @author lishilin
* @author dzc
* @date 2025-01-01
*/
@Slf4j
@@ -82,20 +82,42 @@ public class DeviceCommandController {
}
/**
* 一键起飞
* 一键起飞(飞向指定点)
*/
@Operation(summary = "无人机一键起飞")
@PostMapping("/takeoff")
public Result<String> takeoff(@RequestBody TakeoffRequest request) {
log.info("收到起飞命令: device={}, altitude={}", request.getDeviceSn(), request.getAltitude());
log.info("收到起飞命令: device={}, target=({}, {}), height={}",
request.getDeviceSn(), request.getTargetLatitude(), request.getTargetLongitude(), request.getTargetHeight());
try {
// 验证必要参数
if (request.getDeviceSn() == null || request.getDeviceSn().isEmpty()) {
return Result.failed("设备SN不能为空");
}
if (request.getTargetLatitude() == null || request.getTargetLongitude() == null) {
return Result.failed("目标点经纬度不能为空");
}
// 构建参数
JSONObject params = new JSONObject();
params.put("altitude", request.getAltitude() != null ? request.getAltitude() : 50);
params.put("target_latitude", request.getTargetLatitude());
params.put("target_longitude", request.getTargetLongitude());
params.put("target_height", request.getTargetHeight() != null ? request.getTargetHeight() : 100f);
params.put("security_takeoff_height", request.getSecurityTakeoffHeight() != null ? request.getSecurityTakeoffHeight() : 50f);
params.put("rth_mode", request.getRthMode() != null ? request.getRthMode() : 1); // 默认设定高度模式
params.put("rth_altitude", request.getRthAltitude() != null ? request.getRthAltitude() : 50);
params.put("rc_lost_action", request.getRcLostAction() != null ? request.getRcLostAction() : 2); // 默认返航
params.put("commander_mode_lost_action", request.getCommanderModeLostAction() != null ? request.getCommanderModeLostAction() : 1);
params.put("commander_flight_mode", request.getCommanderFlightMode() != null ? request.getCommanderFlightMode() : 1); // 默认设定高度飞行
params.put("commander_flight_height", request.getCommanderFlightHeight() != null ? request.getCommanderFlightHeight() : 50f);
params.put("flight_id", request.getFlightId() != null ? request.getFlightId() : java.util.UUID.randomUUID().toString().replace("-", "").toUpperCase());
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 5);
params.put("flight_safety_advance_check", request.getFlightSafetyAdvanceCheck() != null ? request.getFlightSafetyAdvanceCheck() : 0);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"takeoff",
"takeoff_to_point",
params
);
@@ -129,23 +151,238 @@ public class DeviceCommandController {
}
/**
* 一键降落
* 取消返航
*/
@Operation(summary = "无人机一键降落")
@PostMapping("/land")
public Result<String> land(@RequestParam String deviceSn) {
log.info("收到降落命令: device={}", deviceSn);
@Operation(summary = "取消返航")
@PostMapping("/return/cancel")
public Result<String> cancelReturnHome(@RequestParam String deviceSn) {
log.info("收到取消返航命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"land",
"return_home_cancel",
new JSONObject()
);
return Result.succeed(commandId, "降落命令已发送");
return Result.succeed(commandId, "取消返航命令已发送");
} catch (Exception e) {
log.error("发送降落命令失败: device={}, error={}", deviceSn, e.getMessage());
log.error("发送取消返航命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 航线暂停(紧急悬停)
*/
@Operation(summary = "航线暂停/紧急悬停")
@PostMapping("/pause")
public Result<String> pause(@RequestParam String deviceSn) {
log.info("收到暂停命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"flighttask_pause",
new JSONObject()
);
return Result.succeed(commandId, "暂停命令已发送");
} catch (Exception e) {
log.error("发送暂停命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 航线恢复
*/
@Operation(summary = "航线恢复")
@PostMapping("/resume")
public Result<String> resume(@RequestParam String deviceSn) {
log.info("收到恢复命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"flighttask_recovery",
new JSONObject()
);
return Result.succeed(commandId, "恢复命令已发送");
} catch (Exception e) {
log.error("发送恢复命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 拍照
*/
@Operation(summary = "无人机拍照")
@PostMapping("/photo")
public Result<String> takePhoto(@RequestParam String deviceSn) {
log.info("收到拍照命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"camera_photo_take",
new JSONObject()
);
return Result.succeed(commandId, "拍照命令已发送");
} catch (Exception e) {
log.error("发送拍照命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 开始录像
*/
@Operation(summary = "开始录像")
@PostMapping("/recording/start")
public Result<String> startRecording(@RequestParam String deviceSn) {
log.info("收到开始录像命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"camera_recording_start",
new JSONObject()
);
return Result.succeed(commandId, "开始录像命令已发送");
} catch (Exception e) {
log.error("发送开始录像命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 停止录像
*/
@Operation(summary = "停止录像")
@PostMapping("/recording/stop")
public Result<String> stopRecording(@RequestParam String deviceSn) {
log.info("收到停止录像命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"camera_recording_stop",
new JSONObject()
);
return Result.succeed(commandId, "停止录像命令已发送");
} catch (Exception e) {
log.error("发送停止录像命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 切换相机模式
*/
@Operation(summary = "切换相机模式")
@PostMapping("/camera/mode")
public Result<String> switchCameraMode(@RequestParam String deviceSn, @RequestParam Integer cameraMode) {
log.info("收到切换相机模式命令: device={}, mode={}", deviceSn, cameraMode);
try {
JSONObject params = new JSONObject();
// camera_mode: 0=拍照模式, 1=录像模式
params.put("camera_mode", cameraMode != null ? cameraMode : 0);
String commandId = commandManager.sendCommand(
deviceSn,
"camera_mode_switch",
params
);
return Result.succeed(commandId, "切换相机模式命令已发送");
} catch (Exception e) {
log.error("发送切换相机模式命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 进入指令飞行模式(DRC模式)
*/
@Operation(summary = "进入指令飞行模式")
@PostMapping("/drc/enter")
public Result<String> enterDrcMode(@RequestParam String deviceSn) {
log.info("收到进入DRC模式命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"drc_mode_enter",
new JSONObject()
);
return Result.succeed(commandId, "进入DRC模式命令已发送");
} catch (Exception e) {
log.error("发送进入DRC模式命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* DRC杆量控制
*/
@Operation(summary = "DRC杆量控制")
@PostMapping("/drc/stick")
public Result<String> stickControl(@RequestBody StickControlRequest request) {
log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}",
request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw());
try {
JSONObject params = new JSONObject();
params.put("roll", request.getRoll() != null ? request.getRoll() : 1024);
params.put("pitch", request.getPitch() != null ? request.getPitch() : 1024);
params.put("throttle", request.getThrottle() != null ? request.getThrottle() : 1024);
params.put("yaw", request.getYaw() != null ? request.getYaw() : 1024);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"stick_control",
params
);
return Result.succeed(commandId, "杆量控制命令已发送");
} catch (Exception e) {
log.error("发送杆量控制命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 云台控制
*/
@Operation(summary = "云台控制")
@PostMapping("/gimbal")
public Result<String> gimbalControl(@RequestBody GimbalControlRequest request) {
log.info("收到云台控制命令: device={}, pitchSpeed={}, yawSpeed={}, locked={}",
request.getDeviceSn(), request.getPitchSpeed(), request.getYawSpeed(), request.getLocked());
try {
JSONObject params = new JSONObject();
params.put("pitch_speed", request.getPitchSpeed() != null ? request.getPitchSpeed() : 0);
params.put("yaw_speed", request.getYawSpeed() != null ? request.getYawSpeed() : 0);
params.put("locked", request.getLocked() != null ? request.getLocked() : false);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"camera_screen_drag",
params
);
return Result.succeed(commandId, "云台控制命令已发送");
} catch (Exception e) {
log.error("发送云台控制命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
@@ -174,10 +411,71 @@ public class DeviceCommandController {
private JSONObject params;
}
/**
* 一键起飞请求参数
*/
@Data
public static class TakeoffRequest {
/** 设备SN */
private String deviceSn;
private Integer altitude; // 起飞高度(米)
/** 目标点纬度 */
private Double targetLatitude;
/** 目标点经度 */
private Double targetLongitude;
/** 目标点高度(椭球高),使用 WGS84 模型 */
private Float targetHeight;
/** 安全起飞高度,相对起飞点的高度 */
private Float securityTakeoffHeight;
/** 返航模式:0=智能高度,1=设定高度 */
private Integer rthMode;
/** 返航高度,相对起飞点的高度 */
private Integer rthAltitude;
/** 遥控器失控动作:0=悬停,1=降落,2=返航 */
private Integer rcLostAction;
/** 指点飞行失控动作:0=继续执行,1=退出任务 */
private Integer commanderModeLostAction;
/** 指点飞行模式:0=智能高度飞行,1=设定高度飞行 */
private Integer commanderFlightMode;
/** 指点飞行高度,相对起飞点的高度 */
private Float commanderFlightHeight;
/** 一键起飞任务UUID */
private String flightId;
/** 最大飞行速度(m/s),范围1-15 */
private Integer maxSpeed;
/** 飞行安全预检查:0=关闭,1=开启 */
private Integer flightSafetyAdvanceCheck;
}
/**
* DRC杆量控制请求参数
*/
@Data
public static class StickControlRequest {
/** 设备SN */
private String deviceSn;
/** 横滚通道(624-1424,1024为中值) */
private Integer roll;
/** 俯仰通道(624-1424,1024为中值) */
private Integer pitch;
/** 升降通道(624-1424,1024为悬停) */
private Integer throttle;
/** 偏航通道(624-1424,1024为中值) */
private Integer yaw;
}
/**
* 云台控制请求参数
*/
@Data
public static class GimbalControlRequest {
/** 设备SN */
private String deviceSn;
/** 云台 pitch 速度(度/秒) */
private Double pitchSpeed;
/** 云台 yaw 速度(度/秒) */
private Double yawSpeed;
/** 是否锁定机头:false=仅云台转,true=机身一起转 */
private Boolean locked;
}
@Data
@@ -95,9 +95,18 @@ public class ThreeDModelFile extends SuperEntity {
@Schema(description = "纬度偏移(度)")
private BigDecimal offsetLatitude;
@Schema(description = "高度偏移(米)")
@Schema(description = "高度偏移(米) - 通用/兼容旧数据")
private BigDecimal offsetHeight;
@Schema(description = "Cesium Ion地形对应的高度偏移(米)")
private BigDecimal cesiumHeight;
@Schema(description = "ArcGIS地形对应的高度偏移(米)")
private BigDecimal arcgisHeight;
@Schema(description = "高度偏移标定时使用的地形服务: cesium_ion/arcgis/ellipsoid")
private String terrainType;
// ========== 变换参数 ==========
@Schema(description = "缩放比例")
@@ -49,9 +49,18 @@ public class ThreeDModelFileDTO {
@Schema(description = "纬度偏移(度)", defaultValue = "0")
private BigDecimal offsetLatitude = BigDecimal.ZERO;
@Schema(description = "高度偏移(米)", defaultValue = "0")
@Schema(description = "高度偏移(米) - 通用", defaultValue = "0")
private BigDecimal offsetHeight = BigDecimal.ZERO;
@Schema(description = "Cesium Ion地形对应的高度偏移(米)")
private BigDecimal cesiumHeight;
@Schema(description = "ArcGIS地形对应的高度偏移(米)")
private BigDecimal arcgisHeight;
@Schema(description = "高度偏移标定时使用的地形服务: cesium_ion/arcgis/ellipsoid", defaultValue = "cesium_ion")
private String terrainType = "cesium_ion";
// ========== 变换参数 ==========
@Schema(description = "缩放比例", defaultValue = "1.0")
@@ -108,8 +108,17 @@ public class ThreeDModelFileVO {
@Schema(description = "纬度偏移")
private BigDecimal latitude;
@Schema(description = "高度偏移")
@Schema(description = "高度偏移 - 通用/兼容旧数据")
private BigDecimal height;
@Schema(description = "Cesium Ion地形对应的高度偏移(米)")
private BigDecimal cesiumHeight;
@Schema(description = "ArcGIS地形对应的高度偏移(米)")
private BigDecimal arcgisHeight;
@Schema(description = "高度偏移标定时使用的地形服务: cesium_ion/arcgis/ellipsoid")
private String terrainType;
}
/**
@@ -149,6 +149,18 @@ public class ThreeDModelFileServiceImpl extends SuperServiceImpl<ThreeDModelFile
if (dto.getOffsetHeight() != null) {
model.setOffsetHeight(dto.getOffsetHeight());
}
// 更新Cesium Ion地形对应的高度偏移
if (dto.getCesiumHeight() != null) {
model.setCesiumHeight(dto.getCesiumHeight());
}
// 更新ArcGIS地形对应的高度偏移
if (dto.getArcgisHeight() != null) {
model.setArcgisHeight(dto.getArcgisHeight());
}
// 更新地形类型(高度标定时使用的地形服务)
if (StrUtil.isNotBlank(dto.getTerrainType())) {
model.setTerrainType(dto.getTerrainType());
}
// 更新变换参数
if (dto.getScale() != null) {
@@ -372,6 +384,9 @@ public class ThreeDModelFileServiceImpl extends SuperServiceImpl<ThreeDModelFile
position.setLongitude(model.getOffsetLongitude());
position.setLatitude(model.getOffsetLatitude());
position.setHeight(model.getOffsetHeight());
position.setCesiumHeight(model.getCesiumHeight());
position.setArcgisHeight(model.getArcgisHeight());
position.setTerrainType(model.getTerrainType());
vo.setPosition(position);
// 设置变换配置
@@ -102,4 +102,52 @@ public class DeviceStatusSseController {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,开始接收无人机实时遥测数据
*
* @param deviceSn 设备SN
* @return 订阅结果
*/
@Operation(summary = "订阅无人机遥测数据")
@PostMapping("/drone-telemetry/{deviceSn}/subscribe")
public org.springframework.http.ResponseEntity<String> subscribeDroneTelemetry(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
log.info("订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
sseEmitterManager.subscribeDroneTelemetry(deviceSn);
return org.springframework.http.ResponseEntity.ok("无人机遥测数据订阅成功");
} catch (Exception e) {
log.error("订阅无人机遥测数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
return org.springframework.http.ResponseEntity.badRequest().body("订阅失败: " + e.getMessage());
}
}
/**
* 取消订阅无人机遥测数据(msg_alarm)
* 退出操控台时调用,停止接收无人机实时遥测数据
*
* @param deviceSn 设备SN
* @return 取消订阅结果
*/
@Operation(summary = "取消订阅无人机遥测数据")
@PostMapping("/drone-telemetry/{deviceSn}/unsubscribe")
public org.springframework.http.ResponseEntity<String> unsubscribeDroneTelemetry(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn) {
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
sseEmitterManager.unsubscribeDroneTelemetry(deviceSn);
return org.springframework.http.ResponseEntity.ok("无人机遥测数据已取消订阅");
} catch (Exception e) {
log.error("取消订阅无人机遥测数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
return org.springframework.http.ResponseEntity.badRequest().body("取消订阅失败: " + e.getMessage());
}
}
}
@@ -327,4 +327,26 @@ public class SseEmitterManager {
public int getDeviceRefCount(String deviceSn) {
return deviceRefCount.getOrDefault(deviceSn, 0);
}
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,开始接收无人机实时遥测数据
*
* @param deviceSn 设备SN
*/
public void subscribeDroneTelemetry(String deviceSn) {
log.info("订阅无人机遥测数据: deviceSn={}", deviceSn);
deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn);
}
/**
* 取消订阅无人机遥测数据(msg_alarm)
* 退出操控台时调用,停止接收无人机实时遥测数据
*
* @param deviceSn 设备SN
*/
public void unsubscribeDroneTelemetry(String deviceSn) {
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
}
}
@@ -160,10 +160,11 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
try {
String payload = message.getPayload();
// log.info("收到WebSocket消息: length={}, payload={}", payload.length(), payload);
log.debug("收到WebSocket消息: length={}", payload.length());
JSONObject json = JSON.parseObject(payload);
String type = json.getString("type");
String topic = json.getString("topic");
// 处理心跳响应
if ("pong".equals(type)) {
@@ -177,9 +178,15 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
return;
}
// 处理命令响应(/device-message-sender/...)
if (topic != null && topic.contains("/device-message-sender/")) {
handleCommandResponseMessage(json);
return;
}
// 处理订阅结果(包括各种消息类型)
// JetLinks返回的消息可能是:result、event、property等
if ("result".equals(type) || json.containsKey("requestId")) {
if ("result".equals(type) || json.containsKey("requestId") || json.containsKey("topic")) {
handleSubscriptionResult(json);
return;
}
@@ -192,6 +199,56 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
}
}
/**
* 处理命令响应消息
*/
private void handleCommandResponseMessage(JSONObject json) {
String topic = json.getString("topic");
String requestId = json.getString("id");
String deviceSn = extractDeviceSn(topic);
log.info("收到命令响应: topic={}, requestId={}, deviceSn={}", topic, requestId, deviceSn);
// 通知命令管理器处理响应
if (commandManager != null && requestId != null) {
try {
// 检查是否成功 - JetLinks响应格式可能有多种
JSONObject payload = json.getJSONObject("payload");
boolean success = false;
String message = null;
if (payload != null) {
// 检查 payload.success 或 payload.result.success
if (payload.containsKey("success")) {
success = payload.getBooleanValue("success");
message = payload.getString("message");
} else if (payload.containsKey("result")) {
JSONObject result = payload.getJSONObject("result");
if (result != null) {
success = result.getBooleanValue("success");
message = result.getString("message");
}
} else {
// 如果有 payload 但没有 success 字段,可能是成功的
success = true;
}
} else {
// 没有 payload,检查顶层是否有 success
success = json.getBooleanValue("success");
message = json.getString("message");
}
log.info("命令响应解析: requestId={}, success={}, message={}", requestId, success, message);
commandManager.getClass()
.getMethod("handleCommandResponse", String.class, boolean.class, String.class)
.invoke(commandManager, requestId, success, message);
} catch (Exception e) {
log.warn("调用命令管理器处理响应失败: {}", e.getMessage());
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
log.warn("WebSocket连接关闭: code={}, reason={}, isAutoClose={}, isManualClose={}",
@@ -252,7 +309,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
// 从topic中提取deviceSn
String deviceSn = extractDeviceSn(topic);
if (deviceSn == null) {
log.warn("无法从topic提取deviceSn: {}", topic);
// 可能是其他类型的响应,打印日志但不阻断
log.debug("无法从topic提取deviceSn,可能是非设备消息: topic={}", topic);
return;
}
@@ -291,15 +349,25 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
/**
* 从topic中提取deviceSn
* topic格式: /device/D-Dock2/{deviceSn}/...
* 支持的topic格式:
* 1. /device/D-Dock2/{deviceSn}/... (订阅消息)
* 2. /device-message-sender/D-Dock2/{deviceSn} (命令响应)
*/
private String extractDeviceSn(String topic) {
if (topic == null || !topic.startsWith("/device/D-Dock2/")) {
if (topic == null) {
log.warn("无法从topic提取deviceSn: {}", topic);
return null;
}
String[] parts = topic.split("/");
if (parts.length >= 4) {
// 格式1: /device/D-Dock2/{deviceSn}/...
if (topic.startsWith("/device/D-Dock2/") && parts.length >= 4) {
return parts[3];
}
// 格式2: /device-message-sender/D-Dock2/{deviceSn}
if (topic.startsWith("/device-message-sender/D-Dock2/") && parts.length >= 4) {
return parts[3];
}
@@ -449,12 +517,13 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
}
});
// 为每个设备重新订阅标准主题(只订阅关键主题)
// 为每个设备重新订阅标准主题(订阅关键主题)
deviceSns.forEach(deviceSn -> {
subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm最重要
SubscriptionTopic.EVENT_FIRE_ALARM, // fire_alarm(机库状态数据)
SubscriptionTopic.EVENT_MSG_ALARM // msg_alarm(无人机遥测数据)
);
});
}
@@ -0,0 +1,30 @@
package com.central.device.websocket.config;
import com.central.device.websocket.handler.DeviceControlWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* 设备控制WebSocket配置
* 用于云台控制和摇杆控制的高频实时通信
*
* @author lishilin
* @date 2025-01-19
*/
@Configuration
@EnableWebSocket
public class DeviceControlWebSocketConfig implements WebSocketConfigurer {
@Autowired
private DeviceControlWebSocketHandler deviceControlWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// 注册WebSocket端点,路径格式: /ws/control/{deviceSn}
registry.addHandler(deviceControlWebSocketHandler, "/ws/control/*")
.setAllowedOrigins("*"); // 生产环境应配置具体域名
}
}
@@ -7,7 +7,7 @@ import org.springframework.stereotype.Component;
/**
* WebSocket配置属性
*
* @author lishilin
* @author dzc
* @date 2025-01-01
*/
@Data
@@ -0,0 +1,309 @@
package com.central.device.websocket.handler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.config.WebSocketProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 设备控制WebSocket处理器
* 处理前端发送的高频控制指令(云台、摇杆)
* 直接转发到JetLinks WebSocket
*
* @author lishilin
* @date 2025-01-19
*/
@Slf4j
@Component
public class DeviceControlWebSocketHandler extends TextWebSocketHandler {
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
@Autowired
private WebSocketProperties properties;
/**
* 活跃的WebSocket会话: sessionId -> WebSocketSession
*/
private final Map<String, WebSocketSession> activeSessions = new ConcurrentHashMap<>();
/**
* 会话对应的设备SN: sessionId -> deviceSn
*/
private final Map<String, String> sessionDeviceMap = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 从URL路径中提取deviceSn: /ws/control/{deviceSn}
String path = session.getUri().getPath();
String deviceSn = extractDeviceSn(path);
if (deviceSn == null || deviceSn.isEmpty()) {
log.warn("无效的WebSocket连接,缺少deviceSn: path={}", path);
session.close(CloseStatus.BAD_DATA.withReason("Missing deviceSn"));
return;
}
String sessionId = session.getId();
activeSessions.put(sessionId, session);
sessionDeviceMap.put(sessionId, deviceSn);
log.info("设备控制WebSocket连接建立: sessionId={}, deviceSn={}", sessionId, deviceSn);
// 确保JetLinks WebSocket已连接
if (!jetLinksWebSocketClient.isConnected()) {
log.info("JetLinks WebSocket未连接,自动建立连接");
jetLinksWebSocketClient.connect();
}
// 发送连接成功消息
sendResponse(session, "response", true, "连接成功", null);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String sessionId = session.getId();
String deviceSn = sessionDeviceMap.get(sessionId);
if (deviceSn == null) {
log.warn("未知会话收到消息: sessionId={}", sessionId);
return;
}
try {
String payload = message.getPayload();
JSONObject json = JSON.parseObject(payload);
String type = json.getString("type");
switch (type) {
case "heartbeat":
// 心跳响应
sendPong(session);
break;
case "stick_control":
// 摇杆控制
handleStickControl(session, deviceSn, json.getJSONObject("data"));
break;
case "gimbal_control":
// 云台控制
handleGimbalControl(session, deviceSn, json.getJSONObject("data"));
break;
default:
log.warn("未知消息类型: type={}, sessionId={}", type, sessionId);
sendResponse(session, "error", false, "未知消息类型: " + type, null);
}
} catch (Exception e) {
log.error("处理控制消息失败: sessionId={}, error={}", sessionId, e.getMessage());
sendResponse(session, "error", false, "消息处理失败: " + e.getMessage(), null);
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
String sessionId = session.getId();
String deviceSn = sessionDeviceMap.remove(sessionId);
activeSessions.remove(sessionId);
log.info("设备控制WebSocket连接关闭: sessionId={}, deviceSn={}, status={}",
sessionId, deviceSn, status);
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
String sessionId = session.getId();
log.error("设备控制WebSocket传输错误: sessionId={}, error={}", sessionId, exception.getMessage());
}
/**
* 处理摇杆控制
*/
private void handleStickControl(WebSocketSession session, String deviceSn, JSONObject data) {
if (data == null) {
sendResponse(session, "error", false, "缺少控制数据", null);
return;
}
// 构建JetLinks命令
JSONObject params = new JSONObject();
params.put("roll", data.getIntValue("roll") != 0 ? data.getIntValue("roll") : 1024);
params.put("pitch", data.getIntValue("pitch") != 0 ? data.getIntValue("pitch") : 1024);
params.put("throttle", data.getIntValue("throttle") != 0 ? data.getIntValue("throttle") : 1024);
params.put("yaw", data.getIntValue("yaw") != 0 ? data.getIntValue("yaw") : 1024);
String commandId = sendToJetLinks(deviceSn, "stick_control", params);
if (commandId != null) {
sendResponse(session, "response", true, "摇杆指令已发送", commandId);
} else {
sendResponse(session, "error", false, "摇杆指令发送失败", null);
}
}
/**
* 处理云台控制
*/
private void handleGimbalControl(WebSocketSession session, String deviceSn, JSONObject data) {
if (data == null) {
sendResponse(session, "error", false, "缺少控制数据", null);
return;
}
// 构建JetLinks命令
JSONObject params = new JSONObject();
params.put("pitch_speed", data.getDoubleValue("pitchSpeed"));
params.put("yaw_speed", data.getDoubleValue("yawSpeed"));
params.put("locked", data.getBooleanValue("locked"));
String commandId = sendToJetLinks(deviceSn, "camera_screen_drag", params);
if (commandId != null) {
sendResponse(session, "response", true, "云台指令已发送", commandId);
} else {
sendResponse(session, "error", false, "云台指令发送失败", null);
}
}
/**
* 发送命令到JetLinks
*
* @return commandId 或 null(失败时)
*/
private String sendToJetLinks(String deviceSn, String method, JSONObject data) {
if (!jetLinksWebSocketClient.isConnected()) {
log.warn("JetLinks WebSocket未连接,尝试重连");
jetLinksWebSocketClient.connect();
// 等待连接(最多1秒,避免阻塞高频控制)
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 10) {
try {
Thread.sleep(100);
waitCount++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
}
if (!jetLinksWebSocketClient.isConnected()) {
log.error("JetLinks WebSocket连接失败");
return null;
}
}
try {
String commandId = UUID.randomUUID().toString();
// 构造 properties
JSONObject properties = new JSONObject();
properties.put("method", method);
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
// 构造 parameter
JSONObject parameter = new JSONObject();
parameter.put("messageType", "WRITE_PROPERTY");
parameter.put("properties", properties);
JSONObject headers = new JSONObject();
headers.put("async", false);
parameter.put("headers", headers);
// 构造完整消息
JSONObject message = new JSONObject();
message.put("type", "sub");
message.put("topic", "/device-message-sender/D-Dock2/" + deviceSn);
message.put("parameter", parameter);
message.put("id", commandId);
// 发送
String messageJson = message.toJSONString();
log.debug("发送实时控制命令: deviceSn={}, method={}, commandId={}", deviceSn, method, commandId);
jetLinksWebSocketClient.send(messageJson);
return commandId;
} catch (Exception e) {
log.error("发送JetLinks命令失败: deviceSn={}, method={}, error={}", deviceSn, method, e.getMessage());
return null;
}
}
/**
* 发送响应消息
*/
private void sendResponse(WebSocketSession session, String type, boolean success, String message, String commandId) {
try {
JSONObject response = new JSONObject();
response.put("type", type);
response.put("success", success);
response.put("message", message);
if (commandId != null) {
response.put("commandId", commandId);
}
session.sendMessage(new TextMessage(response.toJSONString()));
} catch (IOException e) {
log.error("发送响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
}
}
/**
* 发送心跳响应
*/
private void sendPong(WebSocketSession session) {
try {
JSONObject pong = new JSONObject();
pong.put("type", "pong");
pong.put("timestamp", System.currentTimeMillis());
session.sendMessage(new TextMessage(pong.toJSONString()));
} catch (IOException e) {
log.error("发送心跳响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
}
}
/**
* 从路径中提取deviceSn
* 路径格式: /ws/control/{deviceSn}
*/
private String extractDeviceSn(String path) {
if (path == null) return null;
// 移除末尾的斜杠
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
// 提取最后一段作为deviceSn
int lastSlash = path.lastIndexOf('/');
if (lastSlash >= 0 && lastSlash < path.length() - 1) {
return path.substring(lastSlash + 1);
}
return null;
}
/**
* 获取活跃连接数
*/
public int getActiveConnectionCount() {
return activeSessions.size();
}
}
@@ -331,7 +331,11 @@ public class DeviceMessageHandler {
extractKeyFields(data, mergedDockData);
// 保存合并后的完整设备状态数据
JSONObject rawData = new JSONObject();
// 【重要】保留现有的 rawData,避免覆盖 droneData
JSONObject rawData = data.getRawData();
if (rawData == null) {
rawData = new JSONObject();
}
rawData.put("eventType", "device_state");
rawData.put("messageId", messageId);
rawData.put("timestamp", timestamp);
@@ -406,7 +410,8 @@ public class DeviceMessageHandler {
alarmDataService.saveMsgAlarmData(deviceSn, msgAlarmData);
}
log.debug("处理 msg_alarm 事件: deviceSn={}, timestamp={}", deviceSn, timestamp);
log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}",
deviceSn, timestamp, droneData.keySet());
// 触发 msg_alarm 回调(用于一次性订阅)
BiConsumer<String, JSONObject> msgAlarmCallback = msgAlarmCallbacks.get(deviceSn);
@@ -418,7 +423,7 @@ public class DeviceMessageHandler {
}
}
// 如果设备已在 deviceDataMap 中注册,更新其数据
// 如果设备已在 deviceDataMap 中注册,更新其数据并推送SSE
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data != null) {
data.setOnline(true);
@@ -426,6 +431,19 @@ public class DeviceMessageHandler {
// 从 droneData 提取关键字段更新到 DeviceRealtimeData
extractDroneKeyFields(data, droneData);
// 将 msg_alarm 数据合并到 rawData 中
JSONObject rawData = data.getRawData();
if (rawData == null) {
rawData = new JSONObject();
}
// 只保留 droneData,不再重复存储 msgAlarmData
// 前端直接从 rawData.droneData 读取无人机遥测数据
rawData.put("droneData", droneData);
data.setRawData(rawData);
// 推送到前端(通过SSE)
pushDeviceDataUpdate(data);
}
} catch (Exception e) {
@@ -118,22 +118,49 @@ public class DeviceCommandManager {
/**
* 立即发送命令(通过全局WebSocket客户端)
*
* WebSocket发送指令JSON格式:
* {
* "type": "sub",
* "topic": "/device-message-sender/D-Dock2/{deviceSn}",
* "parameter": {
* "messageType": "WRITE_PROPERTY",
* "properties": {指令JSON},
* "headers": {
* "async": false
* }
* },
* "id": "request-id-xxx"
* }
*/
private void sendCommandImmediately(DeviceCommand command) {
try {
command.setStatus(CommandStatus.SENDING);
command.setSendTime(System.currentTimeMillis());
// 构造命令消息
// TODO: 根据JetLinks平台实际API调整消息格式
// 构造指令内容 (properties)
JSONObject properties = buildCommandProperties(command);
// 构造 parameter
JSONObject parameter = new JSONObject();
parameter.put("messageType", "WRITE_PROPERTY");
parameter.put("properties", properties);
JSONObject headers = new JSONObject();
headers.put("async", false);
parameter.put("headers", headers);
// 构造完整消息
JSONObject message = new JSONObject();
message.put("messageId", command.getCommandId());
message.put("deviceId", command.getDeviceSn());
message.put("command", command.getCommandType());
message.put("params", command.getParams());
message.put("type", "sub");
message.put("topic", "/device-message-sender/D-Dock2/" + command.getDeviceSn());
message.put("parameter", parameter);
message.put("id", command.getCommandId());
// 通过全局WebSocket发送
jetLinksWebSocketClient.send(message.toJSONString());
String messageJson = message.toJSONString();
log.info("发送命令消息: {}", messageJson);
jetLinksWebSocketClient.send(messageJson);
command.setStatus(CommandStatus.SENT);
@@ -153,6 +180,102 @@ public class DeviceCommandManager {
}
}
/**
* 根据命令类型构造 properties 内容
*
* @param command 命令对象
* @return properties JSON
*/
private JSONObject buildCommandProperties(DeviceCommand command) {
JSONObject properties = new JSONObject();
JSONObject data = new JSONObject();
String method = command.getCommandType();
JSONObject params = command.getParams();
switch (method) {
case "takeoff_to_point":
// 一键起飞
data.put("target_latitude", params.getDoubleValue("target_latitude"));
data.put("target_longitude", params.getDoubleValue("target_longitude"));
data.put("target_height", params.getFloatValue("target_height"));
data.put("security_takeoff_height", params.getFloatValue("security_takeoff_height"));
data.put("rth_mode", params.getIntValue("rth_mode"));
data.put("rth_altitude", params.getIntValue("rth_altitude"));
data.put("rc_lost_action", params.getIntValue("rc_lost_action"));
data.put("commander_mode_lost_action", params.getIntValue("commander_mode_lost_action"));
data.put("commander_flight_mode", params.getIntValue("commander_flight_mode"));
data.put("commander_flight_height", params.getFloatValue("commander_flight_height"));
data.put("flight_id", params.getString("flight_id"));
data.put("max_speed", params.getIntValue("max_speed"));
data.put("flight_safety_advance_check", params.getIntValue("flight_safety_advance_check"));
break;
case "return_home":
// 一键返航 - 无参数
break;
case "return_home_cancel":
// 返航取消 - 无参数
break;
case "flighttask_pause":
// 航线暂停 - 无参数
break;
case "flighttask_recovery":
// 航线恢复 - 无参数
break;
case "drc_mode_enter":
// 进入指令飞行模式 - 无参数
break;
case "camera_photo_take":
// 拍照 - 无参数
break;
case "camera_recording_start":
// 开始录像 - 无参数
break;
case "camera_recording_stop":
// 停止录像 - 无参数
break;
case "camera_mode_switch":
// 切换相机模式
data.put("camera_mode", params.getIntValue("camera_mode"));
break;
case "stick_control":
// DRC杆量控制
data.put("roll", params.getIntValue("roll"));
data.put("pitch", params.getIntValue("pitch"));
data.put("throttle", params.getIntValue("throttle"));
data.put("yaw", params.getIntValue("yaw"));
break;
case "camera_screen_drag":
// 云台画面拖动控制
data.put("pitch_speed", params.getDoubleValue("pitch_speed"));
data.put("yaw_speed", params.getDoubleValue("yaw_speed"));
data.put("locked", params.getBooleanValue("locked"));
break;
default:
// 其他命令,直接使用 params 作为 data
data = params;
break;
}
properties.put("method", method);
JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data);
properties.put("data", dataWrapper);
return properties;
}
/**
* 加入队列
*/
@@ -132,7 +132,8 @@ public class DeviceSubscriptionManager {
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
SubscriptionTopic.EVENT_FIRE_ALARM,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
messageHandler.removeDevice(deviceSn);
log.debug("取消订阅设备: {}", deviceSn);
@@ -199,7 +200,8 @@ public class DeviceSubscriptionManager {
deviceSn,
SubscriptionTopic.ONLINE, // 设备上线
SubscriptionTopic.OFFLINE, // 设备离线
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(最重要)
SubscriptionTopic.EVENT_FIRE_ALARM, // fire_alarm事件(机库状态数据)
SubscriptionTopic.EVENT_MSG_ALARM // msg_alarm事件(无人机遥测数据)
);
log.info("设备 {} 订阅成功(景区: {})", deviceSn, scenicId);
@@ -234,6 +236,7 @@ public class DeviceSubscriptionManager {
/**
* 订阅单个设备(v3.0新增)
* 用于SSE懒加载模式,只订阅用户请求的设备
* 【优化】只订阅机库状态数据(fire_alarm),无人机遥测数据(msg_alarm)在进入操控台时单独订阅
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
@@ -248,21 +251,21 @@ public class DeviceSubscriptionManager {
try {
// 添加设备到数据Map(scenicId使用0表示单设备订阅)
// log.info("准备添加设备到数据Map: deviceSn={}, tenantId={}", deviceSn, tenantId);
messageHandler.addDevice(deviceSn, 0L, tenantId);
// log.info("设备已添加到数据Map");
// 通过全局WebSocket客户端订阅设备(会自动触发懒加载连接)
// 只订阅关键主题:上线、离线、fire_alarm(包含设备完整状态数据)
log.info("准备订阅WebSocket主题: deviceSn={}", deviceSn);
// 【优化】只订阅机库相关主题:上线、离线、fire_alarm(机库状态)
// 无人机遥测数据(msg_alarm)在进入操控台时单独订阅,因为大部分时间无人机不在线
log.info("准备订阅WebSocket主题(机库数据): deviceSn={}", deviceSn);
jetLinksWebSocketClient.subscribeDevice(
deviceSn,
SubscriptionTopic.ONLINE, // 设备上线
SubscriptionTopic.OFFLINE, // 设备离线
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(最重要,包含电池、GPS等完整数据)
SubscriptionTopic.EVENT_FIRE_ALARM // fire_alarm事件(机库状态数据)
// 【移除】SubscriptionTopic.EVENT_MSG_ALARM - 无人机遥测数据在操控台单独订阅
);
log.info("设备 {} 订阅成功(包括WebSocket订阅)", deviceSn);
log.info("设备 {} 订阅成功(机库数据)", deviceSn);
} catch (Exception e) {
log.error("设备 {} 订阅失败: {}", deviceSn, e.getMessage(), e);
@@ -288,7 +291,8 @@ public class DeviceSubscriptionManager {
deviceSn,
SubscriptionTopic.ONLINE,
SubscriptionTopic.OFFLINE,
SubscriptionTopic.EVENT_FIRE_ALARM
SubscriptionTopic.EVENT_FIRE_ALARM,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
// 移除设备数据
@@ -300,4 +304,60 @@ public class DeviceSubscriptionManager {
log.error("取消订阅设备 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 订阅无人机遥测数据(msg_alarm)
* 进入操控台时调用,只订阅无人机遥测数据,不影响机库状态订阅
*
* @param deviceSn 设备SN
*/
public void subscribeDroneTelemetry(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("设备SN为空,无法订阅无人机遥测");
return;
}
log.info("订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
// 只订阅 msg_alarm 主题
jetLinksWebSocketClient.subscribeDevice(
deviceSn,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
log.info("无人机遥测数据 {} 订阅成功", deviceSn);
} catch (Exception e) {
log.error("订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 取消订阅无人机遥测数据(msg_alarm)
* 退出操控台时调用,只取消无人机遥测数据订阅,不影响机库状态订阅
*
* @param deviceSn 设备SN
*/
public void unsubscribeDroneTelemetry(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("设备SN为空,无法取消订阅无人机遥测");
return;
}
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
// 只取消 msg_alarm 主题
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
log.info("无人机遥测数据 {} 订阅已取消", deviceSn);
} catch (Exception e) {
log.error("取消订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
}