fix:无人船

This commit is contained in:
2026-04-07 22:21:37 +08:00
parent 982e4364d5
commit a338cf7d02
112 changed files with 8255 additions and 611 deletions
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.central.device.entity;
package com.central.device.boat.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
@@ -0,0 +1,369 @@
package com.central.device.boat.manager;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.config.WebSocketProperties;
import com.central.device.websocket.model.CommandStatus;
import com.central.device.websocket.model.DeviceCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 无人船命令管理器
* 负责无人船命令队列管理、发送、重试、超时处理
* 复用全局JetLinksWebSocketClient发送命令,使用 ship 产品标识
*
* @author dzc
* @date 2026-04-07
*/
@Slf4j
@Component
public class BoatCommandManager {
@Autowired
private WebSocketProperties properties;
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
/** 无人船产品标识 */
public static final String PRODUCT_BOAT = "ship";
/** 待发送命令队列: deviceSn -> Queue<DeviceCommand> */
private final ConcurrentHashMap<String, ConcurrentLinkedQueue<DeviceCommand>> commandQueues = new ConcurrentHashMap<>();
/** 已发送等待响应的命令: commandId -> DeviceCommand */
private final ConcurrentHashMap<String, DeviceCommand> pendingCommands = new ConcurrentHashMap<>();
/** 延迟执行器(用于重试) */
private final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(2);
/**
* 发送命令
*
* @param deviceSn 设备SN
* @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo)
* @param params 命令参数
* @return 命令ID
*/
public String sendCommand(String deviceSn, String commandType, JSONObject params) {
DeviceCommand command = DeviceCommand.builder()
.commandId(UUID.randomUUID().toString())
.deviceSn(deviceSn)
.commandType(commandType)
.params(params != null ? params : new JSONObject())
.status(CommandStatus.PENDING)
.createTime(System.currentTimeMillis())
.sendTime(0)
.expireTime(System.currentTimeMillis() + properties.getCommand().getDefaultTimeout())
.retryCount(0)
.maxRetry(properties.getCommand().getMaxRetry())
.build();
log.info("[无人船] 创建命令: commandId={}, device={}, type={}",
command.getCommandId(), deviceSn, commandType);
// 检查全局WebSocket连接状态,未连接则自动连接
if (!jetLinksWebSocketClient.isConnected()) {
log.info("[无人船] WebSocket未连接,自动建立连接: commandId={}", command.getCommandId());
jetLinksWebSocketClient.connect();
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
try {
Thread.sleep(100);
waitCount++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("[无人船] 等待连接被中断");
addToQueue(command);
return command.getCommandId();
}
}
}
if (jetLinksWebSocketClient.isConnected()) {
sendCommandImmediately(command);
} else {
log.warn("[无人船] WebSocket连接失败,命令加入队列: commandId={}, device={}",
command.getCommandId(), deviceSn);
addToQueue(command);
}
return command.getCommandId();
}
/**
* 立即发送命令(通过全局WebSocket客户端)
* topic 使用 /device-message-sender/ship/{deviceSn}
*/
private void sendCommandImmediately(DeviceCommand command) {
try {
command.setStatus(CommandStatus.SENDING);
command.setSendTime(System.currentTimeMillis());
// 构造指令内容 (properties)
JSONObject cmdProperties = buildCommandProperties(command);
// 构造 parameter
JSONObject parameter = new JSONObject();
parameter.put("messageType", "WRITE_PROPERTY");
parameter.put("properties", cmdProperties);
JSONObject headers = new JSONObject();
headers.put("async", false);
parameter.put("headers", headers);
// 构造完整消息(使用 ship 产品标识)
JSONObject message = new JSONObject();
message.put("type", "sub");
message.put("topic", "/device-message-sender/" + PRODUCT_BOAT + "/" + command.getDeviceSn());
message.put("parameter", parameter);
message.put("id", command.getCommandId());
String messageJson = message.toJSONString();
log.info("[无人船] 发送命令消息: {}", messageJson);
jetLinksWebSocketClient.send(messageJson);
command.setStatus(CommandStatus.SENT);
pendingCommands.put(command.getCommandId(), command);
log.info("[无人船] 命令发送成功: commandId={}, device={}, type={}",
command.getCommandId(), command.getDeviceSn(), command.getCommandType());
} catch (Exception e) {
log.error("[无人船] 命令发送失败: commandId={}, error={}", command.getCommandId(), e.getMessage());
command.setStatus(CommandStatus.FAILED);
command.setErrorMsg(e.getMessage());
retryCommand(command);
}
}
/**
* 根据命令类型构造 properties 内容(无人船专用)
*
* 与无人机的关键区别:
* 1. 无人船的暂停/恢复/终止都需要 order_no 参数
* 2. 无人船的开始任务需要 order_no、wayline_link_url、file_md5、stream_urls
*/
private JSONObject buildCommandProperties(DeviceCommand command) {
JSONObject cmdProperties = new JSONObject();
JSONObject data = new JSONObject();
String method = command.getCommandType();
JSONObject params = command.getParams();
switch (method) {
case "flighttask_prepare":
// 开始任务
data.put("order_no", params.getString("order_no"));
data.put("wayline_link_url", params.getString("wayline_link_url"));
data.put("file_md5", params.getString("file_md5"));
if (params.containsKey("stream_urls")) {
data.put("stream_urls", params.get("stream_urls"));
}
break;
case "flighttask_pause":
// 暂停任务
data.put("order_no", params.getString("order_no"));
break;
case "flighttask_recovery":
// 恢复任务
data.put("order_no", params.getString("order_no"));
break;
case "flighttask_undo":
// 终止任务
if (params.containsKey("order_no")) {
data.put("order_no", params.getString("order_no"));
}
break;
default:
data = params;
break;
}
cmdProperties.put("method", method);
cmdProperties.put("data", data);
return cmdProperties;
}
/**
* 加入队列
*/
private void addToQueue(DeviceCommand command) {
ConcurrentLinkedQueue<DeviceCommand> queue = commandQueues
.computeIfAbsent(command.getDeviceSn(), k -> new ConcurrentLinkedQueue<>());
if (queue.size() >= properties.getCommand().getQueueMaxSize()) {
log.error("[无人船] 设备 {} 命令队列已满({}), 拒绝新命令: {}",
command.getDeviceSn(), properties.getCommand().getQueueMaxSize(), command.getCommandId());
command.setStatus(CommandStatus.FAILED);
command.setErrorMsg("命令队列已满");
return;
}
queue.offer(command);
log.info("[无人船] 命令已加入队列: commandId={}, device={}, 队列长度={}",
command.getCommandId(), command.getDeviceSn(), queue.size());
}
/**
* WebSocket重连后处理所有队列
* 由外部在 WebSocket 重连成功后调用
*/
public void onWebSocketReconnected() {
log.info("[无人船] WebSocket重连成功,开始处理命令队列");
if (commandQueues.isEmpty()) {
return;
}
int totalProcessed = 0;
int totalExpired = 0;
for (String deviceSn : commandQueues.keySet()) {
ConcurrentLinkedQueue<DeviceCommand> queue = commandQueues.get(deviceSn);
if (queue == null || queue.isEmpty()) {
continue;
}
while (!queue.isEmpty()) {
DeviceCommand command = queue.poll();
if (System.currentTimeMillis() > command.getExpireTime()) {
command.setStatus(CommandStatus.EXPIRED);
totalExpired++;
log.warn("[无人船] 命令已过期: commandId={}, device={}", command.getCommandId(), deviceSn);
continue;
}
sendCommandImmediately(command);
totalProcessed++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
if (totalProcessed > 0 || totalExpired > 0) {
log.info("[无人船] 命令队列处理完成: 重发={}, 过期={}", totalProcessed, totalExpired);
}
}
/**
* 命令重试
*/
private void retryCommand(DeviceCommand command) {
if (command.getRetryCount() >= command.getMaxRetry()) {
log.error("[无人船] 命令重试次数超限: commandId={}, device={}",
command.getCommandId(), command.getDeviceSn());
command.setStatus(CommandStatus.FAILED);
return;
}
command.setRetryCount(command.getRetryCount() + 1);
log.info("[无人船] 命令准备重试 ({}/{}): commandId={}",
command.getRetryCount(), command.getMaxRetry(), command.getCommandId());
long delay = (long) Math.pow(2, command.getRetryCount()) * properties.getCommand().getRetryDelayBase();
retryExecutor.schedule(() -> {
if (jetLinksWebSocketClient.isConnected()) {
sendCommandImmediately(command);
} else {
addToQueue(command);
}
}, delay, TimeUnit.MILLISECONDS);
}
/**
* 接收设备命令响应
*/
public void handleCommandResponse(String commandId, boolean success, String message) {
DeviceCommand command = pendingCommands.remove(commandId);
if (command == null) {
return;
}
if (success) {
command.setStatus(CommandStatus.SUCCESS);
log.info("[无人船] 命令执行成功: commandId={}, device={}, type={}",
commandId, command.getDeviceSn(), command.getCommandType());
} else {
command.setStatus(CommandStatus.FAILED);
command.setErrorMsg(message);
log.error("[无人船] 命令执行失败: commandId={}, device={}, type={}, error={}",
commandId, command.getDeviceSn(), command.getCommandType(), message);
}
}
/**
* 定时清理过期命令
*/
@Scheduled(fixedRateString = "${device.websocket.command.cleanup-interval:10000}")
public void cleanupExpiredCommands() {
long now = System.currentTimeMillis();
int queueExpiredCount = 0;
AtomicInteger pendingTimeoutCount = new AtomicInteger(0);
for (ConcurrentLinkedQueue<DeviceCommand> queue : commandQueues.values()) {
for (DeviceCommand command : queue) {
if (now > command.getExpireTime()) {
if (queue.remove(command)) {
command.setStatus(CommandStatus.EXPIRED);
queueExpiredCount++;
}
}
}
}
pendingCommands.entrySet().removeIf(entry -> {
DeviceCommand command = entry.getValue();
if (now > command.getExpireTime()) {
command.setStatus(CommandStatus.TIMEOUT);
pendingTimeoutCount.incrementAndGet();
return true;
}
return false;
});
if (queueExpiredCount > 0 || pendingTimeoutCount.get() > 0) {
log.info("[无人船] 清理过期命令: 队列过期={}, 响应超时={}", queueExpiredCount, pendingTimeoutCount.get());
}
}
/**
* 查询命令状态
*/
public CommandStatus getCommandStatus(String commandId) {
DeviceCommand command = pendingCommands.get(commandId);
if (command != null) {
return command.getStatus();
}
for (ConcurrentLinkedQueue<DeviceCommand> queue : commandQueues.values()) {
Optional<DeviceCommand> found = queue.stream()
.filter(cmd -> cmd.getCommandId().equals(commandId))
.findFirst();
if (found.isPresent()) {
return found.get().getStatus();
}
}
return null;
}
}
@@ -0,0 +1,158 @@
package com.central.device.boat.manager;
import com.central.device.boat.model.BoatSubscriptionTopic;
import com.central.device.websocket.client.JetLinksWebSocketClient;
import com.central.device.websocket.handler.DeviceMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 无人船设备订阅管理器
* 管理无人船设备的 WebSocket 主题订阅/取消订阅
* 使用 BoatSubscriptionTopic(ship 产品),通过 JetLinksWebSocketClient 的 subscribeRawTopic/unsubscribeRawTopic 方法
* 确保 topic 被纳入 subscribedTopics 跟踪,消息路由不被过滤
*
* @author dzc
* @date 2026-04-07
*/
@Slf4j
@Component
public class BoatSubscriptionManager {
@Autowired
private JetLinksWebSocketClient jetLinksWebSocketClient;
@Autowired
private DeviceMessageHandler messageHandler;
/**
* 订阅无人船设备(上线、离线、状态事件)
*
* @param deviceSn 设备SN
* @param tenantId 租户ID
*/
public void subscribeBoatDevice(String deviceSn, String tenantId) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("[无人船] 设备SN为空,无法订阅");
return;
}
log.info("[无人船] 订阅设备: deviceSn={}, tenantId={}", deviceSn, tenantId);
try {
ensureConnected();
messageHandler.addDevice(deviceSn, 0L, tenantId);
jetLinksWebSocketClient.subscribeRawTopic(
BoatSubscriptionTopic.BOAT_ONLINE.getTopic(deviceSn), deviceSn);
jetLinksWebSocketClient.subscribeRawTopic(
BoatSubscriptionTopic.BOAT_OFFLINE.getTopic(deviceSn), deviceSn);
jetLinksWebSocketClient.subscribeRawTopic(
BoatSubscriptionTopic.BOAT_EVENT_FIRE_ALARM.getTopic(deviceSn), deviceSn);
log.info("[无人船] 设备 {} 订阅成功", deviceSn);
} catch (Exception e) {
log.error("[无人船] 设备 {} 订阅失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 订阅无人船遥测数据(进入操控台时调用)
*
* @param deviceSn 设备SN
*/
public void subscribeBoatTelemetry(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
log.warn("[无人船] 设备SN为空,无法订阅遥测");
return;
}
log.info("[无人船] 订阅遥测数据: deviceSn={}", deviceSn);
try {
ensureConnected();
jetLinksWebSocketClient.subscribeRawTopic(
BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM.getTopic(deviceSn), deviceSn);
log.info("[无人船] 遥测数据 {} 订阅成功", deviceSn);
} catch (Exception e) {
log.error("[无人船] 订阅遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 取消订阅无人船设备
*
* @param deviceSn 设备SN
*/
public void unsubscribeBoatDevice(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
return;
}
log.info("[无人船] 取消订阅设备: deviceSn={}", deviceSn);
try {
jetLinksWebSocketClient.unsubscribeRawTopic(
BoatSubscriptionTopic.BOAT_ONLINE.getTopic(deviceSn), deviceSn);
jetLinksWebSocketClient.unsubscribeRawTopic(
BoatSubscriptionTopic.BOAT_OFFLINE.getTopic(deviceSn), deviceSn);
jetLinksWebSocketClient.unsubscribeRawTopic(
BoatSubscriptionTopic.BOAT_EVENT_FIRE_ALARM.getTopic(deviceSn), deviceSn);
jetLinksWebSocketClient.unsubscribeRawTopic(
BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM.getTopic(deviceSn), deviceSn);
messageHandler.removeDevice(deviceSn);
log.info("[无人船] 设备 {} 订阅已取消", deviceSn);
} catch (Exception e) {
log.error("[无人船] 取消订阅设备 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 取消订阅无人船遥测数据(退出操控台时调用)
*
* @param deviceSn 设备SN
*/
public void unsubscribeBoatTelemetry(String deviceSn) {
if (deviceSn == null || deviceSn.trim().isEmpty()) {
return;
}
log.info("[无人船] 取消订阅遥测数据: deviceSn={}", deviceSn);
try {
jetLinksWebSocketClient.unsubscribeRawTopic(
BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM.getTopic(deviceSn), deviceSn);
log.info("[无人船] 遥测数据 {} 订阅已取消", deviceSn);
} catch (Exception e) {
log.error("[无人船] 取消订阅遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
}
}
/**
* 确保 WebSocket 已连接
*/
private void ensureConnected() {
if (!jetLinksWebSocketClient.isConnected()) {
log.info("[无人船] WebSocket未连接,自动建立连接");
jetLinksWebSocketClient.connect();
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
try {
Thread.sleep(100);
waitCount++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("等待WebSocket连接被中断");
}
}
if (!jetLinksWebSocketClient.isConnected()) {
throw new RuntimeException("WebSocket连接超时");
}
}
}
}
@@ -0,0 +1,46 @@
package com.central.device.boat.model;
/**
* 无人船WebSocket订阅主题
* 基于JetLinks平台的主题订阅模式,使用 ship 产品标识
*
* @author dzc
* @date 2026-04-07
*/
public enum BoatSubscriptionTopic {
/** 无人船设备上线 */
BOAT_ONLINE("/device/ship/{deviceSn}/online"),
/** 无人船设备离线 */
BOAT_OFFLINE("/device/ship/{deviceSn}/offline"),
/** 无人船设备状态事件 */
BOAT_EVENT_FIRE_ALARM("/device/ship/{deviceSn}/message/event/fire_alarm"),
/** 无人船遥测数据事件 */
BOAT_EVENT_MSG_ALARM("/device/ship/{deviceSn}/message/event/msg_alarm"),
/** 无人船属性上报 */
BOAT_PROPERTY_REPORT("/device/ship/{deviceSn}/message/property/report");
private final String topicPattern;
BoatSubscriptionTopic(String topicPattern) {
this.topicPattern = topicPattern;
}
/**
* 获取主题(替换deviceSn占位符)
*/
public String getTopic(String deviceSn) {
return topicPattern.replace("{deviceSn}", deviceSn);
}
/**
* 获取主题模式
*/
public String getTopicPattern() {
return topicPattern;
}
}
@@ -0,0 +1,325 @@
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.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 java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 无人船SSE发射器管理器
* 管理无人船前端SSE连接、触发WebSocket订阅、推送设备实时数据
*
* 数据流:
* JetLinks IoT → JetLinksWebSocketClient → DeviceMessageHandler
* → msgAlarmCallback → BoatSseEmitterManager.sendBoatDataUpdate() → SSE客户端
*
* 复用组件:
* - BoatSubscriptionManager: WebSocket主题订阅/取消
* - SubscriptionPoolService: Redis订阅池(多客户端隔离)
* - DeviceMessageHandler: 注册回调接收IoT消息
* - EmitterWrapper: SSE连接包装器
*
* @author dzc
* @date 2026-04-07
*/
@Slf4j
@Component
public class BoatSseEmitterManager {
@Autowired
private BoatSubscriptionManager boatSubscriptionManager;
@Autowired
private DeviceMessageHandler messageHandler;
@Autowired
private SubscriptionPoolService subscriptionPoolService;
/** SSE连接池: sessionId -> EmitterWrapper */
private final ConcurrentHashMap<String, EmitterWrapper> emitters = new ConcurrentHashMap<>();
/** 设备订阅本地引用计数: deviceSn -> count */
private final ConcurrentHashMap<String, Integer> deviceRefCount = new ConcurrentHashMap<>();
private ScheduledExecutorService heartbeatExecutor;
private ScheduledExecutorService cleanupExecutor;
@PostConstruct
public void init() {
startHeartbeat();
startOrphanCleanup();
}
/**
* 添加无人船SSE连接
* 创建SSE连接 + 触发WebSocket订阅 + Redis订阅池 + 注册消息回调
*/
public SseEmitter addEmitter(String sessionId, String deviceSn, String tenantId) {
// 移除重复连接
if (emitters.containsKey(sessionId)) {
log.warn("[无人船SSE] 检测到重复连接,先移除: sessionId={}", sessionId);
removeEmitter(sessionId, deviceSn);
}
// 创建SseEmitter(5分钟超时,配合心跳续期)
SseEmitter emitter = new SseEmitter(5 * 60 * 1000L);
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);
emitters.put(sessionId, wrapper);
log.info("[无人船SSE] 新增连接: session={}, deviceSn={}, 当前连接数: {}",
sessionId, deviceSn, emitters.size());
// 发送连接确认
try {
emitter.send(SseEmitter.event()
.name("connected")
.data("{\"status\":\"connected\",\"deviceSn\":\"" + deviceSn + "\"}"));
} catch (Exception e) {
log.error("[无人船SSE] 发送连接确认失败: session={}", sessionId, e);
}
// 增加本地引用计数
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 (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);
}
return emitter;
}
/**
* 移除SSE连接(减少引用计数,必要时取消订阅)
*/
private void removeEmitter(String sessionId, String deviceSn) {
EmitterWrapper wrapper = emitters.remove(sessionId);
if (wrapper == null) {
return;
}
try {
wrapper.getEmitter().complete();
} catch (Exception e) {
log.debug("[无人船SSE] 完成连接失败(可能已关闭): session={}", sessionId);
}
log.info("[无人船SSE] 移除连接: session={}, deviceSn={}, 剩余连接数: {}",
sessionId, deviceSn, emitters.size());
// 减少本地引用计数
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 (isLastOnline && isLastOffline) {
boolean hasMsgAlarm = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM);
if (!hasMsgAlarm) {
log.info("[无人船SSE] 设备 {} 所有订阅者离开,取消设备订阅", deviceSn);
boatSubscriptionManager.unsubscribeBoatDevice(deviceSn);
}
}
}
/**
* 主动移除SSE连接(供控制器调用)
*/
public boolean removeEmitterBySessionId(String sessionId, String deviceSn) {
if (!emitters.containsKey(sessionId)) {
return false;
}
removeEmitter(sessionId, deviceSn);
return true;
}
/**
* 推送无人船数据到所有匹配 deviceSn 的SSE连接
*/
public void sendBoatDataUpdate(String deviceSn, JSONObject data) {
if (data == null) {
return;
}
List<String> deadEmitters = new ArrayList<>();
emitters.forEach((sessionId, wrapper) -> {
if (deviceSn.equals(wrapper.getDeviceSn())) {
try {
wrapper.getEmitter().send(SseEmitter.event()
.name("boat-telemetry")
.data(data.toJSONString())
.id("boat-" + System.currentTimeMillis()));
} catch (Exception e) {
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());
}
});
}
/**
* 心跳(15秒间隔,检测断连)
*/
private void startHeartbeat() {
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
heartbeatExecutor.scheduleAtFixedRate(() -> {
if (emitters.isEmpty()) return;
List<String> deadEmitters = new ArrayList<>();
emitters.forEach((sessionId, wrapper) -> {
try {
wrapper.getEmitter().send(SseEmitter.event()
.name("heartbeat")
.data("ping"));
} catch (Exception e) {
log.warn("[无人船SSE] 心跳失败: session={}", sessionId);
deadEmitters.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());
}
});
}
}, 15000, 15000, TimeUnit.MILLISECONDS);
log.info("[无人船SSE] 心跳已启动,间隔: 15秒");
}
/**
* 孤儿订阅清理(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();
}
}
@@ -30,26 +30,37 @@ public class BoatCommandController {
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@Parameter(description = "航线ID") @RequestParam String boatRouteId,
@Parameter(description = "任务编码") @RequestParam String missionCode) {
String taskId = boatControlService.executeRoute(deviceSn, boatRouteId, missionCode);
return Result.succeed(taskId, "任务已下发");
String commandId = boatControlService.executeRoute(deviceSn, boatRouteId, missionCode);
return Result.succeed(commandId, "任务已下发");
}
@Operation(summary = "暂停航行")
@PostMapping("/pause")
public Result<Void> pause(
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
boatControlService.pause(deviceSn);
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@Parameter(description = "任务编码") @RequestParam String missionCode) {
boatControlService.pause(deviceSn, missionCode);
return Result.succeed(null, "暂停指令已下发");
}
@Operation(summary = "恢复航行")
@PostMapping("/resume")
public Result<Void> resume(
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
boatControlService.resume(deviceSn);
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@Parameter(description = "任务编码") @RequestParam String missionCode) {
boatControlService.resume(deviceSn, missionCode);
return Result.succeed(null, "恢复指令已下发");
}
@Operation(summary = "终止任务")
@PostMapping("/undo")
public Result<Void> undoTask(
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@Parameter(description = "任务编码") @RequestParam String missionCode) {
boatControlService.undoTask(deviceSn, missionCode);
return Result.succeed(null, "终止任务指令已下发");
}
@Operation(summary = "返回起点")
@PostMapping("/return")
public Result<Void> returnToStart(
@@ -5,7 +5,7 @@ import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.JsonElement;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.central.common.model.Result;
import com.central.device.entity.WaylineRoute;
import com.central.device.boat.entity.WaylineRoute;
import com.central.device.feign.FileCenterService;
import com.central.device.message.ControlMessageConstant;
import com.central.device.model.AgeDevice;
@@ -13,10 +13,8 @@ import com.central.device.model.LineFile;
import com.central.device.service.IAgeDeviceService;
import com.central.device.service.ILineFileService;
import com.central.device.service.IWaylineRouteService;
import com.central.device.service.LiveStreamService;
import com.central.device.util.IotRequestResult;
import com.central.device.util.RequestUtils;
import com.central.device.util.TencentLiveUtil;
import com.central.device.websocket.manager.DeviceCommandManager;
import com.central.device.websocket.model.CommandStatus;
import com.central.device.websocket.model.DeviceCommand;
@@ -30,10 +28,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* 设备命令控制器
@@ -1,7 +1,7 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.boat.entity.DroneFlightTrack;
import com.central.device.model.vo.FlightTrackVO;
import com.central.device.service.IDroneFlightTrackService;
import io.swagger.v3.oas.annotations.Operation;
@@ -1,7 +1,7 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.WaterBoundary;
import com.central.device.boat.entity.WaterBoundary;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.dto.WaterBoundaryCreateDTO;
import com.central.device.model.dto.WaterBoundaryDisplayUpdateDTO;
@@ -1,9 +1,9 @@
package com.central.device.controller;
import com.central.common.model.Result;
import com.central.device.entity.WaylineAction;
import com.central.device.entity.WaylineRoute;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.boat.entity.WaylineAction;
import com.central.device.boat.entity.WaylineRoute;
import com.central.device.boat.entity.WaylineWaypoint;
import com.central.device.model.dto.WaylineRouteCreateDTO;
import com.central.device.model.dto.BindDeviceDTO;
import com.central.device.model.vo.WaylineRouteVO;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.BoatRoute;
import com.central.device.boat.entity.BoatRoute;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.BoatTrack;
import com.central.device.boat.entity.BoatTrack;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.BoatWaypoint;
import com.central.device.boat.entity.BoatWaypoint;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.boat.entity.DroneFlightTrack;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaterBoundary;
import com.central.device.boat.entity.WaterBoundary;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineAction;
import com.central.device.boat.entity.WaylineAction;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineRoute;
import com.central.device.boat.entity.WaylineRoute;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -1,7 +1,7 @@
package com.central.device.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.boat.entity.WaylineWaypoint;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@@ -13,7 +13,8 @@ public enum ControlEnum {
FLY_TO_POINT_UPDATE("fly_to_point_stop"),
FLIGHTTASK_PAUSE("flighttask_pause"),
FLIGHTTASK_PREPARE ("flighttask_prepare"),
FLIGHTTASK_RECOVERY( "flighttask_recovery");
FLIGHTTASK_RECOVERY("flighttask_recovery"),
FLIGHTTASK_UNDO("flighttask_undo");
private final String name;
@@ -1,6 +1,6 @@
package com.central.device.model.vo;
import com.central.device.entity.BoatWaypoint;
import com.central.device.boat.entity.BoatWaypoint;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@@ -16,7 +16,7 @@ public interface IBoatControlService {
* @param deviceSn 设备SN
* @param boatRouteId 航线ID
* @param missionCode 任务编码
* @return 任务ID
* @return 命令ID
*/
String executeRoute(String deviceSn, String boatRouteId, String missionCode);
@@ -24,15 +24,25 @@ public interface IBoatControlService {
* 暂停航行
*
* @param deviceSn 设备SN
* @param missionCode 任务编码(对应 order_no)
*/
void pause(String deviceSn);
void pause(String deviceSn, String missionCode);
/**
* 恢复航行
*
* @param deviceSn 设备SN
* @param missionCode 任务编码(对应 order_no)
*/
void resume(String deviceSn);
void resume(String deviceSn, String missionCode);
/**
* 终止任务(结束航行)
*
* @param deviceSn 设备SN
* @param missionCode 任务编码(对应 order_no)
*/
void undoTask(String deviceSn, String missionCode);
/**
* 返回起点
@@ -2,7 +2,7 @@ package com.central.device.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.BoatRoute;
import com.central.device.boat.entity.BoatRoute;
import com.central.device.model.dto.BoatRouteCreateDTO;
import com.central.device.model.dto.BoatRouteUpdateDTO;
import com.central.device.model.vo.BoatRouteDetailVO;
@@ -1,7 +1,7 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.BoatTrack;
import com.central.device.boat.entity.BoatTrack;
import com.central.device.model.vo.BoatRealtimeVO;
import com.central.device.model.vo.TaskTrackVO;
import com.central.device.model.vo.TrackPointVO;
@@ -1,7 +1,7 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.boat.entity.DroneFlightTrack;
import java.time.LocalDateTime;
import java.util.List;
@@ -1,7 +1,7 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaterBoundary;
import com.central.device.boat.entity.WaterBoundary;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.dto.WaterBoundaryCreateDTO;
import com.central.device.model.vo.BoundaryCheckResultVO;
@@ -1,7 +1,7 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaylineRoute;
import com.central.device.boat.entity.WaylineRoute;
import java.util.List;
@@ -1,7 +1,7 @@
package com.central.device.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.boat.entity.WaylineWaypoint;
import java.util.List;
@@ -1,21 +1,21 @@
package com.central.device.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.central.common.exception.BusinessException;
import com.central.device.entity.BoatRoute;
import com.central.device.boat.entity.BoatRoute;
import com.central.device.boat.manager.BoatCommandManager;
import com.central.device.model.AgeDevice;
import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.service.IAgeDeviceService;
import com.central.device.service.IBoatControlService;
import com.central.device.service.IBoatRouteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 无人船控制服务实现
* 当前为Mock实现,待实际设备对接后替换
* 通过 BoatCommandManager 向 JetLinks IoT 平台下发真实控制指令
*
* @author dzc
* @date 2026-01-05
@@ -26,240 +26,112 @@ import java.util.concurrent.ConcurrentHashMap;
public class BoatControlServiceImpl implements IBoatControlService {
private final IBoatRouteService boatRouteService;
/**
* Mock设备状态存储
* key: deviceSn, value: status
*/
private final Map<String, DeviceState> deviceStates = new ConcurrentHashMap<>();
/**
* Mock设备状态
*/
private static class DeviceState {
String status = "idle"; // idle, executing, paused, returning, stopped
String currentTaskId;
String currentRouteId;
boolean online = true;
}
private final BoatCommandManager boatCommandManager;
private final IAgeDeviceService ageDeviceService;
@Override
public String executeRoute(String deviceSn, String boatRouteId, String missionCode) {
log.info("[Mock] 执行航线任务: deviceSn={}, routeId={}, missionCode={}", deviceSn, boatRouteId, missionCode);
log.info("无人船执行航线任务: deviceSn={}, routeId={}, missionCode={}", deviceSn, boatRouteId, missionCode);
// 验证航线
// 1. 验证航线
BoatRoute route = boatRouteService.getByRouteId(boatRouteId);
if (route == null) {
throw new BusinessException("航线不存在");
}
// 检查设备状态
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!state.online) {
throw new BusinessException("设备离线");
}
if ("executing".equals(state.status)) {
throw new BusinessException("设备正在执行其他任务");
}
// 2. 构建指令参数
JSONObject params = new JSONObject();
params.put("order_no", missionCode);
params.put("wayline_link_url", route.getRouteFileUrl());
params.put("file_md5", "");
params.put("stream_urls", getStreamUrls(deviceSn));
// 生成任务ID
String taskId = UUID.randomUUID().toString().replace("-", "");
// 3. 通过 WebSocket 下发指令
String commandId = boatCommandManager.sendCommand(deviceSn, "flighttask_prepare", params);
// 更新Mock状态
state.status = "executing";
state.currentTaskId = taskId;
state.currentRouteId = boatRouteId;
// 更新航线状态
// 4. 更新航线状态
boatRouteService.updateStatus(boatRouteId, BoatRoute.RouteStatus.EXECUTING.getCode());
// TODO: 实际设备对接时,通过MQTT/WebSocket发送控制指令
// 指令格式示例:
// {
// "cmd": "execute_route",
// "taskId": taskId,
// "routeId": boatRouteId,
// "waypoints": [...],
// "params": { "speed": ..., "loop": ... }
// }
log.info("[Mock] 航线任务已下发: taskId={}", taskId);
return taskId;
log.info("无人船航线任务已下发: commandId={}, missionCode={}", commandId, missionCode);
return commandId;
}
@Override
public void pause(String deviceSn) {
log.info("[Mock] 暂停航行: deviceSn={}", deviceSn);
public void pause(String deviceSn, String missionCode) {
log.info("无人船暂停任务: deviceSn={}, missionCode={}", deviceSn, missionCode);
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!"executing".equals(state.status)) {
throw new BusinessException("设备当前未在执行任务");
}
JSONObject params = new JSONObject();
params.put("order_no", missionCode);
state.status = "paused";
// TODO: 发送暂停指令到设备
// {
// "cmd": "pause",
// "deviceSn": deviceSn
// }
log.info("[Mock] 暂停指令已下发");
boatCommandManager.sendCommand(deviceSn, "flighttask_pause", params);
}
@Override
public void resume(String deviceSn) {
log.info("[Mock] 恢复航行: deviceSn={}", deviceSn);
public void resume(String deviceSn, String missionCode) {
log.info("无人船恢复任务: deviceSn={}, missionCode={}", deviceSn, missionCode);
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!"paused".equals(state.status)) {
throw new BusinessException("设备当前未处于暂停状态");
}
JSONObject params = new JSONObject();
params.put("order_no", missionCode);
state.status = "executing";
boatCommandManager.sendCommand(deviceSn, "flighttask_recovery", params);
}
// TODO: 发送恢复指令到设备
// {
// "cmd": "resume",
// "deviceSn": deviceSn
// }
@Override
public void undoTask(String deviceSn, String missionCode) {
log.info("无人船终止任务: deviceSn={}, missionCode={}", deviceSn, missionCode);
log.info("[Mock] 恢复指令已下发");
JSONObject params = new JSONObject();
params.put("order_no", missionCode);
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
}
@Override
public void returnToStart(String deviceSn) {
log.info("[Mock] 返回起点: deviceSn={}", deviceSn);
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!state.online) {
throw new BusinessException("设备离线");
}
String previousStatus = state.status;
state.status = "returning";
// 如果有正在执行的航线,更新状态
if (state.currentRouteId != null && "executing".equals(previousStatus)) {
boatRouteService.updateStatus(state.currentRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
}
// TODO: 发送返航指令到设备
// {
// "cmd": "return_to_start",
// "deviceSn": deviceSn
// }
log.info("[Mock] 返航指令已下发");
log.info("无人船返回起点: deviceSn={}", deviceSn);
// 返回起点等同于终止当前任务,设备端自行处理返航逻辑
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
}
@Override
public void emergencyStop(String deviceSn) {
log.warn("[Mock] 紧急停止: deviceSn={}", deviceSn);
DeviceState state = getOrCreateDeviceState(deviceSn);
String previousRouteId = state.currentRouteId;
state.status = "stopped";
state.currentTaskId = null;
state.currentRouteId = null;
// 更新航线状态
if (previousRouteId != null) {
boatRouteService.updateStatus(previousRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
}
// TODO: 发送紧急停止指令到设备(最高优先级)
// {
// "cmd": "emergency_stop",
// "deviceSn": deviceSn,
// "priority": "highest"
// }
log.warn("[Mock] 紧急停止指令已下发");
log.warn("无人船紧急停止: deviceSn={}", deviceSn);
// 紧急停止使用终止任务指令
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
}
@Override
public void manualControl(String deviceSn, BoatManualControlDTO dto) {
log.debug("[Mock] 手动控制: deviceSn={}, throttle={}, rudder={}",
deviceSn, dto.getThrottle(), dto.getRudder());
DeviceState state = getOrCreateDeviceState(deviceSn);
if (!state.online) {
throw new BusinessException("设备离线");
}
// 手动控制时暂停自动任务
if ("executing".equals(state.status)) {
state.status = "paused";
log.info("[Mock] 切换到手动控制模式,自动任务已暂停");
}
// TODO: 发送手动控制指令到设备
// 这类指令需要高频发送(如50ms间隔)
// {
// "cmd": "manual_control",
// "deviceSn": deviceSn,
// "throttle": dto.getThrottle(),
// "rudder": dto.getRudder(),
// "timestamp": System.currentTimeMillis()
// }
log.debug("无人船手动控制: deviceSn={}, throttle={}, rudder={}",
deviceSn, dto.getThrottle(), dto.getRudder());
// 手动控制暂不通过此链路实现,保留接口
// TODO: 如有专用手动控制协议,后续对接
}
@Override
public boolean isDeviceOnline(String deviceSn) {
DeviceState state = deviceStates.get(deviceSn);
if (state == null) {
// Mock: 假设首次查询的设备都在线
return true;
}
return state.online;
// TODO: 后续对接真实设备在线状态查询
return true;
}
@Override
public String getDeviceStatus(String deviceSn) {
DeviceState state = deviceStates.get(deviceSn);
if (state == null) {
return "idle";
}
return state.status;
// TODO: 后续对接真实设备状态查询
return "idle";
}
// ========== Mock辅助方法 ==========
private DeviceState getOrCreateDeviceState(String deviceSn) {
return deviceStates.computeIfAbsent(deviceSn, k -> new DeviceState());
}
/**
* 模拟设备上线(供测试使用)
*/
public void mockDeviceOnline(String deviceSn) {
DeviceState state = getOrCreateDeviceState(deviceSn);
state.online = true;
log.info("[Mock] 设备上线: deviceSn={}", deviceSn);
}
/**
* 模拟设备离线(供测试使用)
*/
public void mockDeviceOffline(String deviceSn) {
DeviceState state = getOrCreateDeviceState(deviceSn);
state.online = false;
log.info("[Mock] 设备离线: deviceSn={}", deviceSn);
}
/**
* 模拟任务完成(供测试使用)
* 获取设备视频流地址
*/
public void mockTaskComplete(String deviceSn) {
DeviceState state = deviceStates.get(deviceSn);
if (state != null && state.currentRouteId != null) {
boatRouteService.updateStatus(state.currentRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
state.status = "idle";
state.currentTaskId = null;
state.currentRouteId = null;
log.info("[Mock] 任务完成: deviceSn={}", deviceSn);
private JSONObject getStreamUrls(String deviceSn) {
JSONObject result = new JSONObject();
AgeDevice device = ageDeviceService.getByDeviceSn(deviceSn);
if (device != null) {
result.put("pushUrl", device.getPushStreamUrl());
}
result.put("playRtmpUrl", "");
result.put("playFlvUrl", "");
result.put("playM3u8Url", "");
return result;
}
}
@@ -7,8 +7,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.exception.BusinessException;
import com.central.device.entity.BoatRoute;
import com.central.device.entity.BoatWaypoint;
import com.central.device.boat.entity.BoatRoute;
import com.central.device.boat.entity.BoatWaypoint;
import com.central.device.feign.FileCenterService;
import com.central.device.mapper.BoatRouteMapper;
import com.central.device.mapper.BoatWaypointMapper;
@@ -80,7 +80,7 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
} catch (Exception ignored) {
log.error("获取当前登录用户租户失败");
}
route.setTenantId(anchor);
route.setTenantId(anchor==null?"webApp":anchor);
route.setStatus(BoatRoute.RouteStatus.DRAFT.getCode());
route.setIsTemplate(false);
route.setShowInModel(dto.getShowInModel() != null ? dto.getShowInModel() : 0);
@@ -1,9 +1,8 @@
package com.central.device.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.exception.BusinessException;
import com.central.device.entity.BoatTrack;
import com.central.device.boat.entity.BoatTrack;
import com.central.device.mapper.BoatTrackMapper;
import com.central.device.model.vo.BoatRealtimeVO;
import com.central.device.model.vo.TaskTrackVO;
@@ -14,7 +13,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -1,13 +1,12 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.DroneFlightTrack;
import com.central.device.boat.entity.DroneFlightTrack;
import com.central.device.mapper.DroneFlightTrackMapper;
import com.central.device.service.IDroneFlightTrackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@@ -8,7 +8,7 @@ import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.exception.BusinessException;
import com.central.device.entity.WaterBoundary;
import com.central.device.boat.entity.WaterBoundary;
import com.central.device.mapper.WaterBoundaryMapper;
import com.central.device.model.dto.PointDTO;
import com.central.device.model.dto.WaterBoundaryCreateDTO;
@@ -21,7 +21,6 @@ import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -1,8 +1,8 @@
package com.central.device.service.impl;
import com.central.device.entity.WaylineAction;
import com.central.device.entity.WaylineRoute;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.boat.entity.WaylineAction;
import com.central.device.boat.entity.WaylineRoute;
import com.central.device.boat.entity.WaylineWaypoint;
import com.central.device.feign.FileCenterService;
import com.central.device.mapper.WaylineActionMapper;
import com.central.device.mapper.WaylineRouteMapper;
@@ -1,13 +1,12 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.WaylineRoute;
import com.central.device.boat.entity.WaylineRoute;
import com.central.device.mapper.WaylineRouteMapper;
import com.central.device.mapper.WaylineActionMapper;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.mapper.DroneFlightTrackMapper;
import com.central.device.service.IWaylineRouteService;
import com.central.device.model.LineFile;
import com.central.device.service.IWaylineParseService;
import com.central.device.parser.model.KmzParseResult;
import lombok.extern.slf4j.Slf4j;
@@ -17,7 +16,6 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@@ -1,7 +1,7 @@
package com.central.device.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.central.device.entity.WaylineWaypoint;
import com.central.device.boat.entity.WaylineWaypoint;
import com.central.device.mapper.WaylineWaypointMapper;
import com.central.device.service.IWaylineWaypointService;
import org.springframework.stereotype.Service;
@@ -1,9 +1,7 @@
package com.central.device.sse.controller;
import com.alibaba.fastjson.JSON;
import com.central.common.context.LoginUserContextHolder;
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;
@@ -14,14 +12,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控制器
* 提供SSE端点供前端订阅无人船实时位置数据
* 提供SSE端点供前端订阅无人船实时数据
*
* 数据流:
* JetLinks IoT → WebSocket → DeviceMessageHandler → msgAlarmCallback
* → BoatSseEmitterManager → SSE推送到前端
*
* @author dzc
* @date 2026-01-05
@@ -33,17 +33,11 @@ import java.util.concurrent.ConcurrentHashMap;
@RequiredArgsConstructor
public class BoatTelemetrySseController {
private final IBoatTrackService boatTrackService;
/**
* 存储SSE连接
* key: connectionId, value: SseEmitter
*/
private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
private final BoatSseEmitterManager boatSseEmitterManager;
/**
* 订阅无人船遥测数据SSE连接
* 前端建立SSE连接后,会实时推送无人船位置、速度、电量等数据
* 前端建立SSE连接后,后端自动触发WebSocket订阅并实时推送无人船数据
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID(可选)
@@ -58,83 +52,33 @@ public class BoatTelemetrySseController {
@RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) {
String tenantId = LoginUserContextHolder.getCurrentTenantId() != null
? LoginUserContextHolder.getCurrentTenantId() : "1";
? LoginUserContextHolder.getCurrentTenantId() : "1";
String username = LoginUserContextHolder.getUser() != null
? LoginUserContextHolder.getUser().getUsername() : "anonymous";
? LoginUserContextHolder.getUser().getUsername() : "anonymous";
// 生成connectionId
String connectionId;
String sessionId;
if (clientSessionId != null && !clientSessionId.trim().isEmpty()) {
connectionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("客户端订阅无人船遥测SSE(复用会话): connectionId={}, deviceSn={}, tenant={}, user={}",
connectionId, deviceSn, tenantId, username);
sessionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("[无人船SSE] 客户端订阅(复用会话): session={}, deviceSn={}, tenant={}, user={}",
sessionId, deviceSn, tenantId, username);
} else {
connectionId = "boat_" + UUID.randomUUID().toString() + "_" + deviceSn;
log.info("客户端订阅无人船遥测SSE(新会话): connectionId={}, deviceSn={}, tenant={}, user={}",
connectionId, deviceSn, tenantId, username);
sessionId = "boat_" + UUID.randomUUID() + "_" + deviceSn;
log.info("[无人船SSE] 客户端订阅(新会话): session={}, deviceSn={}, tenant={}, user={}",
sessionId, deviceSn, tenantId, username);
}
// 如果已存在相同连接,先移除
if (emitters.containsKey(connectionId)) {
removeConnection(connectionId, deviceSn);
}
// 创建SSE连接 (30分钟超时)
SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
// 配置回调
emitter.onCompletion(() -> {
log.info("无人船SSE连接完成: connectionId={}", connectionId);
removeConnection(connectionId, deviceSn);
});
emitter.onTimeout(() -> {
log.info("无人船SSE连接超时: connectionId={}", connectionId);
removeConnection(connectionId, deviceSn);
});
emitter.onError(e -> {
log.warn("无人船SSE连接错误: connectionId={}, error={}", connectionId, e.getMessage());
removeConnection(connectionId, deviceSn);
});
// 存储连接
emitters.put(connectionId, emitter);
// 注册遥测数据回调
boatTrackService.registerTelemetryCallback(deviceSn, connectionId, data -> {
sendTelemetryData(connectionId, data);
});
// 发送初始连接成功事件
try {
emitter.send(SseEmitter.event()
.name("connected")
.data("{\"status\":\"connected\",\"deviceSn\":\"" + deviceSn + "\"}"));
} catch (IOException e) {
log.error("发送初始连接事件失败: connectionId={}", connectionId, e);
}
// 发送当前实时位置(如果有)
BoatRealtimeVO realtime = boatTrackService.getRealtimePosition(deviceSn);
if (realtime != null) {
sendTelemetryData(connectionId, realtime);
}
SseEmitter emitter = boatSseEmitterManager.addEmitter(sessionId, deviceSn, tenantId);
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);
.header("Cache-Control", "no-cache, no-transform")
.header("Connection", "keep-alive")
.header("X-Accel-Buffering", "no")
.contentType(MediaType.TEXT_EVENT_STREAM)
.body(emitter);
}
/**
* 主动断开无人船遥测SSE连接
*
* @param deviceSn 设备SN
* @param clientSessionId 客户端会话ID
* @return 断开结果
*/
@Operation(summary = "主动断开无人船遥测SSE连接")
@DeleteMapping("/telemetry/{deviceSn}")
@@ -144,27 +88,18 @@ public class BoatTelemetrySseController {
@Parameter(description = "客户端会话ID", required = true)
@RequestHeader(value = "X-Client-Session-Id") String clientSessionId) {
String connectionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("客户端主动断开无人船遥测SSE连接: connectionId={}, deviceSn={}", connectionId, deviceSn);
String sessionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("[无人船SSE] 客户端主动断开: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = removeConnection(connectionId, deviceSn);
if (success) {
return ResponseEntity.ok("连接已断开");
} else {
return ResponseEntity.ok("连接不存在或已断开");
}
boolean success = boatSseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
return ResponseEntity.ok(success ? "连接已断开" : "连接不存在或已断开");
}
/**
* Beacon方式断开无人船遥测SSE连接
* 用于浏览器刷新/关闭时
*
* @param deviceSn 设备SN
* @param body 包含sessionId的请求体
* @return 断开结果
* 用于浏览器刷新/关闭时,sendBeacon只支持POST请求
*/
@Operation(summary = "Beacon方式断开无人船遥测SSE连接")
@Operation(summary = "Beacon方式断开无人船遥测SSE连接(浏览器刷新/关闭时使用)")
@PostMapping("/telemetry/{deviceSn}/disconnect")
public ResponseEntity<String> disconnectBoatTelemetryByBeacon(
@Parameter(description = "设备SN", required = true)
@@ -173,61 +108,14 @@ public class BoatTelemetrySseController {
String clientSessionId = body != null ? body.get("sessionId") : null;
if (clientSessionId == null || clientSessionId.trim().isEmpty()) {
log.warn("Beacon断开无人船SSE请求缺少sessionId: deviceSn={}", deviceSn);
log.warn("[无人船SSE] Beacon断开请求缺少sessionId: deviceSn={}", deviceSn);
return ResponseEntity.badRequest().body("缺少sessionId");
}
String connectionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("Beacon方式断开无人船遥测SSE连接: connectionId={}, deviceSn={}", connectionId, deviceSn);
String sessionId = "boat_" + clientSessionId + "_" + deviceSn;
log.info("[无人船SSE] Beacon方式断开: session={}, deviceSn={}", sessionId, deviceSn);
boolean success = removeConnection(connectionId, deviceSn);
if (success) {
return ResponseEntity.ok("连接已断开");
} else {
return ResponseEntity.ok("连接不存在或已断开");
}
}
// ========== 私有方法 ==========
/**
* 发送遥测数据到指定连接
*/
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("发送遥测数据失败: connectionId={}, error={}", connectionId, e.getMessage());
// 发送失败时移除连接
String deviceSn = data.getDeviceSn();
removeConnection(connectionId, deviceSn);
}
}
/**
* 移除连接并清理资源
*/
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;
boolean success = boatSseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
return ResponseEntity.ok(success ? "连接已断开" : "连接不存在或已断开");
}
}
@@ -381,9 +381,9 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
/**
* 从topic中提取deviceSn
* 支持的topic格式:
* 1. /device/D-Dock2/{deviceSn}/... (订阅消息)
* 2. /device-message-sender/D-Dock2/{deviceSn} (命令响应)
* 支持的topic格式(通用,支持任意产品类型):
* 1. /device/{productType}/{deviceSn}/... (订阅消息,如 AutoDock3、ship)
* 2. /device-message-sender/{productType}/{deviceSn} (命令响应)
*/
private String extractDeviceSn(String topic) {
if (topic == null) {
@@ -393,13 +393,9 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
String[] parts = topic.split("/");
// 格式1: /device/D-Dock2/{deviceSn}/...
if (topic.startsWith("/device/AutoDock3/") && parts.length >= 4) {
return parts[3];
}
// 格式2: /device-message-sender/D-Dock2/{deviceSn}
if (topic.startsWith("/device-message-sender/AutoDock3/") && parts.length >= 4) {
// 通用格式: /device/{productType}/{deviceSn}/... 或 /device-message-sender/{productType}/{deviceSn}
// parts[0] 为空字符串(topic以/开头),parts[1] 为 "device" 或 "device-message-sender",parts[3] 为 deviceSn
if (parts.length >= 4 && ("device".equals(parts[1]) || "device-message-sender".equals(parts[1]))) {
return parts[3];
}
@@ -543,6 +539,95 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
topic, subscriptionId, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
}
/**
* 订阅指定 topic 字符串(公开方法,供非 SubscriptionTopic 枚举的产品使用)
* 将 topic 纳入 subscribedTopics 跟踪,确保消息路由不被过滤
*
* @param topic 完整 topic 路径(如 /device/ship/{deviceSn}/online)
* @param deviceSn 设备SN
*/
public void subscribeRawTopic(String topic, String deviceSn) {
if (topic == null || deviceSn == null) {
return;
}
if (subscribedTopics.contains(topic)) {
log.debug("主题已订阅,跳过重复订阅: topic={}, deviceSn={}", topic, deviceSn);
return;
}
String subscriptionId = "sub-" + deviceSn + "-" + UUID.randomUUID().toString().substring(0, 8);
topicSubscriptionIds.put(topic, subscriptionId);
SubscriptionMessage message = SubscriptionMessage.builder()
.type("sub")
.topic(topic)
.parameter(new JSONObject())
.id(subscriptionId)
.build();
send(JSON.toJSONString(message));
subscribedTopics.add(topic);
deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet();
log.info("发送订阅消息: topic={}, id={}, 设备{}订阅计数: {}",
topic, subscriptionId, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
}
/**
* 取消订阅指定 topic 字符串(公开方法)
*
* @param topic 完整 topic 路径
* @param deviceSn 设备SN
*/
public void unsubscribeRawTopic(String topic, String deviceSn) {
if (topic == null || deviceSn == null) {
return;
}
if (!subscribedTopics.contains(topic)) {
return;
}
String subscriptionId = topicSubscriptionIds.remove(topic);
if (subscriptionId == null) {
subscriptionId = "unsub-" + UUID.randomUUID().toString();
}
SubscriptionMessage message = SubscriptionMessage.builder()
.type("unsub")
.topic(topic)
.parameter(new JSONObject())
.id(subscriptionId)
.build();
send(JSON.toJSONString(message));
subscribedTopics.remove(topic);
boolean hasOtherTopics = subscribedTopics.stream()
.anyMatch(t -> t.contains("/" + deviceSn + "/"));
if (!hasOtherTopics) {
deviceSubscriptionCounts.remove(deviceSn);
} else {
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn);
if (count != null) {
count.decrementAndGet();
}
}
log.info("取消订阅主题: topic={}, id={}, 剩余主题数: {}",
topic, subscriptionId, subscribedTopics.size());
// 所有主题都取消后,自动断开连接
if (subscribedTopics.isEmpty()) {
log.info("所有主题订阅已取消,自动断开WebSocket连接以节省资源");
deviceSubscriptionCounts.clear();
closeConnection();
}
}
/**
* 取消订阅主题
*/