feat: 通过接口获取机库和无人机数据

This commit is contained in:
2025-12-24 16:09:46 +08:00
parent c939713379
commit 68e2084f57
9 changed files with 953 additions and 375 deletions
@@ -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<DeviceAlarmResponse> subscribeOnce(
@GetMapping("/fire-alarm/{deviceSn}")
@Operation(summary = "一次性获取机库状态数据", description = "独立 WebSocket 连接获取 fire_alarm,用完即关,不影响其他业务")
public Result<SingleAlarmResponse> 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<DeviceAlarmResponse> subscribeOnceWithTimeout(
@GetMapping("/fire-alarm/{deviceSn}/timeout/{timeoutSeconds}")
@Operation(summary = "一次性获取机库状态数据(带超时)", description = "可自定义超时时间")
public Result<SingleAlarmResponse> 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<DeviceAlarmResponse> getFromCache(
@GetMapping("/msg-alarm/{deviceSn}")
@Operation(summary = "一次性获取无人机遥测数据", description = "独立 WebSocket 连接获取 msg_alarm,用完即关。注意:无人机需开机才有数据")
public Result<SingleAlarmResponse> 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<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.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<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());
}
}
@@ -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;
}
}
@@ -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<JSONObject> dataRef = new AtomicReference<>();
CountDownLatch dataLatch = new CountDownLatch(1);
log.info("设备 {} 状态检查: SSE引用计数={}, 已注册={}", deviceSn, sseRefCount, deviceAlreadyRegistered);
// 记录本次订阅新增的主题(用于清理时只取消自己订阅的)
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);
// 创建独立的 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<SubscriptionTopic> 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<JSONObject> 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;
}
}
@@ -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;
}
}
@@ -55,6 +55,12 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
*/
private final Set<String> subscribedTopics = new HashSet<>();
/**
* 主题对应的订阅ID:topic -> subscriptionId
* 订阅和取消订阅使用相同的ID,确保只取消自己的订阅
*/
private final ConcurrentHashMap<String, String> 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<String> 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("=== 结束 ===");
}
/**
* 设置命令管理器(延迟注入,避免循环依赖)