fix:无人船2
This commit is contained in:
@@ -88,7 +88,8 @@
|
||||
"Bash(find \"F:/project/go-fly-platform-services/zlt-web/react-web-next/src/services\" -type f \\\\\\( -name \"*.ts\" -o -name \"*.tsx\" \\\\\\) 2>/dev/null | grep -i order)",
|
||||
"Bash(ls /f/project/go-fly-platform-services/zlt-business/device-center/src/main/java/com/central/device/controller/*.java)",
|
||||
"Bash(ls /f/project/go-fly-platform-services/zlt-business/device-center/src/main/java/com/central/device/service/*.java)",
|
||||
"Bash(ls /f/project/go-fly-platform-services/zlt-business/device-center/src/main/java/com/central/device/entity/*.java)"
|
||||
"Bash(ls /f/project/go-fly-platform-services/zlt-business/device-center/src/main/java/com/central/device/entity/*.java)",
|
||||
"Bash(xargs wc:*)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
|
||||
+151
-160
@@ -1,38 +1,41 @@
|
||||
package com.central.device.boat.sse;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.central.device.boat.manager.BoatSubscriptionManager;
|
||||
import com.central.device.model.vo.BoatRealtimeVO;
|
||||
import com.central.device.service.IBoatTrackService;
|
||||
import com.central.device.sse.model.EmitterWrapper;
|
||||
import com.central.device.websocket.handler.DeviceMessageHandler;
|
||||
import com.central.device.websocket.manager.SubscriptionPoolService;
|
||||
import com.central.device.websocket.manager.SubscriptionPoolService.TopicType;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 无人船SSE发射器管理器
|
||||
* 管理无人船前端SSE连接、触发WebSocket订阅、推送设备实时数据
|
||||
* 无人船SSE发射器管理器(独立模块,不与无人机/机库混用)
|
||||
*
|
||||
* 数据流:
|
||||
* JetLinks IoT → JetLinksWebSocketClient → DeviceMessageHandler
|
||||
* → msgAlarmCallback → BoatSseEmitterManager.sendBoatDataUpdate() → SSE客户端
|
||||
* 职责:
|
||||
* 1. 管理所有无人船SSE连接(admin + client)
|
||||
* 2. 按设备SN引用计数,懒加载/卸载 JetLinks WebSocket 订阅
|
||||
* 3. 接收 DeviceMessageHandler 的 boatFireAlarm 回调,转换并推送 boat-telemetry 事件
|
||||
*
|
||||
* 复用组件:
|
||||
* - BoatSubscriptionManager: WebSocket主题订阅/取消
|
||||
* - SubscriptionPoolService: Redis订阅池(多客户端隔离)
|
||||
* - DeviceMessageHandler: 注册回调接收IoT消息
|
||||
* - EmitterWrapper: SSE连接包装器
|
||||
* 数据流:
|
||||
* JetLinks fire_alarm → DeviceMessageHandler.handleDeviceStateEvent()
|
||||
* → navMode 检测 → boatFireAlarmCallback
|
||||
* → handleBoatFireAlarm() → sendBoatDataUpdate() → SSE 客户端
|
||||
*
|
||||
* @author dzc
|
||||
* @date 2026-04-07
|
||||
@@ -48,26 +51,32 @@ public class BoatSseEmitterManager {
|
||||
private DeviceMessageHandler messageHandler;
|
||||
|
||||
@Autowired
|
||||
private SubscriptionPoolService subscriptionPoolService;
|
||||
private IBoatTrackService boatTrackService;
|
||||
|
||||
/** SSE连接池: sessionId -> EmitterWrapper */
|
||||
/** SSE连接池: sessionId → EmitterWrapper */
|
||||
private final ConcurrentHashMap<String, EmitterWrapper> emitters = new ConcurrentHashMap<>();
|
||||
|
||||
/** 设备订阅本地引用计数: deviceSn -> count */
|
||||
/** 设备引用计数: deviceSn → 当前连接数(归零时取消订阅) */
|
||||
private final ConcurrentHashMap<String, Integer> deviceRefCount = new ConcurrentHashMap<>();
|
||||
|
||||
private ScheduledExecutorService heartbeatExecutor;
|
||||
private ScheduledExecutorService cleanupExecutor;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
startHeartbeat();
|
||||
startOrphanCleanup();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
if (heartbeatExecutor != null) {
|
||||
heartbeatExecutor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 连接管理 ====================
|
||||
|
||||
/**
|
||||
* 添加无人船SSE连接
|
||||
* 创建SSE连接 + 触发WebSocket订阅 + Redis订阅池 + 注册消息回调
|
||||
*/
|
||||
public SseEmitter addEmitter(String sessionId, String deviceSn, String tenantId) {
|
||||
// 移除重复连接
|
||||
@@ -76,8 +85,7 @@ public class BoatSseEmitterManager {
|
||||
removeEmitter(sessionId, deviceSn);
|
||||
}
|
||||
|
||||
// 创建SseEmitter(5分钟超时,配合心跳续期)
|
||||
SseEmitter emitter = new SseEmitter(5 * 60 * 1000L);
|
||||
SseEmitter emitter = new SseEmitter(0L);
|
||||
|
||||
emitter.onCompletion(() -> {
|
||||
log.info("[无人船SSE] 连接完成: session={}, deviceSn={}", sessionId, deviceSn);
|
||||
@@ -93,13 +101,9 @@ public class BoatSseEmitterManager {
|
||||
removeEmitter(sessionId, deviceSn);
|
||||
});
|
||||
|
||||
// 保存连接
|
||||
EmitterWrapper wrapper = new EmitterWrapper(emitter, 0L, tenantId, sessionId, deviceSn);
|
||||
emitters.put(sessionId, wrapper);
|
||||
|
||||
log.info("[无人船SSE] 新增连接: session={}, deviceSn={}, 当前连接数: {}",
|
||||
sessionId, deviceSn, emitters.size());
|
||||
|
||||
// 发送连接确认
|
||||
try {
|
||||
emitter.send(SseEmitter.event()
|
||||
@@ -109,37 +113,26 @@ public class BoatSseEmitterManager {
|
||||
log.error("[无人船SSE] 发送连接确认失败: session={}", sessionId, e);
|
||||
}
|
||||
|
||||
// 增加本地引用计数
|
||||
// 引用计数 +1,首次订阅时触发 WebSocket 订阅 + 注册回调
|
||||
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
|
||||
|
||||
// Redis订阅池: 添加 msg_alarm, online, offline 订阅
|
||||
boolean isFirstMsgAlarm = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
|
||||
boolean isFirstOnline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.ONLINE);
|
||||
boolean isFirstOffline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.OFFLINE);
|
||||
|
||||
// 首次订阅时触发WebSocket订阅
|
||||
if (isFirstOnline || isFirstOffline || isFirstMsgAlarm) {
|
||||
log.info("[无人船SSE] 设备 {} 首次订阅,触发WebSocket懒加载", deviceSn);
|
||||
boatSubscriptionManager.subscribeBoatDevice(deviceSn, tenantId);
|
||||
if (refCount == 1) {
|
||||
log.info("[无人船SSE] 设备 {} 首次订阅,触发 WebSocket 订阅", deviceSn);
|
||||
try {
|
||||
boatSubscriptionManager.subscribeBoatDevice(deviceSn, tenantId);
|
||||
messageHandler.registerBoatFireAlarmCallback(deviceSn, (sn, data) -> handleBoatFireAlarm(sn, data));
|
||||
} catch (Exception e) {
|
||||
log.error("[无人船SSE] 设备 {} WebSocket 订阅失败,SSE连接已建立但暂无数据: {}", deviceSn, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
if (isFirstMsgAlarm) {
|
||||
log.info("[无人船SSE] 设备 {} 遥测数据首次订阅,订阅msg_alarm并注册回调", deviceSn);
|
||||
boatSubscriptionManager.subscribeBoatTelemetry(deviceSn);
|
||||
|
||||
// 注册 DeviceMessageHandler 的 msgAlarm 回调
|
||||
messageHandler.registerMsgAlarmCallback(deviceSn, (sn, data) -> {
|
||||
sendBoatDataUpdate(sn, data);
|
||||
});
|
||||
} else {
|
||||
log.info("[无人船SSE] 设备 {} 已有其他订阅者,复用WebSocket订阅, 本地引用: {}", deviceSn, refCount);
|
||||
}
|
||||
log.info("[无人船SSE] 新增连接: session={}, deviceSn={}, 设备引用={}, 总连接数={}",
|
||||
sessionId, deviceSn, refCount, emitters.size());
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除SSE连接(减少引用计数,必要时取消订阅)
|
||||
* 移除SSE连接
|
||||
*/
|
||||
private void removeEmitter(String sessionId, String deviceSn) {
|
||||
EmitterWrapper wrapper = emitters.remove(sessionId);
|
||||
@@ -149,39 +142,23 @@ public class BoatSseEmitterManager {
|
||||
|
||||
try {
|
||||
wrapper.getEmitter().complete();
|
||||
} catch (Exception e) {
|
||||
log.debug("[无人船SSE] 完成连接失败(可能已关闭): session={}", sessionId);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
log.info("[无人船SSE] 移除连接: session={}, deviceSn={}, 剩余连接数: {}",
|
||||
sessionId, deviceSn, emitters.size());
|
||||
|
||||
// 减少本地引用计数
|
||||
deviceRefCount.compute(deviceSn, (k, v) -> {
|
||||
// 引用计数 -1,归零时取消 WebSocket 订阅 + 移除回调
|
||||
Integer remaining = deviceRefCount.compute(deviceSn, (k, v) -> {
|
||||
if (v == null || v <= 1) return null;
|
||||
return v - 1;
|
||||
});
|
||||
|
||||
// Redis订阅池: 移除订阅
|
||||
boolean isLastMsgAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
|
||||
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
|
||||
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
|
||||
|
||||
// 最后一个msg_alarm订阅者离开 → 取消遥测订阅 + 移除回调
|
||||
if (isLastMsgAlarm) {
|
||||
log.info("[无人船SSE] 设备 {} 最后一个订阅者离开,取消遥测订阅", deviceSn);
|
||||
boatSubscriptionManager.unsubscribeBoatTelemetry(deviceSn);
|
||||
messageHandler.removeMsgAlarmCallback(deviceSn);
|
||||
if (remaining == null) {
|
||||
log.info("[无人船SSE] 设备 {} 最后一个订阅者离开,取消 WebSocket 订阅", deviceSn);
|
||||
messageHandler.removeBoatFireAlarmCallback(deviceSn);
|
||||
boatSubscriptionManager.unsubscribeBoatDevice(deviceSn);
|
||||
}
|
||||
|
||||
// 所有基础主题订阅者都离开 → 取消设备订阅
|
||||
if (isLastOnline && isLastOffline) {
|
||||
boolean hasMsgAlarm = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM);
|
||||
if (!hasMsgAlarm) {
|
||||
log.info("[无人船SSE] 设备 {} 所有订阅者离开,取消设备订阅", deviceSn);
|
||||
boatSubscriptionManager.unsubscribeBoatDevice(deviceSn);
|
||||
}
|
||||
}
|
||||
log.info("[无人船SSE] 移除连接: session={}, deviceSn={}, 剩余连接数={}",
|
||||
sessionId, deviceSn, emitters.size());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,14 +172,95 @@ public class BoatSseEmitterManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ==================== 数据处理 ====================
|
||||
|
||||
/**
|
||||
* 推送无人船数据到所有匹配 deviceSn 的SSE连接
|
||||
* 处理无人船 fire_alarm 回调
|
||||
*/
|
||||
public void sendBoatDataUpdate(String deviceSn, JSONObject data) {
|
||||
if (data == null) {
|
||||
private void handleBoatFireAlarm(String deviceSn, JSONObject rawData) {
|
||||
JSONObject boatData = rawData.getJSONObject("boatData");
|
||||
if (boatData == null || boatData.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Long timestamp = rawData.getLong("timestamp");
|
||||
|
||||
// log.info("[无人船SSE] 收到设备遥测: deviceSn={}, lng={}, lat={}, speed={}, heading={}, battery={}, status={}",
|
||||
// deviceSn,
|
||||
// boatData.getDouble("longitude"),
|
||||
// boatData.getDouble("latitude"),
|
||||
// boatData.getDouble("speed"),
|
||||
// boatData.getDouble("heading"),
|
||||
// boatData.getInteger("battery"),
|
||||
// boatData.getString("deviceStatus"));
|
||||
|
||||
// 转换为前端 BoatTelemetryData 格式并推送 SSE
|
||||
JSONObject telemetry = toFrontendJson(deviceSn, boatData, timestamp);
|
||||
sendBoatDataUpdate(deviceSn, telemetry);
|
||||
|
||||
// 更新实时缓存
|
||||
BoatRealtimeVO vo = toRealtimeVO(deviceSn, boatData, timestamp);
|
||||
boatTrackService.pushTelemetryData(deviceSn, vo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设备上报字段 → 前端 BoatTelemetryData JSON
|
||||
*/
|
||||
private JSONObject toFrontendJson(String deviceSn, JSONObject boatData, Long timestamp) {
|
||||
JSONObject t = new JSONObject();
|
||||
t.put("deviceSn", deviceSn);
|
||||
t.put("longitude", boatData.getDouble("longitude"));
|
||||
t.put("latitude", boatData.getDouble("latitude"));
|
||||
t.put("heading", boatData.getDouble("heading"));
|
||||
t.put("speed", boatData.getDouble("speed"));
|
||||
t.put("battery", boatData.getInteger("battery"));
|
||||
t.put("status", boatData.getString("deviceStatus"));
|
||||
t.put("online", true);
|
||||
|
||||
String signal = boatData.getString("signal");
|
||||
t.put("signalStrength", "5G".equals(signal) ? 95 : "4G".equals(signal) ? 75 : 0);
|
||||
|
||||
t.put("recordTime", timestamp != null
|
||||
? Instant.ofEpochMilli(timestamp).toString()
|
||||
: Instant.now().toString());
|
||||
|
||||
Integer wp = boatData.getInteger("waypointIndex");
|
||||
if (wp != null && wp >= 0) {
|
||||
t.put("currentWaypointIndex", wp);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设备上报字段 → BoatRealtimeVO(供缓存/持久化)
|
||||
*/
|
||||
private BoatRealtimeVO toRealtimeVO(String deviceSn, JSONObject boatData, Long timestamp) {
|
||||
BoatRealtimeVO vo = new BoatRealtimeVO();
|
||||
vo.setDeviceSn(deviceSn);
|
||||
vo.setLongitude(boatData.getBigDecimal("longitude"));
|
||||
vo.setLatitude(boatData.getBigDecimal("latitude"));
|
||||
vo.setSpeed(boatData.getBigDecimal("speed"));
|
||||
vo.setHeading(boatData.getBigDecimal("heading"));
|
||||
vo.setBatteryPercent(boatData.getInteger("battery"));
|
||||
vo.setStatus(boatData.getString("deviceStatus"));
|
||||
vo.setOnline(true);
|
||||
|
||||
Integer wp = boatData.getInteger("waypointIndex");
|
||||
if (wp != null && wp >= 0) {
|
||||
vo.setNearestWaypointIndex(wp);
|
||||
}
|
||||
|
||||
vo.setRecordTime(timestamp != null
|
||||
? LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault())
|
||||
: LocalDateTime.now());
|
||||
return vo;
|
||||
}
|
||||
|
||||
// ==================== SSE 推送 ====================
|
||||
|
||||
/**
|
||||
* 推送数据到所有匹配 deviceSn 的 SSE 连接
|
||||
*/
|
||||
private void sendBoatDataUpdate(String deviceSn, JSONObject data) {
|
||||
List<String> deadEmitters = new ArrayList<>();
|
||||
|
||||
emitters.forEach((sessionId, wrapper) -> {
|
||||
@@ -210,115 +268,48 @@ public class BoatSseEmitterManager {
|
||||
try {
|
||||
wrapper.getEmitter().send(SseEmitter.event()
|
||||
.name("boat-telemetry")
|
||||
.data(data.toJSONString())
|
||||
.id("boat-" + System.currentTimeMillis()));
|
||||
.data(data.toJSONString()));
|
||||
} catch (Exception e) {
|
||||
log.warn("[无人船SSE] 推送数据失败: session={}, error={}", sessionId, e.getMessage());
|
||||
log.warn("[无人船SSE] 推送失败: session={}, error={}", sessionId, e.getMessage());
|
||||
deadEmitters.add(sessionId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
deadEmitters.forEach(sessionId -> {
|
||||
EmitterWrapper wrapper = emitters.get(sessionId);
|
||||
if (wrapper != null) {
|
||||
removeEmitter(sessionId, wrapper.getDeviceSn());
|
||||
}
|
||||
deadEmitters.forEach(sid -> {
|
||||
EmitterWrapper w = emitters.get(sid);
|
||||
if (w != null) removeEmitter(sid, w.getDeviceSn());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 心跳(15秒间隔,检测断连)
|
||||
*/
|
||||
// ==================== 心跳 ====================
|
||||
|
||||
private void startHeartbeat() {
|
||||
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
heartbeatExecutor.scheduleAtFixedRate(() -> {
|
||||
if (emitters.isEmpty()) return;
|
||||
|
||||
List<String> deadEmitters = new ArrayList<>();
|
||||
|
||||
List<String> dead = new ArrayList<>();
|
||||
emitters.forEach((sessionId, wrapper) -> {
|
||||
try {
|
||||
wrapper.getEmitter().send(SseEmitter.event()
|
||||
.name("heartbeat")
|
||||
.data("ping"));
|
||||
.name("heartbeat").data("ping"));
|
||||
} catch (Exception e) {
|
||||
log.warn("[无人船SSE] 心跳失败: session={}", sessionId);
|
||||
deadEmitters.add(sessionId);
|
||||
dead.add(sessionId);
|
||||
}
|
||||
});
|
||||
|
||||
if (!deadEmitters.isEmpty()) {
|
||||
log.info("[无人船SSE] 心跳检测到 {} 个断连,清理", deadEmitters.size());
|
||||
deadEmitters.forEach(sessionId -> {
|
||||
EmitterWrapper wrapper = emitters.get(sessionId);
|
||||
if (wrapper != null) {
|
||||
removeEmitter(sessionId, wrapper.getDeviceSn());
|
||||
}
|
||||
if (!dead.isEmpty()) {
|
||||
log.info("[无人船SSE] 心跳检测到 {} 个断连", dead.size());
|
||||
dead.forEach(sid -> {
|
||||
EmitterWrapper w = emitters.get(sid);
|
||||
if (w != null) removeEmitter(sid, w.getDeviceSn());
|
||||
});
|
||||
}
|
||||
}, 15000, 15000, TimeUnit.MILLISECONDS);
|
||||
|
||||
log.info("[无人船SSE] 心跳已启动,间隔: 15秒");
|
||||
}, 15, 15, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 孤儿订阅清理(30秒间隔)
|
||||
* 检查Redis中记录的session是否还有对应的SSE连接
|
||||
*/
|
||||
private void startOrphanCleanup() {
|
||||
cleanupExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
cleanupExecutor.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
java.util.Set<String> activeSessionIds = new java.util.HashSet<>(emitters.keySet());
|
||||
java.util.Set<String> allRedisSessionIds = subscriptionPoolService.getAllSessionIds();
|
||||
|
||||
if (allRedisSessionIds.isEmpty()) return;
|
||||
|
||||
int cleanedCount = 0;
|
||||
for (String sessionId : allRedisSessionIds) {
|
||||
// 只清理无人船的session(boat_前缀)
|
||||
if (!sessionId.startsWith("boat_")) continue;
|
||||
if (activeSessionIds.contains(sessionId)) continue;
|
||||
|
||||
log.info("[无人船SSE] 发现孤儿订阅: sessionId={}", sessionId);
|
||||
|
||||
java.util.List<SubscriptionPoolService.DeviceTopicPair> toUnsubscribe =
|
||||
subscriptionPoolService.removeAllSubscriptions(sessionId);
|
||||
|
||||
for (SubscriptionPoolService.DeviceTopicPair pair : toUnsubscribe) {
|
||||
String deviceSn = pair.getDeviceSn();
|
||||
TopicType topicType = pair.getTopicType();
|
||||
|
||||
if (topicType == TopicType.MSG_ALARM) {
|
||||
if (!subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM)) {
|
||||
boatSubscriptionManager.unsubscribeBoatTelemetry(deviceSn);
|
||||
messageHandler.removeMsgAlarmCallback(deviceSn);
|
||||
}
|
||||
} else if (topicType == TopicType.ONLINE || topicType == TopicType.OFFLINE) {
|
||||
boolean hasAny = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM)
|
||||
|| subscriptionPoolService.hasSubscribers(deviceSn, TopicType.ONLINE)
|
||||
|| subscriptionPoolService.hasSubscribers(deviceSn, TopicType.OFFLINE);
|
||||
if (!hasAny) {
|
||||
boatSubscriptionManager.unsubscribeBoatDevice(deviceSn);
|
||||
}
|
||||
}
|
||||
}
|
||||
cleanedCount++;
|
||||
}
|
||||
|
||||
if (cleanedCount > 0) {
|
||||
log.info("[无人船SSE] 孤儿清理完成: 清理 {} 个session", cleanedCount);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("[无人船SSE] 孤儿清理失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}, 30000, 30000, TimeUnit.MILLISECONDS);
|
||||
|
||||
log.info("[无人船SSE] 孤儿清理已启动,间隔: 30秒");
|
||||
}
|
||||
|
||||
/** 获取连接数 */
|
||||
/** 获取当前连接数 */
|
||||
public int getConnectionCount() {
|
||||
return emitters.size();
|
||||
}
|
||||
|
||||
+17
-74
@@ -1,8 +1,6 @@
|
||||
package com.central.device.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.central.device.model.vo.BoatRealtimeVO;
|
||||
import com.central.device.service.IBoatTrackService;
|
||||
import com.central.device.boat.sse.BoatSseEmitterManager;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -13,15 +11,16 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 客户端SSE遥测数据控制器
|
||||
* Gateway放行 /client/**,无需认证
|
||||
*
|
||||
* 数据流:
|
||||
* 客户端连接 → BoatSseEmitterManager(管理订阅+推送)→ fire_alarm → SSE boat-telemetry 事件
|
||||
*
|
||||
* @author dzc
|
||||
* @date 2026-03-11
|
||||
*/
|
||||
@@ -32,9 +31,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
@RequiredArgsConstructor
|
||||
public class ClientSseController {
|
||||
|
||||
private final IBoatTrackService boatTrackService;
|
||||
|
||||
private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
|
||||
private final BoatSseEmitterManager boatSseEmitterManager;
|
||||
|
||||
@Operation(summary = "客户端订阅设备遥测数据")
|
||||
@GetMapping(value = "/telemetry/{deviceSn}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
@@ -51,45 +48,17 @@ public class ClientSseController {
|
||||
connectionId = "client_" + UUID.randomUUID().toString() + "_" + deviceSn;
|
||||
}
|
||||
|
||||
// 移除已有连接
|
||||
if (emitters.containsKey(connectionId)) {
|
||||
removeConnection(connectionId, deviceSn);
|
||||
}
|
||||
|
||||
// 创建SSE连接(永不超时)
|
||||
SseEmitter emitter = new SseEmitter(0L);
|
||||
emitters.put(connectionId, emitter);
|
||||
|
||||
// 注册遥测回调
|
||||
boatTrackService.registerTelemetryCallback(deviceSn, connectionId, (data) -> {
|
||||
sendTelemetryData(connectionId, data);
|
||||
});
|
||||
|
||||
emitter.onCompletion(() -> {
|
||||
log.info("[ClientSSE] 连接完成: connectionId={}, deviceSn={}", connectionId, deviceSn);
|
||||
removeConnection(connectionId, deviceSn);
|
||||
});
|
||||
emitter.onTimeout(() -> {
|
||||
log.info("[ClientSSE] 连接超时: connectionId={}, deviceSn={}", connectionId, deviceSn);
|
||||
removeConnection(connectionId, deviceSn);
|
||||
});
|
||||
emitter.onError(e -> {
|
||||
log.warn("[ClientSSE] 连接错误: connectionId={}, error={}", connectionId, e.getMessage());
|
||||
removeConnection(connectionId, deviceSn);
|
||||
});
|
||||
|
||||
// 发送初始连接事件
|
||||
try {
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("connected")
|
||||
.data("{\"connectionId\":\"" + connectionId + "\",\"deviceSn\":\"" + deviceSn + "\"}"));
|
||||
} catch (IOException e) {
|
||||
log.error("[ClientSSE] 发送初始事件失败: {}", e.getMessage());
|
||||
removeConnection(connectionId, deviceSn);
|
||||
}
|
||||
|
||||
log.info("[ClientSSE] 客户端订阅遥测: connectionId={}, deviceSn={}", connectionId, deviceSn);
|
||||
return ResponseEntity.ok().body(emitter);
|
||||
|
||||
// 委托给 BoatSseEmitterManager 管理连接和订阅
|
||||
SseEmitter emitter = boatSseEmitterManager.addEmitter(connectionId, deviceSn, null);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header("Cache-Control", "no-cache, no-transform")
|
||||
.header("Connection", "keep-alive")
|
||||
.header("X-Accel-Buffering", "no")
|
||||
.contentType(MediaType.TEXT_EVENT_STREAM)
|
||||
.body(emitter);
|
||||
}
|
||||
|
||||
@Operation(summary = "客户端断开SSE连接")
|
||||
@@ -99,7 +68,7 @@ public class ClientSseController {
|
||||
@RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) {
|
||||
if (clientSessionId != null) {
|
||||
String connectionId = "client_" + clientSessionId + "_" + deviceSn;
|
||||
removeConnection(connectionId, deviceSn);
|
||||
boatSseEmitterManager.removeEmitterBySessionId(connectionId, deviceSn);
|
||||
}
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -112,34 +81,8 @@ public class ClientSseController {
|
||||
String sessionId = body != null ? body.get("sessionId") : null;
|
||||
if (sessionId != null) {
|
||||
String connectionId = "client_" + sessionId + "_" + deviceSn;
|
||||
removeConnection(connectionId, deviceSn);
|
||||
boatSseEmitterManager.removeEmitterBySessionId(connectionId, deviceSn);
|
||||
}
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
private void sendTelemetryData(String connectionId, BoatRealtimeVO data) {
|
||||
SseEmitter emitter = emitters.get(connectionId);
|
||||
if (emitter == null) return;
|
||||
try {
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("boat-telemetry")
|
||||
.data(JSON.toJSONString(data)));
|
||||
} catch (IOException e) {
|
||||
log.warn("[ClientSSE] 发送遥测数据失败: connectionId={}, error={}", connectionId, e.getMessage());
|
||||
removeConnection(connectionId, data.getDeviceSn());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean removeConnection(String connectionId, String deviceSn) {
|
||||
SseEmitter emitter = emitters.remove(connectionId);
|
||||
if (emitter != null) {
|
||||
try {
|
||||
emitter.complete();
|
||||
} catch (Exception e) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
boatTrackService.unregisterTelemetryCallback(deviceSn, connectionId);
|
||||
return emitter != null;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -324,7 +324,7 @@ public class ThreeDModelFileServiceImpl extends SuperServiceImpl<ThreeDModelFile
|
||||
detailMapper.insert(detail);
|
||||
|
||||
// 如果是tileset.json,更新主记录
|
||||
if (filePath.endsWith("tileset.json") && !filePath.contains("/Block/")) {
|
||||
if (filePath.endsWith("tileset.json") && !filePath.matches(".*(/Block[^/]*/|/Block[^/]*$).*")) {
|
||||
model.setTilesetPath(objectKey);
|
||||
model.setTilesetUrl(fileUrl);
|
||||
updateById(model);
|
||||
|
||||
+48
@@ -66,6 +66,12 @@ public class DeviceMessageHandler {
|
||||
*/
|
||||
private final ConcurrentHashMap<String, BiConsumer<String, JSONObject>> msgAlarmCallbacks = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 无人船 fire_alarm 回调监听器(独立于机库 fireAlarmCallbacks)
|
||||
* deviceSn -> callback
|
||||
*/
|
||||
private final ConcurrentHashMap<String, BiConsumer<String, JSONObject>> boatFireAlarmCallbacks = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 最近取消订阅的设备列表(用于抑制取消订阅后短时间内收到的消息警告)
|
||||
* deviceSn -> 取消订阅的时间戳
|
||||
@@ -292,6 +298,27 @@ public class DeviceMessageHandler {
|
||||
|
||||
if (newDockData != null && !newDockData.isEmpty()) {
|
||||
|
||||
// ====== 无人船 fire_alarm 快速通道 ======
|
||||
// 无人船上报的 fire_alarm 含 navMode 字段,与无人机/机库的三类合并格式完全不同
|
||||
// 走独立的 boatFireAlarmCallbacks,不碰机库的 fireAlarmCallbacks
|
||||
if (newDockData.containsKey("navMode")) {
|
||||
JSONObject rawData = new JSONObject();
|
||||
rawData.put("eventType", "boat_state");
|
||||
rawData.put("messageId", messageId);
|
||||
rawData.put("timestamp", timestamp);
|
||||
rawData.put("boatData", newDockData);
|
||||
|
||||
BiConsumer<String, JSONObject> boatCallback = boatFireAlarmCallbacks.get(deviceSn);
|
||||
if (boatCallback != null) {
|
||||
try {
|
||||
boatCallback.accept(deviceSn, rawData);
|
||||
} catch (Exception callbackEx) {
|
||||
log.error("无人船 fire_alarm 回调执行失败: deviceSn={}, error={}", deviceSn, callbackEx.getMessage());
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 判断数据类型并更新对应缓存
|
||||
int dataType = identifyDataType(newDockData);
|
||||
|
||||
@@ -512,6 +539,27 @@ public class DeviceMessageHandler {
|
||||
log.debug("移除 msg_alarm 回调: deviceSn={}", deviceSn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册无人船 fire_alarm 回调(独立于机库 fireAlarmCallbacks)
|
||||
*
|
||||
* @param deviceSn 设备SN
|
||||
* @param callback 回调函数
|
||||
*/
|
||||
public void registerBoatFireAlarmCallback(String deviceSn, BiConsumer<String, JSONObject> callback) {
|
||||
boatFireAlarmCallbacks.put(deviceSn, callback);
|
||||
log.info("注册无人船 fire_alarm 回调: deviceSn={}", deviceSn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除无人船 fire_alarm 回调
|
||||
*
|
||||
* @param deviceSn 设备SN
|
||||
*/
|
||||
public void removeBoatFireAlarmCallback(String deviceSn) {
|
||||
boatFireAlarmCallbacks.remove(deviceSn);
|
||||
log.info("移除无人船 fire_alarm 回调: deviceSn={}", deviceSn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存的 msg_alarm 数据
|
||||
*
|
||||
|
||||
+1
-1
@@ -168,7 +168,7 @@ public class ModelFileUploadService {
|
||||
// 如果有tileset.json,返回其URL
|
||||
for (Map<String, Object> item : successList) {
|
||||
String key = (String) item.get("objectKey");
|
||||
if (key != null && key.endsWith("tileset.json") && !key.contains("/Block/")) {
|
||||
if (key != null && key.endsWith("tileset.json") && !key.matches(".*(/Block[^/]*/|/Block[^/]*$).*")) {
|
||||
result.put("tilesetUrl", item.get("cdnUrl"));
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -125,7 +125,7 @@ const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
||||
const hasTileset = items.some(
|
||||
(item) =>
|
||||
item.relativePath.endsWith('tileset.json') &&
|
||||
!item.relativePath.includes('/Block/'),
|
||||
!/\/Block[^/]*\//.test(item.relativePath),
|
||||
);
|
||||
if (!hasTileset) {
|
||||
message.warning('未检测到根目录下的tileset.json文件,请确保选择了正确的3D Tiles文件夹');
|
||||
|
||||
@@ -134,10 +134,10 @@ const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnec
|
||||
step={0.5}
|
||||
value={targetSpeed}
|
||||
onChange={setTargetSpeed}
|
||||
tooltip={{ formatter: (v) => `${v} km/h` }}
|
||||
tooltip={{ formatter: (v) => `${v} m/s` }}
|
||||
/>
|
||||
</div>
|
||||
<span className={styles.speedValue}>{targetSpeed} km/h</span>
|
||||
<span className={styles.speedValue}>{speed.toFixed(1)} m/s</span>
|
||||
</div>
|
||||
|
||||
{/* 紧急停靠 */}
|
||||
@@ -160,7 +160,7 @@ const RightPanel: React.FC<RightPanelProps> = ({ deviceInfo, boatData, sseConnec
|
||||
<div className={styles.dataCardHeader}>船舶状态</div>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.dataLabel}>速度</span>
|
||||
<span className={styles.dataValue}>{speed.toFixed(1)} km/h</span>
|
||||
<span className={styles.dataValue}>{speed.toFixed(1)} m/s</span>
|
||||
</div>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.dataLabel}>方向</span>
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface UseClientSSEReturn {
|
||||
boatData: BoatTelemetryData | null;
|
||||
sseConnected: boolean;
|
||||
loading: boolean;
|
||||
deviceOffline: boolean;
|
||||
connectSSE: (deviceSn: string) => Promise<void>;
|
||||
disconnectSSE: (deviceSn?: string) => Promise<void>;
|
||||
}
|
||||
@@ -19,6 +20,7 @@ export const useClientSSE = (): UseClientSSEReturn => {
|
||||
const [boatData, setBoatData] = useState<BoatTelemetryData | null>(null);
|
||||
const [sseConnected, setSSEConnected] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [deviceOffline, setDeviceOffline] = useState(false);
|
||||
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const currentDeviceSnRef = useRef<string>('');
|
||||
@@ -71,6 +73,7 @@ export const useClientSSE = (): UseClientSSEReturn => {
|
||||
|
||||
setSSEConnected(false);
|
||||
setBoatData(null);
|
||||
setDeviceOffline(false);
|
||||
currentDeviceSnRef.current = '';
|
||||
}, []);
|
||||
|
||||
@@ -124,6 +127,7 @@ export const useClientSSE = (): UseClientSSEReturn => {
|
||||
|
||||
setSSEConnected(true);
|
||||
setLoading(false);
|
||||
setDeviceOffline(false);
|
||||
reconnectAttemptsRef.current = 0;
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
@@ -149,6 +153,7 @@ export const useClientSSE = (): UseClientSSEReturn => {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
setSSEConnected(false);
|
||||
setDeviceOffline(true);
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
@@ -180,6 +185,7 @@ export const useClientSSE = (): UseClientSSEReturn => {
|
||||
if (error?.name === 'AbortError') return;
|
||||
console.error('[ClientSSE] 读取流错误:', error);
|
||||
setSSEConnected(false);
|
||||
setDeviceOffline(true);
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
@@ -191,6 +197,7 @@ export const useClientSSE = (): UseClientSSEReturn => {
|
||||
if (error?.name === 'AbortError') return;
|
||||
console.error('[ClientSSE] 连接失败:', error);
|
||||
setSSEConnected(false);
|
||||
setDeviceOffline(true);
|
||||
setLoading(false);
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
@@ -224,5 +231,5 @@ export const useClientSSE = (): UseClientSSEReturn => {
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { boatData, sseConnected, loading, connectSSE, disconnectSSE };
|
||||
return { boatData, sseConnected, loading, deviceOffline, connectSSE, disconnectSSE };
|
||||
};
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
/**
|
||||
* 模拟遥测数据生成
|
||||
* SSE 未连接时自动生成模拟船只遥测数据
|
||||
*/
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import type { BoatTelemetryData } from '@/types/boatRoute';
|
||||
|
||||
/** 生成一帧模拟遥测 */
|
||||
const createMockTelemetry = (
|
||||
deviceSn: string,
|
||||
prevData?: BoatTelemetryData | null,
|
||||
initLon?: number,
|
||||
initLat?: number,
|
||||
): BoatTelemetryData => {
|
||||
const baseLon = prevData?.longitude ?? initLon ?? 108.366;
|
||||
const baseLat = prevData?.latitude ?? initLat ?? 22.817;
|
||||
const baseHeading = prevData?.heading ?? 45;
|
||||
|
||||
const headingRad = (baseHeading + (Math.random() - 0.5) * 10) * Math.PI / 180;
|
||||
const moveDistance = 0.00002 + Math.random() * 0.00003;
|
||||
const newLon = baseLon + Math.cos(headingRad) * moveDistance;
|
||||
const newLat = baseLat + Math.sin(headingRad) * moveDistance;
|
||||
const newHeading = ((baseHeading + (Math.random() - 0.5) * 10) + 360) % 360;
|
||||
|
||||
return {
|
||||
deviceSn,
|
||||
longitude: newLon,
|
||||
latitude: newLat,
|
||||
heading: Number(newHeading.toFixed(1)),
|
||||
speed: Number((1.5 + Math.random() * 2).toFixed(1)),
|
||||
battery: Math.max(20, (prevData?.battery ?? 85) - Math.random() * 0.1),
|
||||
signalStrength: 60 + Math.floor(Math.random() * 30),
|
||||
status: '巡航中',
|
||||
recordTime: new Date().toISOString(),
|
||||
taskId: undefined,
|
||||
currentWaypointIndex: undefined,
|
||||
};
|
||||
};
|
||||
|
||||
interface UseMockTelemetryReturn {
|
||||
/** 合并后的遥测数据(SSE 优先,回退到模拟) */
|
||||
boatData: BoatTelemetryData | null;
|
||||
/** 模型中心位���回调,���于重置模拟数据起点 */
|
||||
handleModelCenter: (lon: number, lat: number) => void;
|
||||
}
|
||||
|
||||
export function useMockTelemetry(
|
||||
deviceSn: string,
|
||||
sseBoatData: BoatTelemetryData | null,
|
||||
): UseMockTelemetryReturn {
|
||||
const [mockBoatData, setMockBoatData] = useState<BoatTelemetryData | null>(null);
|
||||
const mockTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const mockDataRef = useRef<BoatTelemetryData | null>(null);
|
||||
const modelCenterRef = useRef<{ lon: number; lat: number } | null>(null);
|
||||
|
||||
const handleModelCenter = useCallback((lon: number, lat: number) => {
|
||||
modelCenterRef.current = { lon, lat };
|
||||
if (mockDataRef.current) {
|
||||
const newData = {
|
||||
...mockDataRef.current,
|
||||
longitude: lon + (Math.random() - 0.5) * 0.001,
|
||||
latitude: lat + (Math.random() - 0.5) * 0.001,
|
||||
};
|
||||
mockDataRef.current = newData;
|
||||
setMockBoatData(newData);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// 有真实 SSE 数据时停止模拟
|
||||
if (sseBoatData) {
|
||||
if (mockTimerRef.current) {
|
||||
clearInterval(mockTimerRef.current);
|
||||
mockTimerRef.current = null;
|
||||
}
|
||||
setMockBoatData(null);
|
||||
mockDataRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// 无真实数据且无模拟定时器,启动模拟
|
||||
if (!mockTimerRef.current && deviceSn) {
|
||||
const center = modelCenterRef.current;
|
||||
const firstData = createMockTelemetry(deviceSn, null, center?.lon, center?.lat);
|
||||
mockDataRef.current = firstData;
|
||||
setMockBoatData(firstData);
|
||||
|
||||
mockTimerRef.current = setInterval(() => {
|
||||
const center2 = modelCenterRef.current;
|
||||
const newData = createMockTelemetry(deviceSn, mockDataRef.current, center2?.lon, center2?.lat);
|
||||
mockDataRef.current = newData;
|
||||
setMockBoatData(newData);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (mockTimerRef.current) {
|
||||
clearInterval(mockTimerRef.current);
|
||||
mockTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [sseBoatData, deviceSn]);
|
||||
|
||||
const boatData = sseBoatData || mockBoatData;
|
||||
|
||||
return { boatData, handleModelCenter };
|
||||
}
|
||||
@@ -144,6 +144,58 @@
|
||||
50% { opacity: 0.5; }
|
||||
}
|
||||
|
||||
/* ========== 设备离线遮罩 ========== */
|
||||
.offlineOverlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 200;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(4, 10, 20, 0.75);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
}
|
||||
|
||||
.offlineCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 40px 48px;
|
||||
background: linear-gradient(135deg, rgba(14, 30, 56, 0.95), rgba(8, 18, 36, 0.98));
|
||||
border: 1px solid rgba(255, 80, 80, 0.3);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.04);
|
||||
text-align: center;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.offlineIcon {
|
||||
font-size: 40px;
|
||||
color: #ff4d4f;
|
||||
margin-bottom: 16px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.offlineTitle {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
letter-spacing: 1px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.offlineDesc {
|
||||
font-size: 13px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.offlineSn {
|
||||
color: @accent-cyan;
|
||||
font-family: 'Rajdhani', monospace;
|
||||
}
|
||||
|
||||
/* ========== 滚动条 ========== */
|
||||
.leftPanel::-webkit-scrollbar,
|
||||
.rightPanel::-webkit-scrollbar {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { ConfigProvider, Button } from 'antd';
|
||||
import { LogoutOutlined } from '@ant-design/icons';
|
||||
import { ConfigProvider, Button, Spin } from 'antd';
|
||||
import { LogoutOutlined, DisconnectOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import { darkTheme } from '@/theme';
|
||||
import LeftPanel from './components/LeftPanel';
|
||||
import CenterView from './components/CenterView';
|
||||
@@ -11,22 +11,20 @@ import EmergencyButton from './components/EmergencyButton';
|
||||
import { useClientAuth } from './hooks/useClientAuth';
|
||||
import { useClientSSE } from './hooks/useClientSSE';
|
||||
import { useRouteData } from './hooks/useRouteData';
|
||||
import { useMockTelemetry } from './hooks/useMockTelemetry';
|
||||
import { useNavigationState } from './hooks/useNavigationState';
|
||||
import { useNavigationData } from './hooks/useNavigationData';
|
||||
import styles from './index.less';
|
||||
|
||||
const ClientPage: React.FC = () => {
|
||||
// ── 认证 ──
|
||||
const { boatData: sseBoatData, sseConnected, connectSSE, disconnectSSE } = useClientSSE();
|
||||
const { boatData: sseBoatData, sseConnected, loading: sseLoading, deviceOffline, connectSSE, disconnectSSE } = useClientSSE();
|
||||
const { deviceSn, deviceInfo, handleLogout } = useClientAuth(disconnectSSE);
|
||||
|
||||
// ── 航线数据 ──
|
||||
const { routes, routeWaypointsMap, selectedRouteId, setSelectedRouteId, routeLoading } =
|
||||
useRouteData(deviceSn);
|
||||
|
||||
// ── 模拟遥测 ──
|
||||
const { boatData, handleModelCenter } = useMockTelemetry(deviceSn, sseBoatData);
|
||||
const boatData = sseBoatData;
|
||||
|
||||
// ── 沉浸模式状态机 ──
|
||||
const {
|
||||
@@ -70,6 +68,32 @@ const ClientPage: React.FC = () => {
|
||||
return (
|
||||
<ConfigProvider theme={darkTheme}>
|
||||
<div className={`${styles.container} ${isImmersive ? styles.sailing : ''}`}>
|
||||
{/* 设备离线遮罩 */}
|
||||
{deviceOffline && !sseConnected && (
|
||||
<div className={styles.offlineOverlay}>
|
||||
<div className={styles.offlineCard}>
|
||||
<DisconnectOutlined className={styles.offlineIcon} />
|
||||
<div className={styles.offlineTitle}>设备不在线</div>
|
||||
<div className={styles.offlineDesc}>
|
||||
无法订阅设备 <span className={styles.offlineSn}>{deviceInfo.deviceName || deviceSn}</span> 的实时数据
|
||||
<br />
|
||||
{sseLoading ? '正在重新连接...' : '请检查设备是否已开机并接入网络'}
|
||||
</div>
|
||||
{sseLoading ? (
|
||||
<Spin size="small" style={{ marginTop: 16 }} />
|
||||
) : (
|
||||
<Button
|
||||
icon={<ReloadOutlined />}
|
||||
onClick={() => connectSSE(deviceSn)}
|
||||
style={{ marginTop: 16, borderColor: 'rgba(0,212,255,0.4)', color: '#00d4ff' }}
|
||||
ghost
|
||||
>
|
||||
重试连接
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* 左侧游览线路 */}
|
||||
<div className={styles.leftPanel}>
|
||||
<LeftPanel
|
||||
@@ -88,7 +112,6 @@ const ClientPage: React.FC = () => {
|
||||
routes={routes}
|
||||
selectedRouteId={selectedRouteId}
|
||||
boatData={boatData}
|
||||
onModelCenter={handleModelCenter}
|
||||
isSailing={isSailing}
|
||||
sailingLoading={sailingLoading}
|
||||
previewStopSignal={previewStopSignal}
|
||||
|
||||
Reference in New Issue
Block a user