diff --git a/.claude/settings.local.json b/.claude/settings.local.json index a1a7938c..affcb935 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -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(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(cmd /c move:*)" + "Bash(cmd /c move:*)", + "Bash(set:*)" ], "deny": [], "ask": [] diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceAlarmController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceAlarmController.java index 17b2d0da..c91da4c3 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceAlarmController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceAlarmController.java @@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.*; /** * 设备告警数据接口 * 提供一次性订阅获取设备 fire_alarm 和 msg_alarm 数据的接口 + * 使用独立 WebSocket 连接,用完即关,不影响其他业务 * * @author lishilin * @date 2025-01-19 @@ -30,35 +31,37 @@ public class DeviceAlarmController { @Autowired private DeviceAlarmDataService alarmDataService; + // ==================== 独立订阅接口 ==================== + /** - * 一次性订阅获取设备告警数据 - * 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅并关闭 WebSocket - * 如果实时订阅未获取到数据,会尝试从 Redis 缓存获取 + * 一次性订阅获取 fire_alarm 数据(机库状态数据) + * 使用独立的 WebSocket 连接,不影响其他 SSE 订阅 + * 默认超时10秒,响应快速 * * @param deviceSn 设备SN - * @return 包含 fire_alarm 和 msg_alarm 数据的结果 + * @return fire_alarm 数据 */ - @GetMapping("/subscribe/{deviceSn}") - @Operation(summary = "一次性订阅获取设备告警数据", description = "订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅") - public Result subscribeOnce( + @GetMapping("/fire-alarm/{deviceSn}") + @Operation(summary = "一次性获取机库状态数据", description = "独立 WebSocket 连接获取 fire_alarm,用完即关,不影响其他业务") + public Result getFireAlarm( @Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) { - log.info("接收到一次性订阅请求: deviceSn={}", deviceSn); + log.info("请求获取 fire_alarm: deviceSn={}", deviceSn); if (deviceSn == null || deviceSn.trim().isEmpty()) { return Result.failed("设备SN不能为空"); } 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.setAlarmType(alarmResult.getAlarmType()); response.setSuccess(alarmResult.isSuccess()); response.setMessage(alarmResult.getMessage()); - response.setFireAlarmData(alarmResult.getFireAlarmData()); - response.setMsgAlarmData(alarmResult.getMsgAlarmData()); - response.setFireAlarmFromCache(alarmResult.isFireAlarmFromCache()); - response.setMsgAlarmFromCache(alarmResult.isMsgAlarmFromCache()); + response.setData(alarmResult.getData()); + response.setFromCache(alarmResult.isFromCache()); if (alarmResult.isSuccess()) { return Result.succeed(response, "获取成功"); @@ -67,45 +70,44 @@ public class DeviceAlarmController { } } catch (Exception e) { - log.error("一次性订阅请求失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e); - return Result.failed("订阅失败: " + e.getMessage()); + log.error("获取 fire_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e); + return Result.failed("获取失败: " + e.getMessage()); } } /** - * 一次性订阅获取设备告警数据(带超时参数) + * 一次性订阅获取 fire_alarm 数据(带超时参数) * * @param deviceSn 设备SN - * @param timeoutSeconds 超时时间(秒),默认30秒 - * @return 包含 fire_alarm 和 msg_alarm 数据的结果 + * @param timeoutSeconds 超时时间(秒) + * @return fire_alarm 数据 */ - @GetMapping("/subscribe/{deviceSn}/timeout/{timeoutSeconds}") - @Operation(summary = "一次性订阅获取设备告警数据(带超时)", description = "订阅 fire_alarm 和 msg_alarm,可自定义超时时间") - public Result subscribeOnceWithTimeout( + @GetMapping("/fire-alarm/{deviceSn}/timeout/{timeoutSeconds}") + @Operation(summary = "一次性获取机库状态数据(带超时)", description = "可自定义超时时间") + public Result getFireAlarmWithTimeout( @Parameter(description = "设备SN", required = true) @PathVariable String deviceSn, @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()) { return Result.failed("设备SN不能为空"); } - if (timeoutSeconds < 1 || timeoutSeconds > 120) { - return Result.failed("超时时间必须在1-120秒之间"); + if (timeoutSeconds < 1 || timeoutSeconds > 60) { + return Result.failed("超时时间必须在1-60秒之间"); } try { - OneTimeSubscriptionService.DeviceAlarmResult alarmResult = - oneTimeSubscriptionService.subscribeOnce(deviceSn, timeoutSeconds); + OneTimeSubscriptionService.SingleAlarmResult alarmResult = + oneTimeSubscriptionService.subscribeFireAlarmOnce(deviceSn, timeoutSeconds); - 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.setFireAlarmData(alarmResult.getFireAlarmData()); - response.setMsgAlarmData(alarmResult.getMsgAlarmData()); - response.setFireAlarmFromCache(alarmResult.isFireAlarmFromCache()); - response.setMsgAlarmFromCache(alarmResult.isMsgAlarmFromCache()); + response.setData(alarmResult.getData()); + response.setFromCache(alarmResult.isFromCache()); if (alarmResult.isSuccess()) { return Result.succeed(response, "获取成功"); @@ -114,44 +116,169 @@ public class DeviceAlarmController { } } catch (Exception e) { - log.error("一次性订阅请求失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e); - return Result.failed("订阅失败: " + e.getMessage()); + log.error("获取 fire_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e); + return Result.failed("获取失败: " + e.getMessage()); } } /** - * 从 Redis 缓存获取设备告警数据(不进行实时订阅) + * 一次性订阅获取 msg_alarm 数据(无人机遥测数据) + * 使用独立的 WebSocket 连接,不影响其他 SSE 订阅 + * 默认超时10秒 + * + * 注意:msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有数据 * * @param deviceSn 设备SN - * @return 缓存的 fire_alarm 和 msg_alarm 数据 + * @return msg_alarm 数据 */ - @GetMapping("/cache/{deviceSn}") - @Operation(summary = "从缓存获取设备告警数据", description = "仅从 Redis 缓存获取,不进行实时订阅") - public Result getFromCache( + @GetMapping("/msg-alarm/{deviceSn}") + @Operation(summary = "一次性获取无人机遥测数据", description = "独立 WebSocket 连接获取 msg_alarm,用完即关。注意:无人机需开机才有数据") + public Result getMsgAlarm( @Parameter(description = "设备SN", required = true) @PathVariable String deviceSn) { - log.info("从缓存获取设备告警数据: deviceSn={}", deviceSn); + log.info("请求获取 msg_alarm: deviceSn={}", deviceSn); if (deviceSn == null || deviceSn.trim().isEmpty()) { return Result.failed("设备SN不能为空"); } try { - JSONObject fireAlarmData = alarmDataService.getFireAlarmData(deviceSn); - JSONObject msgAlarmData = alarmDataService.getMsgAlarmData(deviceSn); + OneTimeSubscriptionService.SingleAlarmResult alarmResult = + 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 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 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.setFireAlarmData(fireAlarmData); - response.setMsgAlarmData(msgAlarmData); - response.setFireAlarmFromCache(fireAlarmData != null); - response.setMsgAlarmFromCache(msgAlarmData != null); - response.setSuccess(fireAlarmData != null || msgAlarmData != null); - response.setMessage(buildCacheResultMessage(fireAlarmData != null, msgAlarmData != null)); + response.setAlarmType("fire_alarm"); + response.setData(data); + response.setFromCache(true); + response.setSuccess(data != null); + response.setMessage(data != null ? "缓存数据存在" : "缓存中无数据"); return Result.succeed(response); } 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 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()); } } @@ -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 - public static class DeviceAlarmResponse { + public static class SingleAlarmResponse { /** * 设备SN */ private String deviceSn; + /** + * 告警类型(fire_alarm 或 msg_alarm) + */ + private String alarmType; + /** * 是否成功 */ @@ -217,23 +334,13 @@ public class DeviceAlarmController { private String message; /** - * fire_alarm 数据(机库状态数据) + * 告警数据 */ - private JSONObject fireAlarmData; + private JSONObject data; /** - * msg_alarm 数据(无人机遥测数据) + * 数据是否来自缓存 */ - private JSONObject msgAlarmData; - - /** - * fire_alarm 数据是否来自缓存 - */ - private boolean fireAlarmFromCache; - - /** - * msg_alarm 数据是否来自缓存 - */ - private boolean msgAlarmFromCache; + private boolean fromCache; } } diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/OneTimeSubscriptionService.java b/zlt-business/device-center/src/main/java/com/central/device/service/OneTimeSubscriptionService.java index eaab8398..8cf3405f 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/OneTimeSubscriptionService.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/OneTimeSubscriptionService.java @@ -1,29 +1,26 @@ package com.central.device.service; import com.alibaba.fastjson.JSONObject; -import com.central.device.sse.manager.SseEmitterManager; -import com.central.device.websocket.client.JetLinksWebSocketClient; -import com.central.device.websocket.handler.DeviceMessageHandler; +import com.central.device.websocket.client.IsolatedWebSocketClient; +import com.central.device.websocket.config.WebSocketProperties; +import com.central.device.websocket.manager.TokenManager; import com.central.device.websocket.model.SubscriptionTopic; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.HashSet; -import java.util.Set; import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * 一次性订阅服务 - * 用于一次性获取设备的 fire_alarm 和 msg_alarm 数据 - * 订阅成功后自动取消订阅并关闭 WebSocket 连接,防止资源浪费 + * 用于一次性获取设备的 fire_alarm 或 msg_alarm 数据 + * 使用独立的 WebSocket 连接,用完即关,不影响其他业务 * * 设计原则: - * 1. 不影响已有的 SSE 订阅(引用计数方式管理) - * 2. msg_alarm 只有无人机开机才有消息,需要容错处理 - * 3. 支持只获取到部分数据的情况 + * 1. 每个订阅使用独立的 WebSocket 连接,完全隔离 + * 2. 用完即关,不占用资源 + * 3. 不影响 SSE 订阅和其他业务 * * @author lishilin * @date 2025-01-19 @@ -33,270 +30,234 @@ import java.util.concurrent.atomic.AtomicReference; public class OneTimeSubscriptionService { /** - * 默认订阅超时时间(秒) + * 独立订阅默认超时时间(秒) */ - private static final int DEFAULT_TIMEOUT_SECONDS = 30; - - @Autowired - private JetLinksWebSocketClient webSocketClient; - - @Autowired - private DeviceMessageHandler messageHandler; + private static final int DEFAULT_TIMEOUT_SECONDS = 10; @Autowired private DeviceAlarmDataService alarmDataService; - @Autowired(required = false) - private SseEmitterManager sseEmitterManager; + @Autowired + private WebSocketProperties webSocketProperties; + + @Autowired + private TokenManager tokenManager; /** - * 一次性订阅获取设备告警数据 - * 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅并关闭 WebSocket + * 独立订阅获取 fire_alarm 数据(机库状态数据) + * 使用独立的 WebSocket 连接,不影响现有 SSE 订阅 + * 获取数据后立即关闭连接 * * @param deviceSn 设备SN - * @return 包含 fire_alarm 和 msg_alarm 数据的结果 + * @return 包含 fire_alarm 数据的结果 */ - public DeviceAlarmResult subscribeOnce(String deviceSn) { - return subscribeOnce(deviceSn, DEFAULT_TIMEOUT_SECONDS); + public SingleAlarmResult subscribeFireAlarmOnce(String deviceSn) { + return subscribeFireAlarmOnce(deviceSn, DEFAULT_TIMEOUT_SECONDS); } /** - * 一次性订阅获取设备告警数据 - * 订阅 fire_alarm 和 msg_alarm,获取数据后立即取消订阅 - * - * 注意: - * 1. msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有消息 - * 2. 不会无限等待,超时后会尝试从 Redis 获取缓存数据 - * 3. 不会影响已有的 SSE 订阅 + * 独立订阅获取 fire_alarm 数据(机库状态数据) + * 使用独立的 WebSocket 连接,不影响现有 SSE 订阅 * * @param deviceSn 设备SN * @param timeoutSeconds 超时时间(秒) - * @return 包含 fire_alarm 和 msg_alarm 数据的结果 + * @return 包含 fire_alarm 数据的结果 */ - public DeviceAlarmResult subscribeOnce(String deviceSn, int timeoutSeconds) { - log.info("开始一次性订阅: deviceSn={}, timeout={}s", deviceSn, timeoutSeconds); + public SingleAlarmResult subscribeFireAlarmOnce(String deviceSn, int timeoutSeconds) { + log.info("独立订阅 fire_alarm 开始: deviceSn={}, timeout={}s", deviceSn, timeoutSeconds); - DeviceAlarmResult result = new DeviceAlarmResult(); + SingleAlarmResult result = new SingleAlarmResult(); result.setDeviceSn(deviceSn); + result.setAlarmType("fire_alarm"); - // 检查 SSE 是否已有此设备的订阅(用于判断是否需要自己管理订阅) - int sseRefCount = getSseRefCount(deviceSn); - boolean hasSseSubscription = sseRefCount > 0; - // 检查设备是否已在消息处理器中注册 - boolean deviceAlreadyRegistered = messageHandler.getDeviceData(deviceSn) != null; + // 用于存储接收到的数据 + AtomicReference dataRef = new AtomicReference<>(); + CountDownLatch dataLatch = new CountDownLatch(1); - log.info("设备 {} 状态检查: SSE引用计数={}, 已注册={}", deviceSn, sseRefCount, deviceAlreadyRegistered); - - // 记录本次订阅新增的主题(用于清理时只取消自己订阅的) - Set mySubscribedTopics = new HashSet<>(); - - // 用于存储回调接收到的数据 - AtomicReference fireAlarmData = new AtomicReference<>(); - AtomicReference 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); + // 创建独立的 WebSocket 客户端 + IsolatedWebSocketClient isolatedClient = new IsolatedWebSocketClient( + webSocketProperties, tokenManager, deviceSn, SubscriptionTopic.EVENT_FIRE_ALARM); try { - // 如果设备未注册,先添加设备到消息处理器(确保可以接收消息) - if (!deviceAlreadyRegistered) { - messageHandler.addDevice(deviceSn, null, null); - } - - // 注册 fire_alarm 回调 - messageHandler.registerFireAlarmCallback(deviceSn, (sn, data) -> { - if (!fireAlarmReceived.getAndSet(true)) { - log.info("一次性订阅收到 fire_alarm 数据: deviceSn={}", sn); - fireAlarmData.set(data); - fireAlarmLatch.countDown(); - } + // 连接并订阅 + boolean connected = isolatedClient.connectAndSubscribe(data -> { + log.info("独立订阅收到 fire_alarm 数据: deviceSn={}", deviceSn); + dataRef.set(data); + dataLatch.countDown(); }); - // 注册 msg_alarm 回调 - messageHandler.registerMsgAlarmCallback(deviceSn, (sn, data) -> { - if (!msgAlarmReceived.getAndSet(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); + if (!connected) { + log.warn("独立 WebSocket 连接失败,尝试从缓存获取: deviceSn={}", deviceSn); + return tryGetFromCache(result, deviceSn, true); } - log.info("一次性订阅等待结束: deviceSn={}, fireAlarm={}, msgAlarm={}", - deviceSn, fireAlarmReceived.get(), msgAlarmReceived.get()); + // 等待数据 + boolean received = dataLatch.await(timeoutSeconds, TimeUnit.SECONDS); - // 设置结果 - result.setFireAlarmData(fireAlarmData.get()); - result.setMsgAlarmData(msgAlarmData.get()); - - // 如果没有订阅到数据,尝试从 Redis 获取缓存数据 - if (result.getFireAlarmData() == null) { - JSONObject cachedFireAlarm = alarmDataService.getFireAlarmData(deviceSn); - if (cachedFireAlarm != null) { - log.info("从 Redis 获取 fire_alarm 缓存数据: deviceSn={}", deviceSn); - result.setFireAlarmData(cachedFireAlarm); - result.setFireAlarmFromCache(true); - } + if (received && dataRef.get() != null) { + result.setData(dataRef.get()); + result.setSuccess(true); + result.setFromCache(false); + result.setMessage("fire_alarm: 实时订阅获取成功"); + log.info("独立订阅 fire_alarm 成功: deviceSn={}", deviceSn); + } else { + log.info("独立订阅 fire_alarm 超时,尝试从缓存获取: deviceSn={}", deviceSn); + return tryGetFromCache(result, deviceSn, 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) { Thread.currentThread().interrupt(); - log.error("一次性订阅被中断: deviceSn={}", deviceSn); + log.error("独立订阅 fire_alarm 被中断: deviceSn={}", deviceSn); result.setSuccess(false); result.setMessage("订阅被中断"); } catch (Exception e) { - log.error("一次性订阅失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e); - result.setSuccess(false); - result.setMessage("订阅失败: " + e.getMessage()); + log.error("独立订阅 fire_alarm 失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e); + return tryGetFromCache(result, deviceSn, true); } finally { - // 清理:移除回调、取消订阅(如果 SSE 没有订阅的话) - cleanupSubscription(deviceSn, hasSseSubscription, deviceAlreadyRegistered, mySubscribedTopics); + // 关闭独立连接 + isolatedClient.close(); + log.info("独立 WebSocket 连接已关闭: deviceSn={}, clientId={}", + deviceSn, isolatedClient.getClientId()); } return result; } /** - * 获取 SSE 对设备的引用计数 + * 独立订阅获取 msg_alarm 数据(无人机遥测数据) + * 使用独立的 WebSocket 连接,不影响现有 SSE 订阅 + * 获取数据后立即关闭连接 + * + * 注意:msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有数据 * * @param deviceSn 设备SN - * @return 引用计数,0 表示无订阅 + * @return 包含 msg_alarm 数据的结果 */ - private int getSseRefCount(String deviceSn) { - if (sseEmitterManager == null) { - return 0; - } - try { - return sseEmitterManager.getDeviceRefCount(deviceSn); - } catch (Exception e) { - log.warn("获取 SSE 引用计数失败: deviceSn={}, error={}", deviceSn, e.getMessage()); - return 0; - } + public SingleAlarmResult subscribeMsgAlarmOnce(String deviceSn) { + return subscribeMsgAlarmOnce(deviceSn, DEFAULT_TIMEOUT_SECONDS); } /** - * 清理订阅资源 - * 设计原则: - * 1. 不影响 SSE 已有的订阅(fire_alarm, online, offline) - * 2. msg_alarm 是一次性订阅额外订阅的,需要自己负责取消 - * 3. 【重要】一次性订阅和SSE订阅完全独立,一次性订阅不应该影响 deviceDataMap + * 独立订阅获取 msg_alarm 数据(无人机遥测数据) + * 使用独立的 WebSocket 连接,不影响现有 SSE 订阅 * - * @param deviceSn 设备SN - * @param hasSseSubscription SSE 是否已有订阅(订阅开始时的状态) - * @param deviceAlreadyRegistered 设备是否在一次性订阅前就已注册 - * @param mySubscribedTopics 本次一次性订阅新增的主题 + * 注意:msg_alarm 只有无人机开机才有消息,如果无人机未开机则不会有数据 + * + * @param deviceSn 设备SN + * @param timeoutSeconds 超时时间(秒) + * @return 包含 msg_alarm 数据的结果 */ - private void cleanupSubscription(String deviceSn, boolean hasSseSubscription, - boolean deviceAlreadyRegistered, Set mySubscribedTopics) { + public SingleAlarmResult subscribeMsgAlarmOnce(String deviceSn, int timeoutSeconds) { + log.info("独立订阅 msg_alarm 开始: deviceSn={}, timeout={}s", deviceSn, timeoutSeconds); + + SingleAlarmResult result = new SingleAlarmResult(); + result.setDeviceSn(deviceSn); + result.setAlarmType("msg_alarm"); + + // 用于存储接收到的数据 + AtomicReference dataRef = new AtomicReference<>(); + CountDownLatch dataLatch = new CountDownLatch(1); + + // 创建独立的 WebSocket 客户端 + IsolatedWebSocketClient isolatedClient = new IsolatedWebSocketClient( + webSocketProperties, tokenManager, deviceSn, SubscriptionTopic.EVENT_MSG_ALARM); + try { - // 【重要】重新检查当前 SSE 引用计数,因为在订阅过程中可能有新的 SSE 连接建立 - int currentSseRefCount = getSseRefCount(deviceSn); - boolean currentHasSseSubscription = currentSseRefCount > 0; + // 连接并订阅 + boolean connected = isolatedClient.connectAndSubscribe(data -> { + log.info("独立订阅收到 msg_alarm 数据: deviceSn={}", deviceSn); + dataRef.set(data); + dataLatch.countDown(); + }); - log.info("清理一次性订阅资源: deviceSn={}, 订阅开始时SSE状态={}, 当前SSE引用计数={}, deviceAlreadyRegistered={}", - deviceSn, hasSseSubscription, currentSseRefCount, deviceAlreadyRegistered); - - // 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); + if (!connected) { + log.warn("独立 WebSocket 连接失败,尝试从缓存获取: deviceSn={}", deviceSn); + return tryGetFromCache(result, deviceSn, false); } + // 等待数据 + 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) { - 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 结果对象 - * @return 消息描述 + * @param result 结果对象 + * @param deviceSn 设备SN + * @param isFireAlarm 是否是 fire_alarm(否则是 msg_alarm) + * @return 更新后的结果 */ - private String buildResultMessage(DeviceAlarmResult result) { - StringBuilder sb = new StringBuilder(); - if (result.getFireAlarmData() != null) { - sb.append("fire_alarm: ").append(result.isFireAlarmFromCache() ? "来自缓存" : "实时订阅"); - } else { - sb.append("fire_alarm: 未获取到"); + private SingleAlarmResult tryGetFromCache(SingleAlarmResult result, String deviceSn, boolean isFireAlarm) { + try { + JSONObject cachedData = isFireAlarm + ? alarmDataService.getFireAlarmData(deviceSn) + : alarmDataService.getMsgAlarmData(deviceSn); + + 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(", "); - if (result.getMsgAlarmData() != null) { - sb.append("msg_alarm: ").append(result.isMsgAlarmFromCache() ? "来自缓存" : "实时订阅"); - } else { - sb.append("msg_alarm: 未获取到"); - } - return sb.toString(); + return result; } /** - * 设备告警数据结果 + * 单一告警数据结果 */ @lombok.Data - public static class DeviceAlarmResult { + public static class SingleAlarmResult { /** * 设备SN */ private String deviceSn; /** - * 是否成功(至少获取到一种数据) + * 告警类型(fire_alarm 或 msg_alarm) + */ + private String alarmType; + + /** + * 是否成功 */ private boolean success; @@ -306,23 +267,13 @@ public class OneTimeSubscriptionService { private String message; /** - * fire_alarm 数据 + * 告警数据 */ - private JSONObject fireAlarmData; + private JSONObject data; /** - * msg_alarm 数据 + * 数据是否来自缓存 */ - private JSONObject msgAlarmData; - - /** - * fire_alarm 数据是否来自缓存 - */ - private boolean fireAlarmFromCache; - - /** - * msg_alarm 数据是否来自缓存 - */ - private boolean msgAlarmFromCache; + private boolean fromCache; } } diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/client/IsolatedWebSocketClient.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/IsolatedWebSocketClient.java new file mode 100644 index 00000000..4e56749b --- /dev/null +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/IsolatedWebSocketClient.java @@ -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 dataCallback; + + /** + * 连接完成回调 + */ + private CompletableFuture 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 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; + } +} diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java index d0c318ee..42e71cb1 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java @@ -55,6 +55,12 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { */ private final Set subscribedTopics = new HashSet<>(); + /** + * 主题对应的订阅ID:topic -> subscriptionId + * 订阅和取消订阅使用相同的ID,确保只取消自己的订阅 + */ + private final ConcurrentHashMap topicSubscriptionIds = new ConcurrentHashMap<>(); + /** * 设备订阅计数:deviceSn -> 订阅次数 * 用于管理同一设备多个主题的订阅,避免过早断开连接 @@ -511,11 +517,15 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { return; } + // 生成唯一的订阅ID,并保存到 Map 中 + String subscriptionId = "sub-" + deviceSn + "-" + topicEnum.name() + "-" + UUID.randomUUID().toString().substring(0, 8); + topicSubscriptionIds.put(topic, subscriptionId); + SubscriptionMessage message = SubscriptionMessage.builder() .type("sub") .topic(topic) .parameter(new JSONObject()) - .id("request-id-" + UUID.randomUUID().toString()) + .id(subscriptionId) .build(); send(JSON.toJSONString(message)); @@ -524,8 +534,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { // 更新设备订阅计数(只有实际发送订阅时才增加) deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet(); - log.info("发送订阅消息: topic={}, 设备{}订阅计数: {}", - topic, deviceSn, deviceSubscriptionCounts.get(deviceSn).get()); + log.info("发送订阅消息: topic={}, id={}, 设备{}订阅计数: {}", + topic, subscriptionId, deviceSn, deviceSubscriptionCounts.get(deviceSn).get()); } /** @@ -540,11 +550,18 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { 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() .type("unsub") .topic(topic) .parameter(new JSONObject()) - .id("request-id-" + UUID.randomUUID().toString()) + .id(subscriptionId) // 使用相同的订阅ID .build(); send(JSON.toJSONString(message)); @@ -566,8 +583,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { } } - log.info("取消订阅主题: topic={}, 剩余主题数: {}, 剩余主题: {}", - topic, subscribedTopics.size(), subscribedTopics); + log.info("取消订阅主题: topic={}, id={}, 剩余主题数: {}", + topic, subscriptionId, subscribedTopics.size()); } /** @@ -586,6 +603,8 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { subscribedTopics.clear(); // 清空设备订阅计数,重新订阅时会重新计算 deviceSubscriptionCounts.clear(); + // 清空订阅ID映射,重新订阅时会生成新的ID + topicSubscriptionIds.clear(); // 按设备分组重新订阅 Set deviceSns = new HashSet<>(); @@ -788,13 +807,6 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { 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()); } - /** - * 打印当前订阅状态(用于调试) - */ - 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("=== 结束 ==="); - } /** * 设置命令管理器(延迟注入,避免循环依赖) diff --git a/zlt-web/react-web-next/dist.zip b/zlt-web/react-web-next/dist.zip index fd793f65..81250a15 100644 Binary files a/zlt-web/react-web-next/dist.zip and b/zlt-web/react-web-next/dist.zip differ diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.tsx index 99b49431..2dfec506 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/TaskPanel.tsx @@ -18,6 +18,9 @@ import { UploadOutlined, DeleteOutlined, PlayCircleOutlined, + VideoCameraOutlined, + LeftOutlined, + RightOutlined, } from '@ant-design/icons'; import { DroneData } from '../hooks/useDroneSSE'; import { waylineRouteApi, WaylineRouteListItemVO, WaypointVO } from '@/services/waylineRoute'; @@ -115,9 +118,10 @@ const TaskPanel: React.FC = ({ const [selectedMissionCode, setSelectedMissionCode] = useState(null); const [missionLoading, setMissionLoading] = useState(false); const [createLoading, setCreateLoading] = useState(false); - const [imagePreviewVisible, setImagePreviewVisible] = useState(false); - const [previewImages, setPreviewImages] = useState([]); - const [imageLoading, setImageLoading] = useState(false); + const [mediaPreviewVisible, setMediaPreviewVisible] = useState(false); + const [previewMediaList, setPreviewMediaList] = useState([]); + const [currentMediaIndex, setCurrentMediaIndex] = useState(0); + const [mediaLoading, setMediaLoading] = useState(false); // Tab 状态 const [activeTab, setActiveTab] = useState('route'); @@ -261,58 +265,68 @@ const TaskPanel: React.FC = ({ 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 => - 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({ name: '计划航线', polyline: { positions: positions, - width: 3, - material: new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.2, - color: Cesium.Color.fromCssColorString('#1890ff'), - }), + width: 6, + material: Cesium.Color.fromCssColorString('#1890ff').withAlpha(0.9), clampToGround: false, }, }); - // 航点标记 - 只标注关键航点(首尾和间隔点)避免重叠 + // 航点标记 const totalPoints = waypoints.length; - // 根据航点数量决定标注间隔:超过20个点时每5个标一个,超过50个每10个标一个 const labelInterval = totalPoints > 50 ? 10 : totalPoints > 20 ? 5 : totalPoints > 10 ? 3 : 1; waypoints.forEach((wp, index) => { const isFirst = index === 0; const isLast = index === totalPoints - 1; const isKeyPoint = isFirst || isLast || (index % labelInterval === 0); - - // 航点统一用蓝色系,起点用深蓝,终点用紫色,中间用浅蓝 - // 避免与无人机(红色)和飞行轨迹(绿色)混淆 const pointColor = isFirst ? '#0050b3' : isLast ? '#722ed1' : '#1890ff'; + const altitude = wp.height ?? 100; const entity = viewer.entities.add({ name: `航点${index + 1}`, - position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height || 100), + position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, altitude), point: { - pixelSize: isKeyPoint ? 8 : 5, // 关键点稍大,普通点更小 + pixelSize: isKeyPoint ? 12 : 8, color: Cesium.Color.fromCssColorString(pointColor), outlineColor: Cesium.Color.WHITE, - outlineWidth: isKeyPoint ? 2 : 1, + outlineWidth: 2, + disableDepthTestDistance: Number.POSITIVE_INFINITY, }, label: isKeyPoint ? { text: isFirst ? '起' : isLast ? '终' : `${index + 1}`, - font: '10px sans-serif', + font: '12px sans-serif', fillColor: Cesium.Color.WHITE, style: Cesium.LabelStyle.FILL_AND_OUTLINE, outlineWidth: 2, outlineColor: Cesium.Color.BLACK, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, - pixelOffset: new Cesium.Cartesian2(0, -10), - scaleByDistance: new Cesium.NearFarScalar(100, 1.0, 5000, 0.5), // 远处缩小 - } : undefined, // 非关键点不显示标签 + pixelOffset: new Cesium.Cartesian2(0, -12), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + } : undefined, }); waypointEntitiesRef.current.push(entity); }); @@ -442,31 +456,54 @@ const TaskPanel: React.FC = ({ } }, [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; try { - setImageLoading(true); + setMediaLoading(true); const res = await listMissionImage(mission.missionCode); if (res.resp_code === 0) { - setPreviewImages(res.data || []); + setPreviewMediaList(res.data || []); + setCurrentMediaIndex(0); if (res.data && res.data.length > 0) { - setImagePreviewVisible(true); + setMediaPreviewVisible(true); } else { - message.info('该任务暂无图片'); + message.info('该任务暂无媒体文件'); } } else { - message.error(res.resp_msg || '获取图片失败'); + message.error(res.resp_msg || '获取媒体文件失败'); } } catch (e) { - console.error('获取任务图片失败:', e); - message.error('获取任务图片失败'); + console.error('获取任务媒体失败:', e); + message.error('获取媒体文件失败'); } 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) => { if (!mission.missionCode) return; @@ -801,14 +838,14 @@ const TaskPanel: React.FC = ({
- + @@ -907,17 +944,169 @@ const TaskPanel: React.FC = ({ )}
- {/* 图片预览 */} - setImagePreviewVisible(vis), - }} + {/* 媒体预览 Modal(支持图片和视频) */} + + {currentMedia && isVideoFile(currentMedia.fileType) ? ( + + ) : ( + + )} + 媒体预览 + {previewMediaList.length > 1 && ( + + {currentMediaIndex + 1} / {previewMediaList.length} + + )} + + } + open={mediaPreviewVisible} + onCancel={() => setMediaPreviewVisible(false)} + footer={null} + width={800} + centered + destroyOnClose + bodyStyle={{ padding: 0, background: '#000', minHeight: 400 }} > - {previewImages.map((img, index) => ( - - ))} - + {currentMedia && ( +
+ {/* 媒体内容 */} +
+ {isVideoFile(currentMedia.fileType) ? ( + + ) : ( + + )} +
+ + {/* 左右切换按钮 */} + {previewMediaList.length > 1 && ( + <> + + + + )} + + {/* 媒体信息 */} +
+
+ + {isVideoFile(currentMedia.fileType) ? ( + }>视频 + ) : ( + }>图片 + )} + + {currentMedia.shootTime && ( + + 拍摄时间: {formatTime(currentMedia.shootTime)} + + )} +
+
+ + {/* 缩略图列表 */} + {previewMediaList.length > 1 && ( +
+ {previewMediaList.map((media, index) => ( +
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) ? ( +
+ +
+ ) : ( + {`媒体${index + )} +
+ ))} +
+ )} +
+ )} + ); }; diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx index 873ba17e..7af3ad9d 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/CesiumContainer.tsx @@ -395,8 +395,9 @@ const CesiumContainer: React.FC = (props) => { longitude: droneData.longitude, latitude: droneData.latitude, height: droneData.height, // 相对高度(相对于起飞点) - elevation: droneData.elevation, // 海拔高度 - altitude: droneData.height, // 3D地图显示用 + elevation: droneData.elevation, // 海拔高度(椭球高度) + // 3D地图显示用 height(相对高度),与航线的 height 对应 + altitude: droneData.height, heading: droneData.attitude_head, timestamp: Date.now(), }; @@ -407,7 +408,7 @@ const CesiumContainer: React.FC = (props) => { if (!viewerRef.current || !Cesium || !realtimePosition) return; if (!realtimePosition.longitude || !realtimePosition.latitude) return; - const droneHeight = realtimePosition.height ?? 50; + const droneHeight = realtimePosition.altitude ?? 50; viewerRef.current.camera.flyTo({ destination: Cesium.Cartesian3.fromDegrees( @@ -434,7 +435,7 @@ const CesiumContainer: React.FC = (props) => { const currentPos = { lon: realtimePosition.longitude, lat: realtimePosition.latitude, - height: realtimePosition.height ?? 0, + height: realtimePosition.altitude ?? 0, }; // 节流:1秒内且位置没变化则跳过 diff --git a/zlt-web/react-web-next/src/services/waylineRoute.ts b/zlt-web/react-web-next/src/services/waylineRoute.ts index 06a07c1b..5e6ae229 100644 --- a/zlt-web/react-web-next/src/services/waylineRoute.ts +++ b/zlt-web/react-web-next/src/services/waylineRoute.ts @@ -20,7 +20,9 @@ export interface WaypointVO { index: number; longitude: number; latitude: number; - height: number; + height: number; // 相对高度 + executeHeight?: number; // 执行高度 + ellipsoidHeight?: number; // 椭球高度(用于3D地图显示) speed?: number; headingAngle?: number; actions?: WaypointActionVO[];