feat: 3d控制指令

This commit is contained in:
2025-12-16 11:43:37 +08:00
parent 4921ab15ce
commit cb912a8c60
23 changed files with 1258 additions and 401 deletions
@@ -46,4 +46,8 @@ public class AgeDevice extends SuperEntity {
private String urlNormal;
private String urlSelect;
private String tenantId;
/**
* 视频流地址(完整WHEP URL,如:http://220.205.16.27:8024/rtc/v1/whep/?app=live&stream=49214ac552fa)
*/
private String videoStreamUrl;
}
@@ -150,4 +150,77 @@ public class DeviceStatusSseController {
return org.springframework.http.ResponseEntity.badRequest().body("取消订阅失败: " + e.getMessage());
}
}
/**
* 订阅无人机遥测数据SSE连接(独立连接)
* 前端建立独立的SSE连接,专门接收无人机遥测数据(msg_alarm)
* 与机库状态数据(fire_alarm)完全分离,互不干扰
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID(可选,从请求头获取,用于连接复用和清理)
* @return SSE连接
*/
@Operation(summary = "订阅无人机遥测数据SSE连接(独立连接)")
@GetMapping(value = "/drone-telemetry/{deviceSn}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public org.springframework.http.ResponseEntity<SseEmitter> subscribeDroneTelemetrySse(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "客户端会话ID(可选)")
@RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) {
String tenantId = LoginUserContextHolder.getCurrentTenantId() != null ? LoginUserContextHolder.getCurrentTenantId() : "1";
String username = LoginUserContextHolder.getUser() != null ? LoginUserContextHolder.getUser().getUsername() : "anonymous";
// 生成sessionId:如果前端提供了clientSessionId,则使用它;否则生成UUID
String sessionId;
if (clientSessionId != null && !clientSessionId.trim().isEmpty()) {
sessionId = "drone_" + clientSessionId + "_" + deviceSn;
log.info("客户端订阅无人机遥测数据SSE(复用会话): session={}, deviceSn={}, tenant={}, user={}",
sessionId, deviceSn, tenantId, username);
} else {
sessionId = "drone_" + java.util.UUID.randomUUID().toString() + "_" + deviceSn;
log.info("客户端订阅无人机遥测数据SSE(新会话): session={}, deviceSn={}, tenant={}, user={}",
sessionId, deviceSn, tenantId, username);
}
// 添加SSE连接(内部会触发WebSocket懒加载和设备订阅)
// 如果同sessionId已存在连接,会自动断开旧连接
SseEmitter emitter = sseEmitterManager.addDroneTelemetryEmitter(sessionId, deviceSn, tenantId);
// 设置响应头,禁用缓冲
return org.springframework.http.ResponseEntity.ok()
.header("Cache-Control", "no-cache, no-transform")
.header("Connection", "keep-alive")
.header("X-Accel-Buffering", "no")
.contentType(org.springframework.http.MediaType.TEXT_EVENT_STREAM)
.body(emitter);
}
/**
* 主动断开无人机遥测数据SSE连接
* 前端页面卸载时调用,确保后端资源及时释放
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID(必需)
* @return 断开结果
*/
@Operation(summary = "主动断开无人机遥测数据SSE连接")
@DeleteMapping("/drone-telemetry/{deviceSn}")
public org.springframework.http.ResponseEntity<String> disconnectDroneTelemetrySse(
@Parameter(description = "设备SN", required = true)
@PathVariable String deviceSn,
@Parameter(description = "客户端会话ID", required = true)
@RequestHeader(value = "X-Client-Session-Id") String clientSessionId) {
String sessionId = "drone_" + clientSessionId + "_" + deviceSn;
log.info("客户端主动断开无人机遥测数据SSE连接: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = sseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
if (success) {
return org.springframework.http.ResponseEntity.ok("无人机遥测数据连接已断开");
} else {
return org.springframework.http.ResponseEntity.ok("连接不存在或已断开");
}
}
}
@@ -5,6 +5,7 @@ import com.central.device.sse.model.EmitterWrapper;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.DeviceSubscriptionManager;
import com.central.device.websocket.model.DeviceRealtimeData;
import com.central.device.websocket.model.DroneRealtimeData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -27,7 +28,7 @@ import java.util.concurrent.TimeUnit;
* 2. WebSocket懒加载:只有前端调用时才连接
* 3. 引用计数:支持多个客户端订阅同一设备
*
* @author lishilin
* @author dzc
* @date 2025-01-19
*/
@Slf4j
@@ -105,8 +106,8 @@ public class SseEmitterManager {
});
// 保存连接(使用deviceSn作为scenicId字段,保持兼容性)
EmitterWrapper wrapper = new EmitterWrapper(emitter, 0L, tenantId, sessionId,deviceSn);
wrapper.setDeviceSn(deviceSn); // 扩展字段
EmitterWrapper wrapper = new EmitterWrapper(emitter, 0L, tenantId, sessionId, deviceSn);
wrapper.setIsDroneTelemetry(false); // 标记为机库状态数据连接
emitters.put(sessionId, wrapper);
log.info("新增SSE连接: session={}, deviceSn={}, tenant={}, 当前连接数: {}",
@@ -155,6 +156,9 @@ public class SseEmitterManager {
return;
}
// 记录连接类型(无人机还是机库)
boolean isDroneTelemetry = wrapper.getIsDroneTelemetry() != null && wrapper.getIsDroneTelemetry();
// 尝试完成emitter(优雅关闭)
try {
wrapper.getEmitter().complete();
@@ -162,8 +166,15 @@ public class SseEmitterManager {
log.debug("完成SSE连接失败(可能已关闭): session={}, error={}", sessionId, e.getMessage());
}
log.info("移除SSE连接: session={}, deviceSn={}, 剩余连接数: {}",
sessionId, deviceSn, emitters.size());
log.info("移除SSE连接: session={}, deviceSn={}, isDroneTelemetry={}, 剩余连接数: {}",
sessionId, deviceSn, isDroneTelemetry, emitters.size());
// 【关键】如果是无人机SSE连接,需要先取消 msg_alarm 订阅
// 无论引用计数是否归零,都要取消无人机遥测数据订阅
if (isDroneTelemetry) {
log.info("无人机SSE连接断开,取消 msg_alarm 订阅: deviceSn={}", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
}
// 减少设备引用计数
Integer refCount = deviceRefCount.compute(deviceSn, (k, v) -> {
@@ -173,9 +184,9 @@ public class SseEmitterManager {
return v - 1;
});
// 关键:如果引用计数归零,取消设备订阅
// 关键:如果引用计数归零,取消所有设备订阅(机库订阅)
if (refCount == null) {
log.info("设备 {} 引用计数归零,取消订阅", deviceSn);
log.info("设备 {} 引用计数归零,取消所有订阅", deviceSn);
deviceSubscriptionManager.unsubscribeDevice(deviceSn);
} else {
log.info("设备 {} 仍有 {} 个订阅,保持连接", deviceSn, refCount);
@@ -201,9 +212,10 @@ public class SseEmitterManager {
/**
* 推送设备数据更新(只推送给订阅该设备的连接)
* 注意:这个方法推送机库数据
*
* @param deviceSn 设备SN
* @param data 设备实时数据
* @param data 设备实时数据(机库数据)
*/
public void sendDeviceDataUpdate(String deviceSn, DeviceRealtimeData data) {
DeviceRealtimeDataDTO dto = convertToDTO(data);
@@ -213,35 +225,29 @@ public class SseEmitterManager {
}
/**
* 发送给指定设备的所有连接
* 发送给指定设备的机库SSE连接(不包括无人机SSE连接)
* 只推送给 isDroneTelemetry = false 的连接
*/
private void sendToDevice(String deviceSn, String eventName, Object data) {
List<String> deadEmitters = new ArrayList<>();
// log.info("准备推送到设备: deviceSn={}, 当前所有连接数: {}", deviceSn, emitters.size());
// 打印所有连接的 deviceSn,用于调试
emitters.values().forEach(wrapper -> {
log.info(" 连接详情: session={}, deviceSn={}", wrapper.getSessionId(), wrapper.getDeviceSn());
});
// 找到匹配的连接
// 找到匹配的机库连接(排除无人机连接)
List<EmitterWrapper> matchingEmitters = emitters.values().stream()
.filter(wrapper -> {
boolean match = deviceSn.equals(wrapper.getDeviceSn());
return match;
boolean matchDevice = deviceSn.equals(wrapper.getDeviceSn());
// 【关键】只推送给机库连接,排除无人机连接
boolean isDeviceConnection = wrapper.getIsDroneTelemetry() == null || !wrapper.getIsDroneTelemetry();
return matchDevice && isDeviceConnection;
})
.toList();
log.info("找到 {} 个匹配设备 {} 的SSE连接", matchingEmitters.size(), deviceSn);
log.debug("推送机库数据到设备 {} 的 {} 个SSE连接", deviceSn, matchingEmitters.size());
matchingEmitters.forEach(wrapper -> {
try {
wrapper.getEmitter().send(SseEmitter.event()
.name(eventName)
.data(data));
log.info("✅ SSE推送成功: session={}, event={}, deviceSn={} , data={}",
wrapper.getSessionId(), eventName, deviceSn, data);
} catch (Exception e) {
log.error("❌ SSE推送失败: session={}, event={}, error={}",
wrapper.getSessionId(), eventName, e.getMessage());
@@ -349,4 +355,179 @@ public class SseEmitterManager {
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
deviceSubscriptionManager.unsubscribeDroneTelemetry(deviceSn);
}
/**
* 添加无人机遥测数据SSE连接(独立连接)
* 专门用于接收无人机遥测数据(msg_alarm),与机库状态数据完全分离
*
* @param sessionId 会话ID(含设备SN)
* @param deviceSn 设备SN
* @param tenantId 租户ID
* @return SSE Emitter
*/
public SseEmitter addDroneTelemetryEmitter(String sessionId, String deviceSn, String tenantId) {
// 检查是否已存在相同sessionId的连接,如果存在则先移除(避免重复连接)
if (emitters.containsKey(sessionId)) {
log.warn("检测到重复的无人机SSE连接,sessionId={},先移除旧连接", sessionId);
removeEmitter(sessionId, deviceSn);
}
// 创建SseEmitter(超时时间5分钟,避免僵尸连接)
long timeoutMs = 5 * 60 * 1000L; // 5分钟
SseEmitter emitter = new SseEmitter(timeoutMs);
// 设置回调
emitter.onCompletion(() -> {
log.info("无人机SSE连接完成: session={}, deviceSn={}", sessionId, deviceSn);
removeEmitter(sessionId, deviceSn);
});
emitter.onTimeout(() -> {
log.warn("无人机SSE连接超时: session={}, deviceSn={}", sessionId, deviceSn);
removeEmitter(sessionId, deviceSn);
});
emitter.onError((ex) -> {
log.error("无人机SSE连接错误: session={}, deviceSn={}, error={}",
sessionId, deviceSn, ex.getMessage());
removeEmitter(sessionId, deviceSn);
});
// 保存连接
EmitterWrapper wrapper = new EmitterWrapper(emitter, 0L, tenantId, sessionId, deviceSn);
wrapper.setDeviceSn(deviceSn);
wrapper.setIsDroneTelemetry(true); // 标记为无人机遥测数据连接
emitters.put(sessionId, wrapper);
log.info("新增无人机SSE连接: session={}, deviceSn={}, isDroneTelemetry={}, tenant={}, 当前连接数: {}",
sessionId, deviceSn, wrapper.getIsDroneTelemetry(), tenantId, emitters.size());
// 立即发送连接确认消息,激活SSE流
try {
emitter.send(SseEmitter.event()
.name("connected")
.data("无人机SSE连接已建立"));
log.info("发送无人机连接确认消息成功: session={}", sessionId);
} catch (Exception e) {
log.error("发送无人机连接确认消息失败: session={}, error={}", sessionId, e.getMessage());
}
// 增加设备引用计数(无人机专用)
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
// 【关键修复】无论引用计数是多少,都需要订阅无人机遥测数据(msg_alarm)
// 因为机库订阅(addEmitter)只订阅了 fire_alarm,不包括 msg_alarm
// 所以这里需要额外订阅 msg_alarm 主题
log.info("设备 {} 订阅无人机遥测数据,当前引用计数: {}", deviceSn, refCount);
// 如果是首次订阅该设备(refCount == 1),需要先订阅基础主题
if (refCount == 1) {
log.info("设备 {} 首次订阅,触发WebSocket懒加载并订阅基础主题", deviceSn);
deviceSubscriptionManager.subscribeDevice(deviceSn, tenantId);
}
// 无论如何都要订阅无人机遥测数据主题(msg_alarm)
// 这是独立于机库订阅的,需要单独调用
log.info("设备 {} 订阅无人机遥测主题 msg_alarm", deviceSn);
deviceSubscriptionManager.subscribeDroneTelemetry(deviceSn);
// 立即推送一次当前无人机数据(如果存在)
com.central.device.websocket.model.DeviceRealtimeData currentData = messageHandler.getDeviceData(deviceSn);
if (currentData != null && currentData.getRawData() != null && currentData.getRawData().get("droneData") != null) {
log.info("推送设备 {} 的当前无人机数据到新连接", deviceSn);
// 注意:这里应该推送无人机数据,而不是机库数据
// 但由于我们刚刚修改了 handleMsgAlarmEvent 不再更新 DeviceRealtimeData
// 所以这里可能不会有 droneData 了
// 等待新的无人机消息到来
} else {
log.info("设备 {} 暂无无人机缓存数据,等待WebSocket消息", deviceSn);
}
return emitter;
}
/**
* 发送无人机数据更新到所有订阅该设备的无人机SSE连接(新版本,使用 DroneRealtimeData)
* 只发送给标记为无人机遥测数据的连接
*
* @param deviceSn 设备SN
* @param data 无人机实时数据
*/
public void sendDroneDataUpdate(String deviceSn, DroneRealtimeData data) {
if (data == null || data.getRawData() == null) {
log.warn("无人机数据为空,跳过推送: deviceSn={}", deviceSn);
return;
}
// 统计无人机SSE连接数
long droneConnectionCount = emitters.values().stream()
.filter(w -> deviceSn.equals(w.getDeviceSn()) && Boolean.TRUE.equals(w.getIsDroneTelemetry()))
.count();
log.info("【无人机数据推送】deviceSn={}, 无人机SSE连接数={}, 总连接数={}",
deviceSn, droneConnectionCount, emitters.size());
if (droneConnectionCount == 0) {
log.warn("【无人机数据推送】没有找到无人机SSE连接: deviceSn={}", deviceSn);
// 打印所有连接的详情
emitters.forEach((sid, w) -> {
log.info(" 连接详情: session={}, deviceSn={}, isDroneTelemetry={}",
sid, w.getDeviceSn(), w.getIsDroneTelemetry());
});
return;
}
// 只查找标记为无人机遥测数据的连接
emitters.forEach((sessionId, wrapper) -> {
if (deviceSn.equals(wrapper.getDeviceSn()) && Boolean.TRUE.equals(wrapper.getIsDroneTelemetry())) {
try {
// 创建专门用于无人机数据的事件
SseEmitter.SseEventBuilder event = SseEmitter.event()
.name("drone-data-update")
.data(data.toFrontendJson()) // 推送前端兼容的JSON
.id("drone-" + System.currentTimeMillis());
wrapper.getEmitter().send(event);
log.info("✅ 发送无人机数据更新成功: session={}, deviceSn={}", sessionId, deviceSn);
} catch (Exception e) {
log.warn("发送无人机数据更新失败,连接可能已关闭: session={}, deviceSn={}, error={}",
sessionId, deviceSn, e.getMessage());
// 不立即移除,等待心跳检测或回调处理
}
}
});
}
/**
* 发送无人机数据更新到所有订阅该设备的无人机SSE连接(旧版本,保持兼容)
* 只发送给标记为无人机遥测数据的连接
*
* @param deviceSn 设备SN
* @param data 设备实时数据
*/
public void sendDroneDataUpdate(String deviceSn, com.central.device.websocket.model.DeviceRealtimeData data) {
if (data == null || data.getRawData() == null || data.getRawData().get("droneData") == null) {
return;
}
// 只查找标记为无人机遥测数据的连接
emitters.forEach((sessionId, wrapper) -> {
if (deviceSn.equals(wrapper.getDeviceSn()) && wrapper.getIsDroneTelemetry()) {
try {
// 创建专门用于无人机数据的事件
SseEmitter.SseEventBuilder event = SseEmitter.event()
.name("drone-data-update")
.data(data.getRawData().get("droneData"))
.id("drone-" + System.currentTimeMillis());
wrapper.getEmitter().send(event);
log.debug("发送无人机数据更新到连接: session={}, deviceSn={}", sessionId, deviceSn);
} catch (Exception e) {
log.warn("发送无人机数据更新失败,连接可能已关闭: session={}, deviceSn={}, error={}",
sessionId, deviceSn, e.getMessage());
// 不立即移除,等待心跳检测或回调处理
}
}
});
}
}
@@ -37,4 +37,29 @@ public class EmitterWrapper {
* 设备SN(新增字段,v3.0)
*/
private String deviceSn;
/**
* 是否为无人机遥测数据连接(新增字段)
* true: 无人机遥测数据(msg_alarm)
* false: 机库状态数据(fire_alarm)
*/
private Boolean isDroneTelemetry = false;
/**
* 无参构造函数(Lombok兼容)
*/
public EmitterWrapper() {
}
/**
* 构造函数(兼容旧代码)
*/
public EmitterWrapper(SseEmitter emitter, Long scenicId, String tenantId, String sessionId, String deviceSn) {
this.emitter = emitter;
this.scenicId = scenicId;
this.tenantId = tenantId;
this.sessionId = sessionId;
this.deviceSn = deviceSn;
this.isDroneTelemetry = false;
}
}
@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.config.WebSocketProperties;
import com.central.device.websocket.handler.DeviceMessageHandler;
import com.central.device.websocket.manager.DeviceCommandManager;
import com.central.device.websocket.manager.TokenManager;
import com.central.device.websocket.model.SubscriptionMessage;
import com.central.device.websocket.model.SubscriptionTopic;
@@ -20,9 +21,11 @@ import javax.annotation.PreDestroy;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* JetLinks平台WebSocket客户端(全局单例)
@@ -44,13 +47,19 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
/**
* 命令管理器(延迟注入,避免循环依赖)
*/
private Object commandManager;
private DeviceCommandManager commandManager;
/**
* 当前订阅的主题列表
*/
private final Set<String> subscribedTopics = new HashSet<>();
/**
* 设备订阅计数:deviceSn -> 订阅次数
* 用于管理同一设备多个主题的订阅,避免过早断开连接
*/
private final ConcurrentHashMap<String, AtomicInteger> deviceSubscriptionCounts = new ConcurrentHashMap<>();
/**
* WebSocket会话
*/
@@ -147,9 +156,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
// 处理命令队列
if (commandManager != null) {
try {
commandManager.getClass()
.getMethod("onWebSocketReconnected")
.invoke(commandManager);
commandManager.onWebSocketReconnected();
} catch (Exception e) {
log.warn("调用命令管理器失败: {}", e.getMessage());
}
@@ -207,7 +214,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
String requestId = json.getString("id");
String deviceSn = extractDeviceSn(topic);
log.info("收到命令响应: topic={}, requestId={}, deviceSn={}", topic, requestId, deviceSn);
log.info("收到命令响应: topic={}, requestId={}, deviceSn={}, json={}", topic, requestId, deviceSn, json.toJSONString());
// 通知命令管理器处理响应
if (commandManager != null && requestId != null) {
@@ -231,6 +238,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
} else {
// 如果有 payload 但没有 success 字段,可能是成功的
success = true;
log.debug("命令响应没有success字段,默认视为成功: requestId={}", requestId);
}
} else {
// 没有 payload,检查顶层是否有 success
@@ -238,14 +246,14 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
message = json.getString("message");
}
log.info("命令响应解析: requestId={}, success={}, message={}", requestId, success, message);
log.info("命令响应解析结果: requestId={}, success={}, message={}", requestId, success, message);
commandManager.getClass()
.getMethod("handleCommandResponse", String.class, boolean.class, String.class)
.invoke(commandManager, requestId, success, message);
commandManager.handleCommandResponse(requestId, success, message);
} catch (Exception e) {
log.warn("调用命令管理器处理响应失败: {}", e.getMessage());
log.error("调用命令管理器处理响应失败: requestId={}, error={}", requestId, e.getMessage(), e);
}
} else {
log.warn("命令管理器未设置或requestId为空: commandManager={}, requestId={}", commandManager != null, requestId);
}
}
@@ -336,7 +344,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
messageHandler.handlePropertyReport(deviceSn, json.toJSONString());
} else if (topic.contains("/message/event/fire_alarm")) {
// 设备状态事件上报 - 使用专用处理方法
log.info("处理fire_alarm事件: deviceSn={}", deviceSn);
// log.info("处理fire_alarm事件: deviceSn={}", deviceSn);
messageHandler.handleDeviceStateEvent(deviceSn, json.toJSONString());
} else if (topic.contains("/message/event/msg_alarm")) {
// 无人机遥测数据事件 - 使用专用处理方法
@@ -442,10 +450,15 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
unsubscribeTopic(topic, deviceSn);
}
// 检查是否所有订阅都已取消,如果是则断开WebSocket连接以节省资源
if (subscribedTopics.isEmpty()) {
log.info("所有设备订阅已取消,自动断开WebSocket连接以节省资源");
// 检查是否所有设备的订阅都已取消,如果是则断开WebSocket连接以节省资源
// 注意:这里检查deviceSubscriptionCounts而不是subscribedTopics
// 因为一个设备可能有多个主题订阅(fire_alarm + msg_alarm)
if (deviceSubscriptionCounts.isEmpty()) {
log.info("所有设备的所有订阅已取消,自动断开WebSocket连接以节省资源");
closeConnection();
} else {
log.info("仍有{}个设备有活跃订阅,保持WebSocket连接: {}",
deviceSubscriptionCounts.size(), deviceSubscriptionCounts.keySet());
}
}
@@ -465,7 +478,12 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
send(JSON.toJSONString(message));
subscribedTopics.add(topic);
log.info("发送订阅消息: topic={}, id={}, message={}", topic, message.getId(), JSON.toJSONString(message));
// 更新设备订阅计数
deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet();
log.info("发送订阅消息: topic={}, id={}, message={}, 设备{}订阅计数: {}",
topic, message.getId(), JSON.toJSONString(message),
deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
}
/**
@@ -490,8 +508,19 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
send(JSON.toJSONString(message));
subscribedTopics.remove(topic);
log.info("取消订阅主题: topic={}, id={}, 剩余订阅数: {}, 剩余主题: {}",
topic, message.getId(), subscribedTopics.size(), subscribedTopics);
// 更新设备订阅计数
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn);
if (count != null) {
int newCount = count.decrementAndGet();
if (newCount <= 0) {
deviceSubscriptionCounts.remove(deviceSn);
log.info("设备{}所有订阅已取消,从订阅计数中移除", deviceSn);
}
}
log.info("取消订阅主题: topic={}, id={}, 剩余订阅数: {}, 剩余主题: {}, 设备{}剩余订阅计数: {}",
topic, message.getId(), subscribedTopics.size(), subscribedTopics,
deviceSn, count != null ? count.get() : 0);
}
/**
@@ -503,10 +532,12 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
return;
}
log.info("重新订阅 {} 个主题", subscribedTopics.size());
log.info("重新订阅 {} 个主题,涉及 {} 个设备", subscribedTopics.size(), deviceSubscriptionCounts.size());
Set<String> topics = new HashSet<>(subscribedTopics);
subscribedTopics.clear();
// 清空设备订阅计数,重新订阅时会重新计算
deviceSubscriptionCounts.clear();
// 按设备分组重新订阅(订阅所有标准主题)
Set<String> deviceSns = new HashSet<>();
@@ -675,10 +706,40 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
return subscribedTopics.size();
}
/**
* 获取设备订阅计数
*/
public int getDeviceSubscriptionCount(String deviceSn) {
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn);
return count != null ? count.get() : 0;
}
/**
* 获取所有有活跃订阅的设备
*/
public Set<String> getActiveDevices() {
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("=== 结束 ===");
}
/**
* 设置命令管理器(延迟注入,避免循环依赖)
*/
public void setCommandManager(Object commandManager) {
public void setCommandManager(DeviceCommandManager commandManager) {
this.commandManager = commandManager;
}
@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.central.device.service.DeviceAlarmDataService;
import com.central.device.websocket.model.DeviceRealtimeData;
import com.central.device.websocket.model.DroneRealtimeData;
import com.central.device.websocket.model.GpsData;
import com.central.device.websocket.model.message.DeviceStateEventMessage;
import com.central.device.websocket.model.message.PropertyReportMessage;
@@ -322,7 +323,7 @@ public class DeviceMessageHandler {
}
// 三种数据都齐全了,合并并推送
log.info("设备 {} 三种数据已齐全,开始合并推送", deviceSn);
// log.info("设备 {} 三种数据已齐全,开始合并推送", deviceSn);
// 合并三种缓存数据
JSONObject mergedDockData = mergeAllCaches(cache);
@@ -423,29 +424,23 @@ public class DeviceMessageHandler {
}
}
// 如果设备已在 deviceDataMap 中注册,更新其数据并推送SSE
DeviceRealtimeData data = deviceDataMap.get(deviceSn);
if (data != null) {
data.setOnline(true);
data.setLastMessageTime(timestamp != null ? timestamp : System.currentTimeMillis());
// 创建无人机数据对象(与机库数据完全分离)
DroneRealtimeData droneRealtimeData = DroneRealtimeData.fromRawData(deviceSn, droneData);
// 从 droneData 提取关键字段更新到 DeviceRealtimeData
extractDroneKeyFields(data, droneData);
// 将 msg_alarm 数据合并到 rawData 中
JSONObject rawData = data.getRawData();
if (rawData == null) {
rawData = new JSONObject();
// 推送到无人机专用的SSE连接
if (sseEmitterManager != null) {
try {
log.info("【handleMsgAlarmEvent】准备推送无人机数据到SSE: deviceSn={}", deviceSn);
sseEmitterManager.getClass()
.getMethod("sendDroneDataUpdate", String.class, DroneRealtimeData.class)
.invoke(sseEmitterManager, deviceSn, droneRealtimeData);
log.info("【handleMsgAlarmEvent】已推送无人机数据到专用SSE连接: deviceSn={}", deviceSn);
} catch (Exception e) {
log.error("【handleMsgAlarmEvent】调用无人机SSE推送失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
}
// 只保留 droneData,不再重复存储 msgAlarmData
// 前端直接从 rawData.droneData 读取无人机遥测数据
rawData.put("droneData", droneData);
data.setRawData(rawData);
// 推送到前端(通过SSE)
pushDeviceDataUpdate(data);
} else {
log.warn("【handleMsgAlarmEvent】sseEmitterManager 为 null,无法推送无人机数据");
}
} catch (Exception e) {
log.error("解析 msg_alarm 消息失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
}
@@ -400,13 +400,13 @@ public class DeviceCommandManager {
if (success) {
command.setStatus(CommandStatus.SUCCESS);
log.info("命令执行成功: commandId={}, device={}",
commandId, command.getDeviceSn());
log.info("命令执行成功: commandId={}, device={}, type={}",
commandId, command.getDeviceSn(), command.getCommandType());
} else {
command.setStatus(CommandStatus.FAILED);
command.setErrorMsg(message);
log.error("命令执行失败: commandId={}, device={}, error={}",
commandId, command.getDeviceSn(), message);
log.error("命令执行失败: commandId={}, device={}, type={}, error={}",
commandId, command.getDeviceSn(), command.getCommandType(), message);
}
}
@@ -317,19 +317,31 @@ public class DeviceSubscriptionManager {
return;
}
log.info("订阅无人机遥测数据: deviceSn={}", deviceSn);
log.info("【调试】开始订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
// 打印当前WebSocket连接状态
boolean isConnected = jetLinksWebSocketClient.isConnected();
log.info("【调试】WebSocket连接状态: {}", isConnected ? "已连接" : "未连接");
// 打印当前设备订阅计数
int deviceCount = jetLinksWebSocketClient.getDeviceSubscriptionCount(deviceSn);
log.info("【调试】设备{}当前订阅计数: {}", deviceSn, deviceCount);
// 只订阅 msg_alarm 主题
jetLinksWebSocketClient.subscribeDevice(
deviceSn,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
log.info("无人机遥测数据 {} 订阅成功", deviceSn);
log.info("【调试】无人机遥测数据 {} 订阅成功", deviceSn);
// 打印订阅后的状态
int newDeviceCount = jetLinksWebSocketClient.getDeviceSubscriptionCount(deviceSn);
log.info("【调试】设备{}订阅后计数: {}", deviceSn, newDeviceCount);
} catch (Exception e) {
log.error("订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
log.error("【调试】订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
@@ -345,19 +357,31 @@ public class DeviceSubscriptionManager {
return;
}
log.info("取消订阅无人机遥测数据: deviceSn={}", deviceSn);
log.info("【调试】开始取消订阅无人机遥测数据: deviceSn={}", deviceSn);
try {
// 打印取消订阅前的状态
int deviceCount = jetLinksWebSocketClient.getDeviceSubscriptionCount(deviceSn);
log.info("【调试】设备{}取消订阅前计数: {}", deviceSn, deviceCount);
// 只取消 msg_alarm 主题
jetLinksWebSocketClient.unsubscribeDevice(
deviceSn,
SubscriptionTopic.EVENT_MSG_ALARM // 无人机遥测数据
);
log.info("无人机遥测数据 {} 订阅已取消", deviceSn);
log.info("【调试】无人机遥测数据 {} 订阅已取消", deviceSn);
// 打印取消订阅后的状态
int newDeviceCount = jetLinksWebSocketClient.getDeviceSubscriptionCount(deviceSn);
log.info("【调试】设备{}取消订阅后计数: {}", deviceSn, newDeviceCount);
// 打印当前所有活跃设备
java.util.Set<String> activeDevices = jetLinksWebSocketClient.getActiveDevices();
log.info("【调试】当前活跃设备: {}", activeDevices);
} catch (Exception e) {
log.error("取消订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
log.error("【调试】取消订阅无人机遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
}