Merge pull request 'feat: 通过接口获取机库和无人机数据' (#9) from feature_dzc into test
Reviewed-on: http://220.205.16.27:18081/goflytec/GoFly-platform-services/pulls/9
This commit is contained in:
@@ -63,7 +63,8 @@
|
|||||||
"Bash(cmd /c del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\websocket\\handler\\DeviceControlWebSocketHandler.java\")",
|
"Bash(cmd /c del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\websocket\\handler\\DeviceControlWebSocketHandler.java\")",
|
||||||
"Bash(tree:*)",
|
"Bash(tree:*)",
|
||||||
"Bash(move \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-business\\\\order-center\\\\src\\\\main\\\\resources\\\\mapper\\\\mission\\\\MissionMapper.xml\" \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-business\\\\order-center\\\\src\\\\main\\\\resources\\\\mapper\\\\MissionMapper.xml\")",
|
"Bash(move \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-business\\\\order-center\\\\src\\\\main\\\\resources\\\\mapper\\\\mission\\\\MissionMapper.xml\" \"F:\\\\project\\\\go-fly-platform-services\\\\zlt-business\\\\order-center\\\\src\\\\main\\\\resources\\\\mapper\\\\MissionMapper.xml\")",
|
||||||
"Bash(cmd /c move:*)"
|
"Bash(cmd /c move:*)",
|
||||||
|
"Bash(set:*)"
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
+188
-81
@@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
/**
|
/**
|
||||||
* 设备告警数据接口
|
* 设备告警数据接口
|
||||||
* 提供一次性订阅获取设备 fire_alarm 和 msg_alarm 数据的接口
|
* 提供一次性订阅获取设备 fire_alarm 和 msg_alarm 数据的接口
|
||||||
|
* 使用独立 WebSocket 连接,用完即关,不影响其他业务
|
||||||
*
|
*
|
||||||
* @author lishilin
|
* @author lishilin
|
||||||
* @date 2025-01-19
|
* @date 2025-01-19
|
||||||
@@ -30,35 +31,37 @@ public class DeviceAlarmController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private DeviceAlarmDataService alarmDataService;
|
private DeviceAlarmDataService alarmDataService;
|
||||||
|
|
||||||
|
// ==================== 独立订阅接口 ====================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 一次性订阅获取设备告警数据
|
* 一次性订阅获取 fire_alarm 数据(机库状态数据)
|
||||||
* 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅并关闭 WebSocket
|
* 使用独立的 WebSocket 连接,不影响其他 SSE 订阅
|
||||||
* 如果实时订阅未获取到数据,会尝试从 Redis 缓存获取
|
* 默认超时10秒,响应快速
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
|
* @return fire_alarm 数据
|
||||||
*/
|
*/
|
||||||
@GetMapping("/subscribe/{deviceSn}")
|
@GetMapping("/fire-alarm/{deviceSn}")
|
||||||
@Operation(summary = "一次性订阅获取设备告警数据", description = "订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅")
|
@Operation(summary = "一次性获取机库状态数据", description = "独立 WebSocket 连接获取 fire_alarm,用完即关,不影响其他业务")
|
||||||
public Result<DeviceAlarmResponse> subscribeOnce(
|
public Result<SingleAlarmResponse> getFireAlarm(
|
||||||
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
|
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
|
||||||
log.info("接收到一次性订阅请求: deviceSn={}", deviceSn);
|
log.info("请求获取 fire_alarm: deviceSn={}", deviceSn);
|
||||||
|
|
||||||
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
return Result.failed("设备SN不能为空");
|
return Result.failed("设备SN不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
OneTimeSubscriptionService.DeviceAlarmResult alarmResult = oneTimeSubscriptionService.subscribeOnce(deviceSn);
|
OneTimeSubscriptionService.SingleAlarmResult alarmResult =
|
||||||
|
oneTimeSubscriptionService.subscribeFireAlarmOnce(deviceSn);
|
||||||
|
|
||||||
DeviceAlarmResponse response = new DeviceAlarmResponse();
|
SingleAlarmResponse response = new SingleAlarmResponse();
|
||||||
response.setDeviceSn(alarmResult.getDeviceSn());
|
response.setDeviceSn(alarmResult.getDeviceSn());
|
||||||
|
response.setAlarmType(alarmResult.getAlarmType());
|
||||||
response.setSuccess(alarmResult.isSuccess());
|
response.setSuccess(alarmResult.isSuccess());
|
||||||
response.setMessage(alarmResult.getMessage());
|
response.setMessage(alarmResult.getMessage());
|
||||||
response.setFireAlarmData(alarmResult.getFireAlarmData());
|
response.setData(alarmResult.getData());
|
||||||
response.setMsgAlarmData(alarmResult.getMsgAlarmData());
|
response.setFromCache(alarmResult.isFromCache());
|
||||||
response.setFireAlarmFromCache(alarmResult.isFireAlarmFromCache());
|
|
||||||
response.setMsgAlarmFromCache(alarmResult.isMsgAlarmFromCache());
|
|
||||||
|
|
||||||
if (alarmResult.isSuccess()) {
|
if (alarmResult.isSuccess()) {
|
||||||
return Result.succeed(response, "获取成功");
|
return Result.succeed(response, "获取成功");
|
||||||
@@ -67,45 +70,44 @@ public class DeviceAlarmController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("一次性订阅请求失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
log.error("获取 fire_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
return Result.failed("订阅失败: " + e.getMessage());
|
return Result.failed("获取失败: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 一次性订阅获取设备告警数据(带超时参数)
|
* 一次性订阅获取 fire_alarm 数据(带超时参数)
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @param timeoutSeconds 超时时间(秒),默认30秒
|
* @param timeoutSeconds 超时时间(秒)
|
||||||
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
|
* @return fire_alarm 数据
|
||||||
*/
|
*/
|
||||||
@GetMapping("/subscribe/{deviceSn}/timeout/{timeoutSeconds}")
|
@GetMapping("/fire-alarm/{deviceSn}/timeout/{timeoutSeconds}")
|
||||||
@Operation(summary = "一次性订阅获取设备告警数据(带超时)", description = "订阅 fire_alarm 和 msg_alarm,可自定义超时时间")
|
@Operation(summary = "一次性获取机库状态数据(带超时)", description = "可自定义超时时间")
|
||||||
public Result<DeviceAlarmResponse> subscribeOnceWithTimeout(
|
public Result<SingleAlarmResponse> getFireAlarmWithTimeout(
|
||||||
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn,
|
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn,
|
||||||
@Parameter(description = "超时时间(秒)", required = true) @PathVariable int timeoutSeconds) {
|
@Parameter(description = "超时时间(秒)", required = true) @PathVariable int timeoutSeconds) {
|
||||||
log.info("接收到一次性订阅请求(带超时): deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
|
log.info("请求获取 fire_alarm(带超时): deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
|
||||||
|
|
||||||
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
return Result.failed("设备SN不能为空");
|
return Result.failed("设备SN不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (timeoutSeconds < 1 || timeoutSeconds > 120) {
|
if (timeoutSeconds < 1 || timeoutSeconds > 60) {
|
||||||
return Result.failed("超时时间必须在1-120秒之间");
|
return Result.failed("超时时间必须在1-60秒之间");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
OneTimeSubscriptionService.DeviceAlarmResult alarmResult =
|
OneTimeSubscriptionService.SingleAlarmResult alarmResult =
|
||||||
oneTimeSubscriptionService.subscribeOnce(deviceSn, timeoutSeconds);
|
oneTimeSubscriptionService.subscribeFireAlarmOnce(deviceSn, timeoutSeconds);
|
||||||
|
|
||||||
DeviceAlarmResponse response = new DeviceAlarmResponse();
|
SingleAlarmResponse response = new SingleAlarmResponse();
|
||||||
response.setDeviceSn(alarmResult.getDeviceSn());
|
response.setDeviceSn(alarmResult.getDeviceSn());
|
||||||
|
response.setAlarmType(alarmResult.getAlarmType());
|
||||||
response.setSuccess(alarmResult.isSuccess());
|
response.setSuccess(alarmResult.isSuccess());
|
||||||
response.setMessage(alarmResult.getMessage());
|
response.setMessage(alarmResult.getMessage());
|
||||||
response.setFireAlarmData(alarmResult.getFireAlarmData());
|
response.setData(alarmResult.getData());
|
||||||
response.setMsgAlarmData(alarmResult.getMsgAlarmData());
|
response.setFromCache(alarmResult.isFromCache());
|
||||||
response.setFireAlarmFromCache(alarmResult.isFireAlarmFromCache());
|
|
||||||
response.setMsgAlarmFromCache(alarmResult.isMsgAlarmFromCache());
|
|
||||||
|
|
||||||
if (alarmResult.isSuccess()) {
|
if (alarmResult.isSuccess()) {
|
||||||
return Result.succeed(response, "获取成功");
|
return Result.succeed(response, "获取成功");
|
||||||
@@ -114,44 +116,169 @@ public class DeviceAlarmController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("一次性订阅请求失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
log.error("获取 fire_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
return Result.failed("订阅失败: " + e.getMessage());
|
return Result.failed("获取失败: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从 Redis 缓存获取设备告警数据(不进行实时订阅)
|
* 一次性订阅获取 msg_alarm 数据(无人机遥测数据)
|
||||||
|
* 使用独立的 WebSocket 连接,不影响其他 SSE 订阅
|
||||||
|
* 默认超时10秒
|
||||||
|
*
|
||||||
|
* 注意:msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有数据
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @return 缓存的 fire_alarm 和 msg_alarm 数据
|
* @return msg_alarm 数据
|
||||||
*/
|
*/
|
||||||
@GetMapping("/cache/{deviceSn}")
|
@GetMapping("/msg-alarm/{deviceSn}")
|
||||||
@Operation(summary = "从缓存获取设备告警数据", description = "仅从 Redis 缓存获取,不进行实时订阅")
|
@Operation(summary = "一次性获取无人机遥测数据", description = "独立 WebSocket 连接获取 msg_alarm,用完即关。注意:无人机需开机才有数据")
|
||||||
public Result<DeviceAlarmResponse> getFromCache(
|
public Result<SingleAlarmResponse> getMsgAlarm(
|
||||||
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
|
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
|
||||||
log.info("从缓存获取设备告警数据: deviceSn={}", deviceSn);
|
log.info("请求获取 msg_alarm: deviceSn={}", deviceSn);
|
||||||
|
|
||||||
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
return Result.failed("设备SN不能为空");
|
return Result.failed("设备SN不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
JSONObject fireAlarmData = alarmDataService.getFireAlarmData(deviceSn);
|
OneTimeSubscriptionService.SingleAlarmResult alarmResult =
|
||||||
JSONObject msgAlarmData = alarmDataService.getMsgAlarmData(deviceSn);
|
oneTimeSubscriptionService.subscribeMsgAlarmOnce(deviceSn);
|
||||||
|
|
||||||
DeviceAlarmResponse response = new DeviceAlarmResponse();
|
SingleAlarmResponse response = new SingleAlarmResponse();
|
||||||
|
response.setDeviceSn(alarmResult.getDeviceSn());
|
||||||
|
response.setAlarmType(alarmResult.getAlarmType());
|
||||||
|
response.setSuccess(alarmResult.isSuccess());
|
||||||
|
response.setMessage(alarmResult.getMessage());
|
||||||
|
response.setData(alarmResult.getData());
|
||||||
|
response.setFromCache(alarmResult.isFromCache());
|
||||||
|
|
||||||
|
if (alarmResult.isSuccess()) {
|
||||||
|
return Result.succeed(response, "获取成功");
|
||||||
|
} else {
|
||||||
|
return Result.succeed(response, "未获取到数据(无人机可能未开机)");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取 msg_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
|
return Result.failed("获取失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 一次性订阅获取 msg_alarm 数据(带超时参数)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @param timeoutSeconds 超时时间(秒)
|
||||||
|
* @return msg_alarm 数据
|
||||||
|
*/
|
||||||
|
@GetMapping("/msg-alarm/{deviceSn}/timeout/{timeoutSeconds}")
|
||||||
|
@Operation(summary = "一次性获取无人机遥测数据(带超时)", description = "可自定义超时时间。注意:无人机需开机才有数据")
|
||||||
|
public Result<SingleAlarmResponse> getMsgAlarmWithTimeout(
|
||||||
|
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn,
|
||||||
|
@Parameter(description = "超时时间(秒)", required = true) @PathVariable int timeoutSeconds) {
|
||||||
|
log.info("请求获取 msg_alarm(带超时): deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
|
||||||
|
|
||||||
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
|
return Result.failed("设备SN不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (timeoutSeconds < 1 || timeoutSeconds > 60) {
|
||||||
|
return Result.failed("超时时间必须在1-60秒之间");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
OneTimeSubscriptionService.SingleAlarmResult alarmResult =
|
||||||
|
oneTimeSubscriptionService.subscribeMsgAlarmOnce(deviceSn, timeoutSeconds);
|
||||||
|
|
||||||
|
SingleAlarmResponse response = new SingleAlarmResponse();
|
||||||
|
response.setDeviceSn(alarmResult.getDeviceSn());
|
||||||
|
response.setAlarmType(alarmResult.getAlarmType());
|
||||||
|
response.setSuccess(alarmResult.isSuccess());
|
||||||
|
response.setMessage(alarmResult.getMessage());
|
||||||
|
response.setData(alarmResult.getData());
|
||||||
|
response.setFromCache(alarmResult.isFromCache());
|
||||||
|
|
||||||
|
if (alarmResult.isSuccess()) {
|
||||||
|
return Result.succeed(response, "获取成功");
|
||||||
|
} else {
|
||||||
|
return Result.succeed(response, "未获取到数据(无人机可能未开机)");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取 msg_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
|
return Result.failed("获取失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 缓存相关接口 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 Redis 缓存获取 fire_alarm 数据(不进行实时订阅)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @return 缓存的 fire_alarm 数据
|
||||||
|
*/
|
||||||
|
@GetMapping("/cache/fire-alarm/{deviceSn}")
|
||||||
|
@Operation(summary = "从缓存获取机库状态数据", description = "仅从 Redis 缓存获取,不进行实时订阅")
|
||||||
|
public Result<SingleAlarmResponse> getFireAlarmFromCache(
|
||||||
|
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
|
||||||
|
log.info("从缓存获取 fire_alarm 数据: deviceSn={}", deviceSn);
|
||||||
|
|
||||||
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
|
return Result.failed("设备SN不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSONObject data = alarmDataService.getFireAlarmData(deviceSn);
|
||||||
|
|
||||||
|
SingleAlarmResponse response = new SingleAlarmResponse();
|
||||||
response.setDeviceSn(deviceSn);
|
response.setDeviceSn(deviceSn);
|
||||||
response.setFireAlarmData(fireAlarmData);
|
response.setAlarmType("fire_alarm");
|
||||||
response.setMsgAlarmData(msgAlarmData);
|
response.setData(data);
|
||||||
response.setFireAlarmFromCache(fireAlarmData != null);
|
response.setFromCache(true);
|
||||||
response.setMsgAlarmFromCache(msgAlarmData != null);
|
response.setSuccess(data != null);
|
||||||
response.setSuccess(fireAlarmData != null || msgAlarmData != null);
|
response.setMessage(data != null ? "缓存数据存在" : "缓存中无数据");
|
||||||
response.setMessage(buildCacheResultMessage(fireAlarmData != null, msgAlarmData != null));
|
|
||||||
|
|
||||||
return Result.succeed(response);
|
return Result.succeed(response);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("从缓存获取数据失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
log.error("从缓存获取 fire_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
|
return Result.failed("获取缓存失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 Redis 缓存获取 msg_alarm 数据(不进行实时订阅)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @return 缓存的 msg_alarm 数据
|
||||||
|
*/
|
||||||
|
@GetMapping("/cache/msg-alarm/{deviceSn}")
|
||||||
|
@Operation(summary = "从缓存获取无人机遥测数据", description = "仅从 Redis 缓存获取,不进行实时订阅")
|
||||||
|
public Result<SingleAlarmResponse> getMsgAlarmFromCache(
|
||||||
|
@Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) {
|
||||||
|
log.info("从缓存获取 msg_alarm 数据: deviceSn={}", deviceSn);
|
||||||
|
|
||||||
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
|
return Result.failed("设备SN不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
JSONObject data = alarmDataService.getMsgAlarmData(deviceSn);
|
||||||
|
|
||||||
|
SingleAlarmResponse response = new SingleAlarmResponse();
|
||||||
|
response.setDeviceSn(deviceSn);
|
||||||
|
response.setAlarmType("msg_alarm");
|
||||||
|
response.setData(data);
|
||||||
|
response.setFromCache(true);
|
||||||
|
response.setSuccess(data != null);
|
||||||
|
response.setMessage(data != null ? "缓存数据存在" : "缓存中无数据");
|
||||||
|
|
||||||
|
return Result.succeed(response);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("从缓存获取 msg_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
return Result.failed("获取缓存失败: " + e.getMessage());
|
return Result.failed("获取缓存失败: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,30 +309,20 @@ public class DeviceAlarmController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建缓存结果消息
|
* 单一告警数据响应
|
||||||
*/
|
|
||||||
private String buildCacheResultMessage(boolean hasFireAlarm, boolean hasMsgAlarm) {
|
|
||||||
if (hasFireAlarm && hasMsgAlarm) {
|
|
||||||
return "fire_alarm 和 msg_alarm 缓存数据都存在";
|
|
||||||
} else if (hasFireAlarm) {
|
|
||||||
return "仅 fire_alarm 缓存数据存在";
|
|
||||||
} else if (hasMsgAlarm) {
|
|
||||||
return "仅 msg_alarm 缓存数据存在";
|
|
||||||
} else {
|
|
||||||
return "缓存中无数据";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设备告警数据响应
|
|
||||||
*/
|
*/
|
||||||
@lombok.Data
|
@lombok.Data
|
||||||
public static class DeviceAlarmResponse {
|
public static class SingleAlarmResponse {
|
||||||
/**
|
/**
|
||||||
* 设备SN
|
* 设备SN
|
||||||
*/
|
*/
|
||||||
private String deviceSn;
|
private String deviceSn;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 告警类型(fire_alarm 或 msg_alarm)
|
||||||
|
*/
|
||||||
|
private String alarmType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 是否成功
|
* 是否成功
|
||||||
*/
|
*/
|
||||||
@@ -217,23 +334,13 @@ public class DeviceAlarmController {
|
|||||||
private String message;
|
private String message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* fire_alarm 数据(机库状态数据)
|
* 告警数据
|
||||||
*/
|
*/
|
||||||
private JSONObject fireAlarmData;
|
private JSONObject data;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* msg_alarm 数据(无人机遥测数据)
|
* 数据是否来自缓存
|
||||||
*/
|
*/
|
||||||
private JSONObject msgAlarmData;
|
private boolean fromCache;
|
||||||
|
|
||||||
/**
|
|
||||||
* fire_alarm 数据是否来自缓存
|
|
||||||
*/
|
|
||||||
private boolean fireAlarmFromCache;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* msg_alarm 数据是否来自缓存
|
|
||||||
*/
|
|
||||||
private boolean msgAlarmFromCache;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+167
-216
@@ -1,29 +1,26 @@
|
|||||||
package com.central.device.service;
|
package com.central.device.service;
|
||||||
|
|
||||||
import com.alibaba.fastjson.JSONObject;
|
import com.alibaba.fastjson.JSONObject;
|
||||||
import com.central.device.sse.manager.SseEmitterManager;
|
import com.central.device.websocket.client.IsolatedWebSocketClient;
|
||||||
import com.central.device.websocket.client.JetLinksWebSocketClient;
|
import com.central.device.websocket.config.WebSocketProperties;
|
||||||
import com.central.device.websocket.handler.DeviceMessageHandler;
|
import com.central.device.websocket.manager.TokenManager;
|
||||||
import com.central.device.websocket.model.SubscriptionTopic;
|
import com.central.device.websocket.model.SubscriptionTopic;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 一次性订阅服务
|
* 一次性订阅服务
|
||||||
* 用于一次性获取设备的 fire_alarm 和 msg_alarm 数据
|
* 用于一次性获取设备的 fire_alarm 或 msg_alarm 数据
|
||||||
* 订阅成功后自动取消订阅并关闭 WebSocket 连接,防止资源浪费
|
* 使用独立的 WebSocket 连接,用完即关,不影响其他业务
|
||||||
*
|
*
|
||||||
* 设计原则:
|
* 设计原则:
|
||||||
* 1. 不影响已有的 SSE 订阅(引用计数方式管理)
|
* 1. 每个订阅使用独立的 WebSocket 连接,完全隔离
|
||||||
* 2. msg_alarm 只有无人机开机才有消息,需要容错处理
|
* 2. 用完即关,不占用资源
|
||||||
* 3. 支持只获取到部分数据的情况
|
* 3. 不影响 SSE 订阅和其他业务
|
||||||
*
|
*
|
||||||
* @author lishilin
|
* @author lishilin
|
||||||
* @date 2025-01-19
|
* @date 2025-01-19
|
||||||
@@ -33,270 +30,234 @@ import java.util.concurrent.atomic.AtomicReference;
|
|||||||
public class OneTimeSubscriptionService {
|
public class OneTimeSubscriptionService {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 默认订阅超时时间(秒)
|
* 独立订阅默认超时时间(秒)
|
||||||
*/
|
*/
|
||||||
private static final int DEFAULT_TIMEOUT_SECONDS = 30;
|
private static final int DEFAULT_TIMEOUT_SECONDS = 10;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private JetLinksWebSocketClient webSocketClient;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private DeviceMessageHandler messageHandler;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private DeviceAlarmDataService alarmDataService;
|
private DeviceAlarmDataService alarmDataService;
|
||||||
|
|
||||||
@Autowired(required = false)
|
@Autowired
|
||||||
private SseEmitterManager sseEmitterManager;
|
private WebSocketProperties webSocketProperties;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TokenManager tokenManager;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 一次性订阅获取设备告警数据
|
* 独立订阅获取 fire_alarm 数据(机库状态数据)
|
||||||
* 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅并关闭 WebSocket
|
* 使用独立的 WebSocket 连接,不影响现有 SSE 订阅
|
||||||
|
* 获取数据后立即关闭连接
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
|
* @return 包含 fire_alarm 数据的结果
|
||||||
*/
|
*/
|
||||||
public DeviceAlarmResult subscribeOnce(String deviceSn) {
|
public SingleAlarmResult subscribeFireAlarmOnce(String deviceSn) {
|
||||||
return subscribeOnce(deviceSn, DEFAULT_TIMEOUT_SECONDS);
|
return subscribeFireAlarmOnce(deviceSn, DEFAULT_TIMEOUT_SECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 一次性订阅获取设备告警数据
|
* 独立订阅获取 fire_alarm 数据(机库状态数据)
|
||||||
* 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅
|
* 使用独立的 WebSocket 连接,不影响现有 SSE 订阅
|
||||||
*
|
|
||||||
* 注意:
|
|
||||||
* 1. msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有消息
|
|
||||||
* 2. 不会无限等待,超时后会尝试从 Redis 获取缓存数据
|
|
||||||
* 3. 不会影响已有的 SSE 订阅
|
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @param timeoutSeconds 超时时间(秒)
|
* @param timeoutSeconds 超时时间(秒)
|
||||||
* @return 包含 fire_alarm 和 msg_alarm 数据的结果
|
* @return 包含 fire_alarm 数据的结果
|
||||||
*/
|
*/
|
||||||
public DeviceAlarmResult subscribeOnce(String deviceSn, int timeoutSeconds) {
|
public SingleAlarmResult subscribeFireAlarmOnce(String deviceSn, int timeoutSeconds) {
|
||||||
log.info("开始一次性订阅: deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
|
log.info("独立订阅 fire_alarm 开始: deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
|
||||||
|
|
||||||
DeviceAlarmResult result = new DeviceAlarmResult();
|
SingleAlarmResult result = new SingleAlarmResult();
|
||||||
result.setDeviceSn(deviceSn);
|
result.setDeviceSn(deviceSn);
|
||||||
|
result.setAlarmType("fire_alarm");
|
||||||
|
|
||||||
// 检查 SSE 是否已有此设备的订阅(用于判断是否需要自己管理订阅)
|
// 用于存储接收到的数据
|
||||||
int sseRefCount = getSseRefCount(deviceSn);
|
AtomicReference<JSONObject> dataRef = new AtomicReference<>();
|
||||||
boolean hasSseSubscription = sseRefCount > 0;
|
CountDownLatch dataLatch = new CountDownLatch(1);
|
||||||
// 检查设备是否已在消息处理器中注册
|
|
||||||
boolean deviceAlreadyRegistered = messageHandler.getDeviceData(deviceSn) != null;
|
|
||||||
|
|
||||||
log.info("设备 {} 状态检查: SSE引用计数={}, 已注册={}", deviceSn, sseRefCount, deviceAlreadyRegistered);
|
// 创建独立的 WebSocket 客户端
|
||||||
|
IsolatedWebSocketClient isolatedClient = new IsolatedWebSocketClient(
|
||||||
// 记录本次订阅新增的主题(用于清理时只取消自己订阅的)
|
webSocketProperties, tokenManager, deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM);
|
||||||
Set<SubscriptionTopic> mySubscribedTopics = new HashSet<>();
|
|
||||||
|
|
||||||
// 用于存储回调接收到的数据
|
|
||||||
AtomicReference<JSONObject> fireAlarmData = new AtomicReference<>();
|
|
||||||
AtomicReference<JSONObject> msgAlarmData = new AtomicReference<>();
|
|
||||||
AtomicBoolean fireAlarmReceived = new AtomicBoolean(false);
|
|
||||||
AtomicBoolean msgAlarmReceived = new AtomicBoolean(false);
|
|
||||||
|
|
||||||
// 用于等待数据的 CountDownLatch(只等待1个即可返回,不强制等待全部)
|
|
||||||
CountDownLatch fireAlarmLatch = new CountDownLatch(1);
|
|
||||||
CountDownLatch msgAlarmLatch = new CountDownLatch(1);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 如果设备未注册,先添加设备到消息处理器(确保可以接收消息)
|
// 连接并订阅
|
||||||
if (!deviceAlreadyRegistered) {
|
boolean connected = isolatedClient.connectAndSubscribe(data -> {
|
||||||
messageHandler.addDevice(deviceSn, null, null);
|
log.info("独立订阅收到 fire_alarm 数据: deviceSn={}", deviceSn);
|
||||||
}
|
dataRef.set(data);
|
||||||
|
dataLatch.countDown();
|
||||||
// 注册 fire_alarm 回调
|
|
||||||
messageHandler.registerFireAlarmCallback(deviceSn, (sn, data) -> {
|
|
||||||
if (!fireAlarmReceived.getAndSet(true)) {
|
|
||||||
log.info("一次性订阅收到 fire_alarm 数据: deviceSn={}", sn);
|
|
||||||
fireAlarmData.set(data);
|
|
||||||
fireAlarmLatch.countDown();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 注册 msg_alarm 回调
|
if (!connected) {
|
||||||
messageHandler.registerMsgAlarmCallback(deviceSn, (sn, data) -> {
|
log.warn("独立 WebSocket 连接失败,尝试从缓存获取: deviceSn={}", deviceSn);
|
||||||
if (!msgAlarmReceived.getAndSet(true)) {
|
return tryGetFromCache(result, deviceSn, true);
|
||||||
log.info("一次性订阅收到 msg_alarm 数据: deviceSn={}", sn);
|
|
||||||
msgAlarmData.set(data);
|
|
||||||
msgAlarmLatch.countDown();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 订阅主题(始终订阅,WebSocket 内部会处理重复订阅)
|
|
||||||
// 即使 SSE 已订阅,也再次订阅,因为 WebSocket 的 subscribedTopics 会去重
|
|
||||||
webSocketClient.subscribeDevice(deviceSn,
|
|
||||||
SubscriptionTopic.EVENT_FIRE_ALARM,
|
|
||||||
SubscriptionTopic.EVENT_MSG_ALARM);
|
|
||||||
mySubscribedTopics.add(SubscriptionTopic.EVENT_FIRE_ALARM);
|
|
||||||
mySubscribedTopics.add(SubscriptionTopic.EVENT_MSG_ALARM);
|
|
||||||
|
|
||||||
// 等待 fire_alarm 数据(fire_alarm 是机库数据,通常会有)
|
|
||||||
boolean fireAlarmCompleted = fireAlarmLatch.await(timeoutSeconds, TimeUnit.SECONDS);
|
|
||||||
|
|
||||||
// 等待 msg_alarm 数据(msg_alarm 只有无人机开机才有,给较短时间)
|
|
||||||
// 如果 fire_alarm 已收到,只再等 5 秒;否则不额外等待
|
|
||||||
if (fireAlarmCompleted && !msgAlarmReceived.get()) {
|
|
||||||
log.info("fire_alarm 已收到,额外等待 5 秒获取 msg_alarm: deviceSn={}", deviceSn);
|
|
||||||
msgAlarmLatch.await(5, TimeUnit.SECONDS);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info("一次性订阅等待结束: deviceSn={}, fireAlarm={}, msgAlarm={}",
|
// 等待数据
|
||||||
deviceSn, fireAlarmReceived.get(), msgAlarmReceived.get());
|
boolean received = dataLatch.await(timeoutSeconds, TimeUnit.SECONDS);
|
||||||
|
|
||||||
// 设置结果
|
if (received && dataRef.get() != null) {
|
||||||
result.setFireAlarmData(fireAlarmData.get());
|
result.setData(dataRef.get());
|
||||||
result.setMsgAlarmData(msgAlarmData.get());
|
result.setSuccess(true);
|
||||||
|
result.setFromCache(false);
|
||||||
// 如果没有订阅到数据,尝试从 Redis 获取缓存数据
|
result.setMessage("fire_alarm: 实时订阅获取成功");
|
||||||
if (result.getFireAlarmData() == null) {
|
log.info("独立订阅 fire_alarm 成功: deviceSn={}", deviceSn);
|
||||||
JSONObject cachedFireAlarm = alarmDataService.getFireAlarmData(deviceSn);
|
} else {
|
||||||
if (cachedFireAlarm != null) {
|
log.info("独立订阅 fire_alarm 超时,尝试从缓存获取: deviceSn={}", deviceSn);
|
||||||
log.info("从 Redis 获取 fire_alarm 缓存数据: deviceSn={}", deviceSn);
|
return tryGetFromCache(result, deviceSn, true);
|
||||||
result.setFireAlarmData(cachedFireAlarm);
|
|
||||||
result.setFireAlarmFromCache(true);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.getMsgAlarmData() == null) {
|
|
||||||
JSONObject cachedMsgAlarm = alarmDataService.getMsgAlarmData(deviceSn);
|
|
||||||
if (cachedMsgAlarm != null) {
|
|
||||||
log.info("从 Redis 获取 msg_alarm 缓存数据: deviceSn={}", deviceSn);
|
|
||||||
result.setMsgAlarmData(cachedMsgAlarm);
|
|
||||||
result.setMsgAlarmFromCache(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
result.setSuccess(result.getFireAlarmData() != null || result.getMsgAlarmData() != null);
|
|
||||||
result.setMessage(buildResultMessage(result));
|
|
||||||
|
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
log.error("一次性订阅被中断: deviceSn={}", deviceSn);
|
log.error("独立订阅 fire_alarm 被中断: deviceSn={}", deviceSn);
|
||||||
result.setSuccess(false);
|
result.setSuccess(false);
|
||||||
result.setMessage("订阅被中断");
|
result.setMessage("订阅被中断");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("一次性订阅失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
log.error("独立订阅 fire_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
result.setSuccess(false);
|
return tryGetFromCache(result, deviceSn, true);
|
||||||
result.setMessage("订阅失败: " + e.getMessage());
|
|
||||||
} finally {
|
} finally {
|
||||||
// 清理:移除回调、取消订阅(如果 SSE 没有订阅的话)
|
// 关闭独立连接
|
||||||
cleanupSubscription(deviceSn, hasSseSubscription, deviceAlreadyRegistered, mySubscribedTopics);
|
isolatedClient.close();
|
||||||
|
log.info("独立 WebSocket 连接已关闭: deviceSn={}, clientId={}",
|
||||||
|
deviceSn, isolatedClient.getClientId());
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取 SSE 对设备的引用计数
|
* 独立订阅获取 msg_alarm 数据(无人机遥测数据)
|
||||||
|
* 使用独立的 WebSocket 连接,不影响现有 SSE 订阅
|
||||||
|
* 获取数据后立即关闭连接
|
||||||
|
*
|
||||||
|
* 注意:msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有数据
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @return 引用计数,0 表示无订阅
|
* @return 包含 msg_alarm 数据的结果
|
||||||
*/
|
*/
|
||||||
private int getSseRefCount(String deviceSn) {
|
public SingleAlarmResult subscribeMsgAlarmOnce(String deviceSn) {
|
||||||
if (sseEmitterManager == null) {
|
return subscribeMsgAlarmOnce(deviceSn, DEFAULT_TIMEOUT_SECONDS);
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return sseEmitterManager.getDeviceRefCount(deviceSn);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("获取 SSE 引用计数失败: deviceSn={}, error={}", deviceSn, e.getMessage());
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清理订阅资源
|
* 独立订阅获取 msg_alarm 数据(无人机遥测数据)
|
||||||
* 设计原则:
|
* 使用独立的 WebSocket 连接,不影响现有 SSE 订阅
|
||||||
* 1. 不影响 SSE 已有的订阅(fire_alarm, online, offline)
|
|
||||||
* 2. msg_alarm 是一次性订阅额外订阅的,需要自己负责取消
|
|
||||||
* 3. 【重要】一次性订阅和SSE订阅完全独立,一次性订阅不应该影响 deviceDataMap
|
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* 注意:msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有数据
|
||||||
* @param hasSseSubscription SSE 是否已有订阅(订阅开始时的状态)
|
*
|
||||||
* @param deviceAlreadyRegistered 设备是否在一次性订阅前就已注册
|
* @param deviceSn 设备SN
|
||||||
* @param mySubscribedTopics 本次一次性订阅新增的主题
|
* @param timeoutSeconds 超时时间(秒)
|
||||||
|
* @return 包含 msg_alarm 数据的结果
|
||||||
*/
|
*/
|
||||||
private void cleanupSubscription(String deviceSn, boolean hasSseSubscription,
|
public SingleAlarmResult subscribeMsgAlarmOnce(String deviceSn, int timeoutSeconds) {
|
||||||
boolean deviceAlreadyRegistered, Set<SubscriptionTopic> mySubscribedTopics) {
|
log.info("独立订阅 msg_alarm 开始: deviceSn={}, timeout={}s", deviceSn, timeoutSeconds);
|
||||||
|
|
||||||
|
SingleAlarmResult result = new SingleAlarmResult();
|
||||||
|
result.setDeviceSn(deviceSn);
|
||||||
|
result.setAlarmType("msg_alarm");
|
||||||
|
|
||||||
|
// 用于存储接收到的数据
|
||||||
|
AtomicReference<JSONObject> dataRef = new AtomicReference<>();
|
||||||
|
CountDownLatch dataLatch = new CountDownLatch(1);
|
||||||
|
|
||||||
|
// 创建独立的 WebSocket 客户端
|
||||||
|
IsolatedWebSocketClient isolatedClient = new IsolatedWebSocketClient(
|
||||||
|
webSocketProperties, tokenManager, deviceSn, SubscriptionTopic.EVENT_MSG_ALARM);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 【重要】重新检查当前 SSE 引用计数,因为在订阅过程中可能有新的 SSE 连接建立
|
// 连接并订阅
|
||||||
int currentSseRefCount = getSseRefCount(deviceSn);
|
boolean connected = isolatedClient.connectAndSubscribe(data -> {
|
||||||
boolean currentHasSseSubscription = currentSseRefCount > 0;
|
log.info("独立订阅收到 msg_alarm 数据: deviceSn={}", deviceSn);
|
||||||
|
dataRef.set(data);
|
||||||
|
dataLatch.countDown();
|
||||||
|
});
|
||||||
|
|
||||||
log.info("清理一次性订阅资源: deviceSn={}, 订阅开始时SSE状态={}, 当前SSE引用计数={}, deviceAlreadyRegistered={}",
|
if (!connected) {
|
||||||
deviceSn, hasSseSubscription, currentSseRefCount, deviceAlreadyRegistered);
|
log.warn("独立 WebSocket 连接失败,尝试从缓存获取: deviceSn={}", deviceSn);
|
||||||
|
return tryGetFromCache(result, deviceSn, false);
|
||||||
// 1. 移除回调(回调是一次性订阅独有的,SSE 不使用)
|
|
||||||
messageHandler.removeFireAlarmCallback(deviceSn);
|
|
||||||
messageHandler.removeMsgAlarmCallback(deviceSn);
|
|
||||||
|
|
||||||
// 2. 取消订阅(使用当前最新的 SSE 状态来判断)
|
|
||||||
if (currentHasSseSubscription) {
|
|
||||||
// SSE 当前有订阅,只取消 msg_alarm(这是一次性订阅额外订阅的)
|
|
||||||
// SSE 目前只订阅 online, offline, fire_alarm,不订阅 msg_alarm
|
|
||||||
// 所以 msg_alarm 需要一次性订阅自己负责取消
|
|
||||||
log.info("SSE 当前有订阅(引用计数={}),只取消 msg_alarm: deviceSn={}", currentSseRefCount, deviceSn);
|
|
||||||
webSocketClient.unsubscribeDevice(deviceSn, SubscriptionTopic.EVENT_MSG_ALARM);
|
|
||||||
// 不移除设备,因为 SSE 还在使用
|
|
||||||
} else {
|
|
||||||
// SSE 当前无订阅,可以安全取消本次订阅的所有主题
|
|
||||||
if (!mySubscribedTopics.isEmpty()) {
|
|
||||||
log.info("SSE 当前无订阅,取消本次订阅的主题: deviceSn={}, topics={}", deviceSn, mySubscribedTopics);
|
|
||||||
webSocketClient.unsubscribeDevice(deviceSn,
|
|
||||||
mySubscribedTopics.toArray(new SubscriptionTopic[0]));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 【修复】无论设备之前是否注册,只要当前 SSE 无订阅,就应该移除设备
|
|
||||||
// 因为一次性订阅和 SSE 订阅是独立的,一次性订阅结束后应该清理自己添加的资源
|
|
||||||
// 原来的逻辑 `!deviceAlreadyRegistered` 会导致:
|
|
||||||
// - 如果一次性订阅A设备时,A设备已在deviceDataMap中(例如之前SSE订阅过但已断开)
|
|
||||||
// - 一次性订阅结束后,A设备不会被移除
|
|
||||||
// - 后续收到A设备的消息时,会打印"收到未订阅设备的状态事件"警告
|
|
||||||
messageHandler.removeDevice(deviceSn);
|
|
||||||
log.info("已从 deviceDataMap 移除设备: deviceSn={}", deviceSn);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 等待数据
|
||||||
|
boolean received = dataLatch.await(timeoutSeconds, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
if (received && dataRef.get() != null) {
|
||||||
|
result.setData(dataRef.get());
|
||||||
|
result.setSuccess(true);
|
||||||
|
result.setFromCache(false);
|
||||||
|
result.setMessage("msg_alarm: 实时订阅获取成功");
|
||||||
|
log.info("独立订阅 msg_alarm 成功: deviceSn={}", deviceSn);
|
||||||
|
} else {
|
||||||
|
log.info("独立订阅 msg_alarm 超时(可能无人机未开机),尝试从缓存获取: deviceSn={}", deviceSn);
|
||||||
|
return tryGetFromCache(result, deviceSn, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
log.error("独立订阅 msg_alarm 被中断: deviceSn={}", deviceSn);
|
||||||
|
result.setSuccess(false);
|
||||||
|
result.setMessage("订阅被中断");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("清理订阅资源失败: deviceSn={}, error={}", deviceSn, e.getMessage());
|
log.error("独立订阅 msg_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
|
return tryGetFromCache(result, deviceSn, false);
|
||||||
|
} finally {
|
||||||
|
// 关闭独立连接
|
||||||
|
isolatedClient.close();
|
||||||
|
log.info("独立 WebSocket 连接已关闭: deviceSn={}, clientId={}",
|
||||||
|
deviceSn, isolatedClient.getClientId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建结果消息
|
* 尝试从缓存获取数据
|
||||||
*
|
*
|
||||||
* @param result 结果对象
|
* @param result 结果对象
|
||||||
* @return 消息描述
|
* @param deviceSn 设备SN
|
||||||
|
* @param isFireAlarm 是否是 fire_alarm(否则是 msg_alarm)
|
||||||
|
* @return 更新后的结果
|
||||||
*/
|
*/
|
||||||
private String buildResultMessage(DeviceAlarmResult result) {
|
private SingleAlarmResult tryGetFromCache(SingleAlarmResult result, String deviceSn, boolean isFireAlarm) {
|
||||||
StringBuilder sb = new StringBuilder();
|
try {
|
||||||
if (result.getFireAlarmData() != null) {
|
JSONObject cachedData = isFireAlarm
|
||||||
sb.append("fire_alarm: ").append(result.isFireAlarmFromCache() ? "来自缓存" : "实时订阅");
|
? alarmDataService.getFireAlarmData(deviceSn)
|
||||||
} else {
|
: alarmDataService.getMsgAlarmData(deviceSn);
|
||||||
sb.append("fire_alarm: 未获取到");
|
|
||||||
|
if (cachedData != null) {
|
||||||
|
result.setData(cachedData);
|
||||||
|
result.setSuccess(true);
|
||||||
|
result.setFromCache(true);
|
||||||
|
result.setMessage(result.getAlarmType() + ": 来自缓存");
|
||||||
|
log.info("从缓存获取 {} 数据成功: deviceSn={}", result.getAlarmType(), deviceSn);
|
||||||
|
} else {
|
||||||
|
result.setSuccess(false);
|
||||||
|
result.setFromCache(false);
|
||||||
|
result.setMessage(result.getAlarmType() + ": 未获取到数据(实时订阅超时且无缓存)");
|
||||||
|
log.warn("从缓存获取 {} 数据失败(无缓存): deviceSn={}", result.getAlarmType(), deviceSn);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("从缓存获取数据失败: deviceSn={}, error={}", deviceSn, e.getMessage());
|
||||||
|
result.setSuccess(false);
|
||||||
|
result.setMessage(result.getAlarmType() + ": 获取失败 - " + e.getMessage());
|
||||||
}
|
}
|
||||||
sb.append(", ");
|
return result;
|
||||||
if (result.getMsgAlarmData() != null) {
|
|
||||||
sb.append("msg_alarm: ").append(result.isMsgAlarmFromCache() ? "来自缓存" : "实时订阅");
|
|
||||||
} else {
|
|
||||||
sb.append("msg_alarm: 未获取到");
|
|
||||||
}
|
|
||||||
return sb.toString();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设备告警数据结果
|
* 单一告警数据结果
|
||||||
*/
|
*/
|
||||||
@lombok.Data
|
@lombok.Data
|
||||||
public static class DeviceAlarmResult {
|
public static class SingleAlarmResult {
|
||||||
/**
|
/**
|
||||||
* 设备SN
|
* 设备SN
|
||||||
*/
|
*/
|
||||||
private String deviceSn;
|
private String deviceSn;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 是否成功(至少获取到一种数据)
|
* 告警类型(fire_alarm 或 msg_alarm)
|
||||||
|
*/
|
||||||
|
private String alarmType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否成功
|
||||||
*/
|
*/
|
||||||
private boolean success;
|
private boolean success;
|
||||||
|
|
||||||
@@ -306,23 +267,13 @@ public class OneTimeSubscriptionService {
|
|||||||
private String message;
|
private String message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* fire_alarm 数据
|
* 告警数据
|
||||||
*/
|
*/
|
||||||
private JSONObject fireAlarmData;
|
private JSONObject data;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* msg_alarm 数据
|
* 数据是否来自缓存
|
||||||
*/
|
*/
|
||||||
private JSONObject msgAlarmData;
|
private boolean fromCache;
|
||||||
|
|
||||||
/**
|
|
||||||
* fire_alarm 数据是否来自缓存
|
|
||||||
*/
|
|
||||||
private boolean fireAlarmFromCache;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* msg_alarm 数据是否来自缓存
|
|
||||||
*/
|
|
||||||
private boolean msgAlarmFromCache;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+329
@@ -0,0 +1,329 @@
|
|||||||
|
package com.central.device.websocket.client;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.central.device.websocket.config.WebSocketProperties;
|
||||||
|
import com.central.device.websocket.manager.TokenManager;
|
||||||
|
import com.central.device.websocket.model.SubscriptionMessage;
|
||||||
|
import com.central.device.websocket.model.SubscriptionTopic;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.socket.CloseStatus;
|
||||||
|
import org.springframework.web.socket.TextMessage;
|
||||||
|
import org.springframework.web.socket.WebSocketSession;
|
||||||
|
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
|
||||||
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 独立WebSocket客户端
|
||||||
|
* 用于一次性订阅场景,每次创建新连接,用完即关闭
|
||||||
|
* 完全独立于全局JetLinksWebSocketClient,不影响SSE订阅
|
||||||
|
*
|
||||||
|
* 使用场景:
|
||||||
|
* - 一次性获取fire_alarm数据(机库状态)
|
||||||
|
* - 一次性获取msg_alarm数据(无人机遥测)
|
||||||
|
*
|
||||||
|
* @author lishilin
|
||||||
|
* @date 2025-01-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public class IsolatedWebSocketClient extends TextWebSocketHandler {
|
||||||
|
|
||||||
|
private final WebSocketProperties properties;
|
||||||
|
private final TokenManager tokenManager;
|
||||||
|
private final StandardWebSocketClient webSocketClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebSocket会话
|
||||||
|
*/
|
||||||
|
private volatile WebSocketSession session;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接状态
|
||||||
|
*/
|
||||||
|
private volatile boolean isConnected = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目标设备SN
|
||||||
|
*/
|
||||||
|
private final String deviceSn;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目标主题类型
|
||||||
|
*/
|
||||||
|
private final SubscriptionTopic targetTopic;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据接收回调
|
||||||
|
*/
|
||||||
|
private Consumer<JSONObject> dataCallback;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接完成回调
|
||||||
|
*/
|
||||||
|
private CompletableFuture<Boolean> connectFuture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 客户端唯一标识(用于日志区分)
|
||||||
|
*/
|
||||||
|
private final String clientId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订阅消息的唯一ID(订阅和取消订阅使用相同的ID)
|
||||||
|
*/
|
||||||
|
private final String subscriptionId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造函数
|
||||||
|
*
|
||||||
|
* @param properties WebSocket配置
|
||||||
|
* @param tokenManager Token管理器
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @param targetTopic 目标订阅主题
|
||||||
|
*/
|
||||||
|
public IsolatedWebSocketClient(WebSocketProperties properties,
|
||||||
|
TokenManager tokenManager,
|
||||||
|
String deviceSn,
|
||||||
|
SubscriptionTopic targetTopic) {
|
||||||
|
this.properties = properties;
|
||||||
|
this.tokenManager = tokenManager;
|
||||||
|
this.deviceSn = deviceSn;
|
||||||
|
this.targetTopic = targetTopic;
|
||||||
|
this.webSocketClient = new StandardWebSocketClient();
|
||||||
|
this.clientId = UUID.randomUUID().toString().substring(0, 8);
|
||||||
|
// 生成唯一的订阅ID,订阅和取消订阅都使用这个ID
|
||||||
|
this.subscriptionId = "isolated-" + clientId + "-" + UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
log.info("[IsolatedWS-{}] 创建独立WebSocket客户端: deviceSn={}, topic={}, subscriptionId={}",
|
||||||
|
clientId, deviceSn, targetTopic, subscriptionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接并订阅
|
||||||
|
*
|
||||||
|
* @param dataCallback 数据接收回调
|
||||||
|
* @return 连接是否成功
|
||||||
|
*/
|
||||||
|
public boolean connectAndSubscribe(Consumer<JSONObject> dataCallback) {
|
||||||
|
this.dataCallback = dataCallback;
|
||||||
|
this.connectFuture = new CompletableFuture<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
String token = tokenManager.getValidToken();
|
||||||
|
String url = properties.getConnection().getBaseUrl() + "/" + token;
|
||||||
|
|
||||||
|
log.info("[IsolatedWS-{}] 连接WebSocket: deviceSn={}, topic={}",
|
||||||
|
clientId, deviceSn, targetTopic);
|
||||||
|
|
||||||
|
session = webSocketClient.execute(this, url).get(10, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
// 等待连接建立并订阅完成
|
||||||
|
return connectFuture.get(5, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[IsolatedWS-{}] 连接失败: deviceSn={}, error={}",
|
||||||
|
clientId, deviceSn, e.getMessage());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
||||||
|
log.info("[IsolatedWS-{}] 连接成功: deviceSn={}", clientId, deviceSn);
|
||||||
|
|
||||||
|
this.session = session;
|
||||||
|
this.isConnected = true;
|
||||||
|
|
||||||
|
// 立即发送订阅消息
|
||||||
|
subscribeTopic();
|
||||||
|
|
||||||
|
// 通知连接成功
|
||||||
|
if (connectFuture != null) {
|
||||||
|
connectFuture.complete(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
||||||
|
try {
|
||||||
|
String payload = message.getPayload();
|
||||||
|
JSONObject json = JSON.parseObject(payload);
|
||||||
|
|
||||||
|
String type = json.getString("type");
|
||||||
|
String topic = json.getString("topic");
|
||||||
|
|
||||||
|
// 处理心跳响应(忽略)
|
||||||
|
if ("pong".equals(type)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理认证错误
|
||||||
|
if ("authError".equals(type)) {
|
||||||
|
log.error("[IsolatedWS-{}] 认证失败: {}", clientId, json.getString("message"));
|
||||||
|
close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否是目标主题的消息
|
||||||
|
if (topic != null && isTargetTopic(topic)) {
|
||||||
|
log.info("[IsolatedWS-{}] 收到目标数据: deviceSn={}, topic={}",
|
||||||
|
clientId, deviceSn, targetTopic);
|
||||||
|
|
||||||
|
// 提取payload数据
|
||||||
|
JSONObject payloadData = json.getJSONObject("payload");
|
||||||
|
if (payloadData != null && dataCallback != null) {
|
||||||
|
dataCallback.accept(payloadData);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[IsolatedWS-{}] 处理消息失败: error={}", clientId, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否是目标主题的消息
|
||||||
|
*/
|
||||||
|
private boolean isTargetTopic(String topic) {
|
||||||
|
if (topic == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查设备SN和主题类型
|
||||||
|
boolean containsDeviceSn = topic.contains("/" + deviceSn + "/");
|
||||||
|
|
||||||
|
switch (targetTopic) {
|
||||||
|
case EVENT_FIRE_ALARM:
|
||||||
|
return containsDeviceSn && topic.contains("/message/event/fire_alarm");
|
||||||
|
case EVENT_MSG_ALARM:
|
||||||
|
return containsDeviceSn && topic.contains("/message/event/msg_alarm");
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
|
||||||
|
log.info("[IsolatedWS-{}] 连接关闭: code={}, reason={}",
|
||||||
|
clientId, status.getCode(), status.getReason());
|
||||||
|
|
||||||
|
this.isConnected = false;
|
||||||
|
this.session = null;
|
||||||
|
|
||||||
|
// 如果连接还在等待中,通知失败
|
||||||
|
if (connectFuture != null && !connectFuture.isDone()) {
|
||||||
|
connectFuture.complete(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
|
||||||
|
log.error("[IsolatedWS-{}] 连接异常: {}", clientId, exception.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订阅目标主题
|
||||||
|
*/
|
||||||
|
private void subscribeTopic() {
|
||||||
|
String topic = targetTopic.getTopic(deviceSn);
|
||||||
|
|
||||||
|
SubscriptionMessage message = SubscriptionMessage.builder()
|
||||||
|
.type("sub")
|
||||||
|
.topic(topic)
|
||||||
|
.parameter(new JSONObject())
|
||||||
|
.id(subscriptionId) // 使用固定的订阅ID
|
||||||
|
.build();
|
||||||
|
|
||||||
|
send(JSON.toJSONString(message));
|
||||||
|
|
||||||
|
log.info("[IsolatedWS-{}] 发送订阅消息: topic={}, id={}", clientId, topic, subscriptionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消订阅
|
||||||
|
* 使用与订阅时相同的ID,确保只取消自己的订阅
|
||||||
|
*/
|
||||||
|
private void unsubscribeTopic() {
|
||||||
|
if (!isConnected || session == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String topic = targetTopic.getTopic(deviceSn);
|
||||||
|
|
||||||
|
SubscriptionMessage message = SubscriptionMessage.builder()
|
||||||
|
.type("unsub")
|
||||||
|
.topic(topic)
|
||||||
|
.parameter(new JSONObject())
|
||||||
|
.id(subscriptionId) // 使用相同的订阅ID
|
||||||
|
.build();
|
||||||
|
|
||||||
|
send(JSON.toJSONString(message));
|
||||||
|
|
||||||
|
log.info("[IsolatedWS-{}] 发送取消订阅消息: topic={}, id={}", clientId, topic, subscriptionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送消息
|
||||||
|
*/
|
||||||
|
private void send(String message) {
|
||||||
|
if (session != null && session.isOpen()) {
|
||||||
|
try {
|
||||||
|
session.sendMessage(new TextMessage(message));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[IsolatedWS-{}] 发送消息失败: {}", clientId, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭连接
|
||||||
|
* 先取消订阅(使用相同的订阅ID),再关闭连接
|
||||||
|
* 这样更规范,确保只取消自己的订阅,不会影响其他连接
|
||||||
|
*/
|
||||||
|
public void close() {
|
||||||
|
log.info("[IsolatedWS-{}] 关闭独立WebSocket连接: deviceSn={}", clientId, deviceSn);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 先取消订阅(使用相同的subscriptionId)
|
||||||
|
unsubscribeTopic();
|
||||||
|
|
||||||
|
// 2. 等待一小段时间确保取消订阅消息发送
|
||||||
|
Thread.sleep(100);
|
||||||
|
|
||||||
|
// 3. 关闭连接
|
||||||
|
if (session != null && session.isOpen()) {
|
||||||
|
session.close();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[IsolatedWS-{}] 关闭连接失败: {}", clientId, e.getMessage());
|
||||||
|
} finally {
|
||||||
|
this.isConnected = false;
|
||||||
|
this.session = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否已连接
|
||||||
|
*/
|
||||||
|
public boolean isConnected() {
|
||||||
|
return isConnected && session != null && session.isOpen();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取客户端ID
|
||||||
|
*/
|
||||||
|
public String getClientId() {
|
||||||
|
return clientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取订阅ID
|
||||||
|
*/
|
||||||
|
public String getSubscriptionId() {
|
||||||
|
return subscriptionId;
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
-27
@@ -55,6 +55,12 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
*/
|
*/
|
||||||
private final Set<String> subscribedTopics = new HashSet<>();
|
private final Set<String> subscribedTopics = new HashSet<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主题对应的订阅ID:topic -> subscriptionId
|
||||||
|
* 订阅和取消订阅使用相同的ID,确保只取消自己的订阅
|
||||||
|
*/
|
||||||
|
private final ConcurrentHashMap<String, String> topicSubscriptionIds = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设备订阅计数:deviceSn -> 订阅次数
|
* 设备订阅计数:deviceSn -> 订阅次数
|
||||||
* 用于管理同一设备多个主题的订阅,避免过早断开连接
|
* 用于管理同一设备多个主题的订阅,避免过早断开连接
|
||||||
@@ -511,11 +517,15 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 生成唯一的订阅ID,并保存到 Map 中
|
||||||
|
String subscriptionId = "sub-" + deviceSn + "-" + topicEnum.name() + "-" + UUID.randomUUID().toString().substring(0, 8);
|
||||||
|
topicSubscriptionIds.put(topic, subscriptionId);
|
||||||
|
|
||||||
SubscriptionMessage message = SubscriptionMessage.builder()
|
SubscriptionMessage message = SubscriptionMessage.builder()
|
||||||
.type("sub")
|
.type("sub")
|
||||||
.topic(topic)
|
.topic(topic)
|
||||||
.parameter(new JSONObject())
|
.parameter(new JSONObject())
|
||||||
.id("request-id-" + UUID.randomUUID().toString())
|
.id(subscriptionId)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
send(JSON.toJSONString(message));
|
send(JSON.toJSONString(message));
|
||||||
@@ -524,8 +534,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
// 更新设备订阅计数(只有实际发送订阅时才增加)
|
// 更新设备订阅计数(只有实际发送订阅时才增加)
|
||||||
deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet();
|
deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet();
|
||||||
|
|
||||||
log.info("发送订阅消息: topic={}, 设备{}订阅计数: {}",
|
log.info("发送订阅消息: topic={}, id={}, 设备{}订阅计数: {}",
|
||||||
topic, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
|
topic, subscriptionId, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -540,11 +550,18 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 获取订阅时使用的 ID(如果没有则生成一个,但这种情况不应该发生)
|
||||||
|
String subscriptionId = topicSubscriptionIds.remove(topic);
|
||||||
|
if (subscriptionId == null) {
|
||||||
|
log.warn("未找到主题对应的订阅ID,使用新ID取消订阅: topic={}", topic);
|
||||||
|
subscriptionId = "unsub-" + UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
|
||||||
SubscriptionMessage message = SubscriptionMessage.builder()
|
SubscriptionMessage message = SubscriptionMessage.builder()
|
||||||
.type("unsub")
|
.type("unsub")
|
||||||
.topic(topic)
|
.topic(topic)
|
||||||
.parameter(new JSONObject())
|
.parameter(new JSONObject())
|
||||||
.id("request-id-" + UUID.randomUUID().toString())
|
.id(subscriptionId) // 使用相同的订阅ID
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
send(JSON.toJSONString(message));
|
send(JSON.toJSONString(message));
|
||||||
@@ -566,8 +583,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info("取消订阅主题: topic={}, 剩余主题数: {}, 剩余主题: {}",
|
log.info("取消订阅主题: topic={}, id={}, 剩余主题数: {}",
|
||||||
topic, subscribedTopics.size(), subscribedTopics);
|
topic, subscriptionId, subscribedTopics.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -586,6 +603,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
subscribedTopics.clear();
|
subscribedTopics.clear();
|
||||||
// 清空设备订阅计数,重新订阅时会重新计算
|
// 清空设备订阅计数,重新订阅时会重新计算
|
||||||
deviceSubscriptionCounts.clear();
|
deviceSubscriptionCounts.clear();
|
||||||
|
// 清空订阅ID映射,重新订阅时会生成新的ID
|
||||||
|
topicSubscriptionIds.clear();
|
||||||
|
|
||||||
// 按设备分组重新订阅
|
// 按设备分组重新订阅
|
||||||
Set<String> deviceSns = new HashSet<>();
|
Set<String> deviceSns = new HashSet<>();
|
||||||
@@ -788,13 +807,6 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
return isConnected && session != null && session.isOpen();
|
return isConnected && session != null && session.isOpen();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取当前订阅数
|
|
||||||
*/
|
|
||||||
public int getSubscriptionCount() {
|
|
||||||
return subscribedTopics.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取设备订阅计数
|
* 获取设备订阅计数
|
||||||
*/
|
*/
|
||||||
@@ -810,20 +822,6 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
return new HashSet<>(deviceSubscriptionCounts.keySet());
|
return new HashSet<>(deviceSubscriptionCounts.keySet());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 打印当前订阅状态(用于调试)
|
|
||||||
*/
|
|
||||||
public void printSubscriptionStatus() {
|
|
||||||
log.info("=== WebSocket订阅状态 ===");
|
|
||||||
log.info("连接状态: {}", isConnected() ? "已连接" : "未连接");
|
|
||||||
log.info("主题订阅数: {}", subscribedTopics.size());
|
|
||||||
log.info("设备订阅数: {}", deviceSubscriptionCounts.size());
|
|
||||||
log.info("活跃设备: {}", deviceSubscriptionCounts.keySet());
|
|
||||||
deviceSubscriptionCounts.forEach((deviceSn, count) -> {
|
|
||||||
log.info(" 设备 {}: {} 个主题订阅", deviceSn, count.get());
|
|
||||||
});
|
|
||||||
log.info("=== 结束 ===");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设置命令管理器(延迟注入,避免循环依赖)
|
* 设置命令管理器(延迟注入,避免循环依赖)
|
||||||
|
|||||||
Binary file not shown.
+234
-45
@@ -18,6 +18,9 @@ import {
|
|||||||
UploadOutlined,
|
UploadOutlined,
|
||||||
DeleteOutlined,
|
DeleteOutlined,
|
||||||
PlayCircleOutlined,
|
PlayCircleOutlined,
|
||||||
|
VideoCameraOutlined,
|
||||||
|
LeftOutlined,
|
||||||
|
RightOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { DroneData } from '../hooks/useDroneSSE';
|
import { DroneData } from '../hooks/useDroneSSE';
|
||||||
import { waylineRouteApi, WaylineRouteListItemVO, WaypointVO } from '@/services/waylineRoute';
|
import { waylineRouteApi, WaylineRouteListItemVO, WaypointVO } from '@/services/waylineRoute';
|
||||||
@@ -115,9 +118,10 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
|||||||
const [selectedMissionCode, setSelectedMissionCode] = useState<string | null>(null);
|
const [selectedMissionCode, setSelectedMissionCode] = useState<string | null>(null);
|
||||||
const [missionLoading, setMissionLoading] = useState(false);
|
const [missionLoading, setMissionLoading] = useState(false);
|
||||||
const [createLoading, setCreateLoading] = useState(false);
|
const [createLoading, setCreateLoading] = useState(false);
|
||||||
const [imagePreviewVisible, setImagePreviewVisible] = useState(false);
|
const [mediaPreviewVisible, setMediaPreviewVisible] = useState(false);
|
||||||
const [previewImages, setPreviewImages] = useState<MissionImage[]>([]);
|
const [previewMediaList, setPreviewMediaList] = useState<MissionImage[]>([]);
|
||||||
const [imageLoading, setImageLoading] = useState(false);
|
const [currentMediaIndex, setCurrentMediaIndex] = useState(0);
|
||||||
|
const [mediaLoading, setMediaLoading] = useState(false);
|
||||||
|
|
||||||
// Tab 状态
|
// Tab 状态
|
||||||
const [activeTab, setActiveTab] = useState<string>('route');
|
const [activeTab, setActiveTab] = useState<string>('route');
|
||||||
@@ -261,58 +265,68 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
|||||||
|
|
||||||
clearWaylineEntities();
|
clearWaylineEntities();
|
||||||
|
|
||||||
|
// 调试:打印航点高度信息
|
||||||
|
console.log('[航线绘制] 航点数量:', waypoints.length);
|
||||||
|
console.log('[航线绘制] 前3个航点:', waypoints.slice(0, 3).map(wp => ({
|
||||||
|
index: wp.index,
|
||||||
|
lng: wp.longitude,
|
||||||
|
lat: wp.latitude,
|
||||||
|
height: wp.height,
|
||||||
|
ellipsoidHeight: wp.ellipsoidHeight,
|
||||||
|
})));
|
||||||
|
|
||||||
|
// 使用 height(相对高度)
|
||||||
const positions = waypoints.map(wp =>
|
const positions = waypoints.map(wp =>
|
||||||
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height || 100)
|
Cesium.Cartesian3.fromDegrees(
|
||||||
|
wp.longitude,
|
||||||
|
wp.latitude,
|
||||||
|
wp.height ?? 100
|
||||||
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
// 计划航线(蓝色)
|
// 计划航线(蓝色)- 使用简单的实线,加粗
|
||||||
waylineEntityRef.current = viewer.entities.add({
|
waylineEntityRef.current = viewer.entities.add({
|
||||||
name: '计划航线',
|
name: '计划航线',
|
||||||
polyline: {
|
polyline: {
|
||||||
positions: positions,
|
positions: positions,
|
||||||
width: 3,
|
width: 6,
|
||||||
material: new Cesium.PolylineGlowMaterialProperty({
|
material: Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9),
|
||||||
glowPower: 0.2,
|
|
||||||
color: Cesium.Color.fromCssColorString('#1890ff'),
|
|
||||||
}),
|
|
||||||
clampToGround: false,
|
clampToGround: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// 航点标记 - 只标注关键航点(首尾和间隔点)避免重叠
|
// 航点标记
|
||||||
const totalPoints = waypoints.length;
|
const totalPoints = waypoints.length;
|
||||||
// 根据航点数量决定标注间隔:超过20个点时每5个标一个,超过50个每10个标一个
|
|
||||||
const labelInterval = totalPoints > 50 ? 10 : totalPoints > 20 ? 5 : totalPoints > 10 ? 3 : 1;
|
const labelInterval = totalPoints > 50 ? 10 : totalPoints > 20 ? 5 : totalPoints > 10 ? 3 : 1;
|
||||||
|
|
||||||
waypoints.forEach((wp, index) => {
|
waypoints.forEach((wp, index) => {
|
||||||
const isFirst = index === 0;
|
const isFirst = index === 0;
|
||||||
const isLast = index === totalPoints - 1;
|
const isLast = index === totalPoints - 1;
|
||||||
const isKeyPoint = isFirst || isLast || (index % labelInterval === 0);
|
const isKeyPoint = isFirst || isLast || (index % labelInterval === 0);
|
||||||
|
|
||||||
// 航点统一用蓝色系,起点用深蓝,终点用紫色,中间用浅蓝
|
|
||||||
// 避免与无人机(红色)和飞行轨迹(绿色)混淆
|
|
||||||
const pointColor = isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff';
|
const pointColor = isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff';
|
||||||
|
const altitude = wp.height ?? 100;
|
||||||
|
|
||||||
const entity = viewer.entities.add({
|
const entity = viewer.entities.add({
|
||||||
name: `航点${index + 1}`,
|
name: `航点${index + 1}`,
|
||||||
position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height || 100),
|
position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, altitude),
|
||||||
point: {
|
point: {
|
||||||
pixelSize: isKeyPoint ? 8 : 5, // 关键点稍大,普通点更小
|
pixelSize: isKeyPoint ? 12 : 8,
|
||||||
color: Cesium.Color.fromCssColorString(pointColor),
|
color: Cesium.Color.fromCssColorString(pointColor),
|
||||||
outlineColor: Cesium.Color.WHITE,
|
outlineColor: Cesium.Color.WHITE,
|
||||||
outlineWidth: isKeyPoint ? 2 : 1,
|
outlineWidth: 2,
|
||||||
|
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||||
},
|
},
|
||||||
label: isKeyPoint ? {
|
label: isKeyPoint ? {
|
||||||
text: isFirst ? '起' : isLast ? '终' : `${index + 1}`,
|
text: isFirst ? '起' : isLast ? '终' : `${index + 1}`,
|
||||||
font: '10px sans-serif',
|
font: '12px sans-serif',
|
||||||
fillColor: Cesium.Color.WHITE,
|
fillColor: Cesium.Color.WHITE,
|
||||||
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
|
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
|
||||||
outlineWidth: 2,
|
outlineWidth: 2,
|
||||||
outlineColor: Cesium.Color.BLACK,
|
outlineColor: Cesium.Color.BLACK,
|
||||||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||||||
pixelOffset: new Cesium.Cartesian2(0, -10),
|
pixelOffset: new Cesium.Cartesian2(0, -12),
|
||||||
scaleByDistance: new Cesium.NearFarScalar(100, 1.0, 5000, 0.5), // 远处缩小
|
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||||
} : undefined, // 非关键点不显示标签
|
} : undefined,
|
||||||
});
|
});
|
||||||
waypointEntitiesRef.current.push(entity);
|
waypointEntitiesRef.current.push(entity);
|
||||||
});
|
});
|
||||||
@@ -442,31 +456,54 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
|||||||
}
|
}
|
||||||
}, [selectedRouteId, routeList, deviceSn, tourismId, isDockIdle, loadMissionsByDevice]);
|
}, [selectedRouteId, routeList, deviceSn, tourismId, isDockIdle, loadMissionsByDevice]);
|
||||||
|
|
||||||
// 查看任务图片
|
// 判断是否为视频文件
|
||||||
const handleViewMissionImages = useCallback(async (mission: Mission) => {
|
const isVideoFile = useCallback((fileType?: string) => {
|
||||||
|
if (!fileType) return false;
|
||||||
|
const videoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo'];
|
||||||
|
return videoTypes.includes(fileType.toLowerCase()) || fileType.toLowerCase().startsWith('video/');
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 查看任务媒体(图片和视频)
|
||||||
|
const handleViewMissionMedia = useCallback(async (mission: Mission) => {
|
||||||
if (!mission.missionCode) return;
|
if (!mission.missionCode) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setImageLoading(true);
|
setMediaLoading(true);
|
||||||
const res = await listMissionImage(mission.missionCode);
|
const res = await listMissionImage(mission.missionCode);
|
||||||
if (res.resp_code === 0) {
|
if (res.resp_code === 0) {
|
||||||
setPreviewImages(res.data || []);
|
setPreviewMediaList(res.data || []);
|
||||||
|
setCurrentMediaIndex(0);
|
||||||
if (res.data && res.data.length > 0) {
|
if (res.data && res.data.length > 0) {
|
||||||
setImagePreviewVisible(true);
|
setMediaPreviewVisible(true);
|
||||||
} else {
|
} else {
|
||||||
message.info('该任务暂无图片');
|
message.info('该任务暂无媒体文件');
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
message.error(res.resp_msg || '获取图片失败');
|
message.error(res.resp_msg || '获取媒体文件失败');
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('获取任务图片失败:', e);
|
console.error('获取任务媒体失败:', e);
|
||||||
message.error('获取任务图片失败');
|
message.error('获取媒体文件失败');
|
||||||
} finally {
|
} finally {
|
||||||
setImageLoading(false);
|
setMediaLoading(false);
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// 切换到上一个媒体
|
||||||
|
const handlePrevMedia = useCallback(() => {
|
||||||
|
setCurrentMediaIndex(prev => (prev > 0 ? prev - 1 : previewMediaList.length - 1));
|
||||||
|
}, [previewMediaList.length]);
|
||||||
|
|
||||||
|
// 切换到下一个媒体
|
||||||
|
const handleNextMedia = useCallback(() => {
|
||||||
|
setCurrentMediaIndex(prev => (prev < previewMediaList.length - 1 ? prev + 1 : 0));
|
||||||
|
}, [previewMediaList.length]);
|
||||||
|
|
||||||
|
// 当前预览的媒体
|
||||||
|
const currentMedia = useMemo(() => {
|
||||||
|
return previewMediaList[currentMediaIndex];
|
||||||
|
}, [previewMediaList, currentMediaIndex]);
|
||||||
|
|
||||||
// 完成任务
|
// 完成任务
|
||||||
const handleCompleteMission = useCallback(async (mission: Mission) => {
|
const handleCompleteMission = useCallback(async (mission: Mission) => {
|
||||||
if (!mission.missionCode) return;
|
if (!mission.missionCode) return;
|
||||||
@@ -801,14 +838,14 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.taskActions}>
|
<div className={styles.taskActions}>
|
||||||
<Tooltip title="查看图片">
|
<Tooltip title="查看媒体">
|
||||||
<button
|
<button
|
||||||
className={styles.actionBtn}
|
className={styles.actionBtn}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
handleViewMissionImages(mission);
|
handleViewMissionMedia(mission);
|
||||||
}}
|
}}
|
||||||
disabled={imageLoading}
|
disabled={mediaLoading}
|
||||||
>
|
>
|
||||||
<PictureOutlined />
|
<PictureOutlined />
|
||||||
</button>
|
</button>
|
||||||
@@ -907,17 +944,169 @@ const TaskPanel: React.FC<TaskPanelProps> = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 图片预览 */}
|
{/* 媒体预览 Modal(支持图片和视频) */}
|
||||||
<Image.PreviewGroup
|
<Modal
|
||||||
preview={{
|
title={
|
||||||
visible: imagePreviewVisible,
|
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||||
onVisibleChange: (vis) => setImagePreviewVisible(vis),
|
{currentMedia && isVideoFile(currentMedia.fileType) ? (
|
||||||
}}
|
<VideoCameraOutlined />
|
||||||
|
) : (
|
||||||
|
<PictureOutlined />
|
||||||
|
)}
|
||||||
|
<span>媒体预览</span>
|
||||||
|
{previewMediaList.length > 1 && (
|
||||||
|
<span style={{ fontSize: 12, color: '#999', marginLeft: 8 }}>
|
||||||
|
{currentMediaIndex + 1} / {previewMediaList.length}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
open={mediaPreviewVisible}
|
||||||
|
onCancel={() => setMediaPreviewVisible(false)}
|
||||||
|
footer={null}
|
||||||
|
width={800}
|
||||||
|
centered
|
||||||
|
destroyOnClose
|
||||||
|
bodyStyle={{ padding: 0, background: '#000', minHeight: 400 }}
|
||||||
>
|
>
|
||||||
{previewImages.map((img, index) => (
|
{currentMedia && (
|
||||||
<Image key={img.id || index} src={img.viewUrl} style={{ display: 'none' }} />
|
<div style={{ position: 'relative' }}>
|
||||||
))}
|
{/* 媒体内容 */}
|
||||||
</Image.PreviewGroup>
|
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 400 }}>
|
||||||
|
{isVideoFile(currentMedia.fileType) ? (
|
||||||
|
<video
|
||||||
|
key={currentMedia.id || currentMediaIndex}
|
||||||
|
src={currentMedia.viewUrl}
|
||||||
|
controls
|
||||||
|
autoPlay
|
||||||
|
style={{ maxWidth: '100%', maxHeight: '70vh' }}
|
||||||
|
>
|
||||||
|
您的浏览器不支持视频播放
|
||||||
|
</video>
|
||||||
|
) : (
|
||||||
|
<Image
|
||||||
|
src={currentMedia.viewUrl}
|
||||||
|
style={{ maxWidth: '100%', maxHeight: '70vh' }}
|
||||||
|
preview={false}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 左右切换按钮 */}
|
||||||
|
{previewMediaList.length > 1 && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={handlePrevMedia}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
left: 10,
|
||||||
|
top: '50%',
|
||||||
|
transform: 'translateY(-50%)',
|
||||||
|
background: 'rgba(0,0,0,0.5)',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: '50%',
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
color: '#fff',
|
||||||
|
cursor: 'pointer',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LeftOutlined />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleNextMedia}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
right: 10,
|
||||||
|
top: '50%',
|
||||||
|
transform: 'translateY(-50%)',
|
||||||
|
background: 'rgba(0,0,0,0.5)',
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: '50%',
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
color: '#fff',
|
||||||
|
cursor: 'pointer',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<RightOutlined />
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 媒体信息 */}
|
||||||
|
<div style={{ padding: '12px 16px', background: '#1f1f1f', color: '#fff' }}>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||||
|
<span>
|
||||||
|
{isVideoFile(currentMedia.fileType) ? (
|
||||||
|
<Tag color="blue" icon={<VideoCameraOutlined />}>视频</Tag>
|
||||||
|
) : (
|
||||||
|
<Tag color="green" icon={<PictureOutlined />}>图片</Tag>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
{currentMedia.shootTime && (
|
||||||
|
<span style={{ fontSize: 12, color: '#999' }}>
|
||||||
|
拍摄时间: {formatTime(currentMedia.shootTime)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 缩略图列表 */}
|
||||||
|
{previewMediaList.length > 1 && (
|
||||||
|
<div style={{
|
||||||
|
padding: '8px 16px',
|
||||||
|
background: '#1f1f1f',
|
||||||
|
display: 'flex',
|
||||||
|
gap: 8,
|
||||||
|
overflowX: 'auto',
|
||||||
|
}}>
|
||||||
|
{previewMediaList.map((media, index) => (
|
||||||
|
<div
|
||||||
|
key={media.id || index}
|
||||||
|
onClick={() => setCurrentMediaIndex(index)}
|
||||||
|
style={{
|
||||||
|
width: 60,
|
||||||
|
height: 60,
|
||||||
|
flexShrink: 0,
|
||||||
|
cursor: 'pointer',
|
||||||
|
border: index === currentMediaIndex ? '2px solid #1890ff' : '2px solid transparent',
|
||||||
|
borderRadius: 4,
|
||||||
|
overflow: 'hidden',
|
||||||
|
position: 'relative',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isVideoFile(media.fileType) ? (
|
||||||
|
<div style={{
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
background: '#333',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
}}>
|
||||||
|
<VideoCameraOutlined style={{ fontSize: 20, color: '#fff' }} />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<img
|
||||||
|
src={media.viewUrl}
|
||||||
|
alt={`媒体${index + 1}`}
|
||||||
|
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Modal>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+5
-4
@@ -395,8 +395,9 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
|||||||
longitude: droneData.longitude,
|
longitude: droneData.longitude,
|
||||||
latitude: droneData.latitude,
|
latitude: droneData.latitude,
|
||||||
height: droneData.height, // 相对高度(相对于起飞点)
|
height: droneData.height, // 相对高度(相对于起飞点)
|
||||||
elevation: droneData.elevation, // 海拔高度
|
elevation: droneData.elevation, // 海拔高度(椭球高度)
|
||||||
altitude: droneData.height, // 3D地图显示用
|
// 3D地图显示用 height(相对高度),与航线的 height 对应
|
||||||
|
altitude: droneData.height,
|
||||||
heading: droneData.attitude_head,
|
heading: droneData.attitude_head,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
};
|
};
|
||||||
@@ -407,7 +408,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
|||||||
if (!viewerRef.current || !Cesium || !realtimePosition) return;
|
if (!viewerRef.current || !Cesium || !realtimePosition) return;
|
||||||
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
|
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
|
||||||
|
|
||||||
const droneHeight = realtimePosition.height ?? 50;
|
const droneHeight = realtimePosition.altitude ?? 50;
|
||||||
|
|
||||||
viewerRef.current.camera.flyTo({
|
viewerRef.current.camera.flyTo({
|
||||||
destination: Cesium.Cartesian3.fromDegrees(
|
destination: Cesium.Cartesian3.fromDegrees(
|
||||||
@@ -434,7 +435,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
|||||||
const currentPos = {
|
const currentPos = {
|
||||||
lon: realtimePosition.longitude,
|
lon: realtimePosition.longitude,
|
||||||
lat: realtimePosition.latitude,
|
lat: realtimePosition.latitude,
|
||||||
height: realtimePosition.height ?? 0,
|
height: realtimePosition.altitude ?? 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
// 节流:1秒内且位置没变化则跳过
|
// 节流:1秒内且位置没变化则跳过
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ export interface WaypointVO {
|
|||||||
index: number;
|
index: number;
|
||||||
longitude: number;
|
longitude: number;
|
||||||
latitude: number;
|
latitude: number;
|
||||||
height: number;
|
height: number; // 相对高度
|
||||||
|
executeHeight?: number; // 执行高度
|
||||||
|
ellipsoidHeight?: number; // 椭球高度(用于3D地图显示)
|
||||||
speed?: number;
|
speed?: number;
|
||||||
headingAngle?: number;
|
headingAngle?: number;
|
||||||
actions?: WaypointActionVO[];
|
actions?: WaypointActionVO[];
|
||||||
|
|||||||
Reference in New Issue
Block a user