feat: 无人机控制指令
This commit is contained in:
@@ -58,7 +58,9 @@
|
|||||||
"Bash(del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\websocket\\config\\DeviceControlWebSocketConfig.java\")",
|
"Bash(del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\websocket\\config\\DeviceControlWebSocketConfig.java\")",
|
||||||
"Bash(del \"F:\\project\\go-fly-platform-services\\zlt-web\\react-web-next\\src\\services\\deviceControlWs.ts\")",
|
"Bash(del \"F:\\project\\go-fly-platform-services\\zlt-web\\react-web-next\\src\\services\\deviceControlWs.ts\")",
|
||||||
"Bash(del:*)",
|
"Bash(del:*)",
|
||||||
"Bash(cmd /c del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\controller\\CdnProxyController.java\")"
|
"Bash(cmd /c del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\controller\\CdnProxyController.java\")",
|
||||||
|
"Bash(cmd /c del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\websocket\\config\\DeviceControlWebSocketConfig.java\")",
|
||||||
|
"Bash(cmd /c del \"F:\\project\\go-fly-platform-services\\zlt-business\\device-center\\src\\main\\java\\com\\central\\device\\websocket\\handler\\DeviceControlWebSocketHandler.java\")"
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 3.2 MiB After Width: | Height: | Size: 1.7 MiB |
@@ -107,16 +107,16 @@
|
|||||||
<version>4.12.0</version>
|
<version>4.12.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- WebSocket客户端 -->
|
<!-- WebSocket支持(客户端和服务端) -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-websocket</artifactId>
|
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- Jakarta Servlet API (Spring Boot 3.x 使用 Jakarta 命名空间) -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>jakarta.servlet</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>jakarta.servlet-api</artifactId>
|
||||||
<version>4.0.1</version>
|
<scope>provided</scope>
|
||||||
<scope>compile</scope>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|||||||
+5
-2
@@ -336,8 +336,8 @@ public class DeviceCommandController {
|
|||||||
@Operation(summary = "DRC杆量控制")
|
@Operation(summary = "DRC杆量控制")
|
||||||
@PostMapping("/drc/stick")
|
@PostMapping("/drc/stick")
|
||||||
public Result<String> stickControl(@RequestBody StickControlRequest request) {
|
public Result<String> stickControl(@RequestBody StickControlRequest request) {
|
||||||
log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}",
|
log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}, gimbalPitch={}",
|
||||||
request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw());
|
request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw(), request.getGimbalPitch());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
JSONObject params = new JSONObject();
|
JSONObject params = new JSONObject();
|
||||||
@@ -345,6 +345,7 @@ public class DeviceCommandController {
|
|||||||
params.put("pitch", request.getPitch() != null ? request.getPitch() : 1024);
|
params.put("pitch", request.getPitch() != null ? request.getPitch() : 1024);
|
||||||
params.put("throttle", request.getThrottle() != null ? request.getThrottle() : 1024);
|
params.put("throttle", request.getThrottle() != null ? request.getThrottle() : 1024);
|
||||||
params.put("yaw", request.getYaw() != null ? request.getYaw() : 1024);
|
params.put("yaw", request.getYaw() != null ? request.getYaw() : 1024);
|
||||||
|
params.put("gimbal_pitch", request.getGimbalPitch() != null ? request.getGimbalPitch() : 1024);
|
||||||
|
|
||||||
String commandId = commandManager.sendCommand(
|
String commandId = commandManager.sendCommand(
|
||||||
request.getDeviceSn(),
|
request.getDeviceSn(),
|
||||||
@@ -461,6 +462,8 @@ public class DeviceCommandController {
|
|||||||
private Integer throttle;
|
private Integer throttle;
|
||||||
/** 偏航通道(624-1424,1024为中值) */
|
/** 偏航通道(624-1424,1024为中值) */
|
||||||
private Integer yaw;
|
private Integer yaw;
|
||||||
|
/** 云台俯仰(624-1424,1024为中值) */
|
||||||
|
private Integer gimbalPitch;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+1
-1
@@ -16,7 +16,7 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import jakarta.annotation.Resource;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import jakarta.annotation.Resource;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+3
-4
@@ -11,7 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
@@ -464,8 +464,7 @@ public class SseEmitterManager {
|
|||||||
.filter(w -> deviceSn.equals(w.getDeviceSn()) && Boolean.TRUE.equals(w.getIsDroneTelemetry()))
|
.filter(w -> deviceSn.equals(w.getDeviceSn()) && Boolean.TRUE.equals(w.getIsDroneTelemetry()))
|
||||||
.count();
|
.count();
|
||||||
|
|
||||||
log.info("【无人机数据推送】deviceSn={}, 无人机SSE连接数={}, 总连接数={}",
|
// log.info("【无人机数据推送】deviceSn={}, 无人机SSE连接数={}, 总连接数={}",deviceSn, droneConnectionCount, emitters.size());
|
||||||
deviceSn, droneConnectionCount, emitters.size());
|
|
||||||
|
|
||||||
if (droneConnectionCount == 0) {
|
if (droneConnectionCount == 0) {
|
||||||
log.warn("【无人机数据推送】没有找到无人机SSE连接: deviceSn={}", deviceSn);
|
log.warn("【无人机数据推送】没有找到无人机SSE连接: deviceSn={}", deviceSn);
|
||||||
@@ -488,7 +487,7 @@ public class SseEmitterManager {
|
|||||||
.id("drone-" + System.currentTimeMillis());
|
.id("drone-" + System.currentTimeMillis());
|
||||||
|
|
||||||
wrapper.getEmitter().send(event);
|
wrapper.getEmitter().send(event);
|
||||||
log.info("✅ 发送无人机数据更新成功: session={}, deviceSn={}", sessionId, deviceSn);
|
// log.info("✅ 发送无人机数据更新成功: session={}, deviceSn={}", sessionId, deviceSn);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("发送无人机数据更新失败,连接可能已关闭: session={}, deviceSn={}, error={}",
|
log.warn("发送无人机数据更新失败,连接可能已关闭: session={}, deviceSn={}, error={}",
|
||||||
sessionId, deviceSn, e.getMessage());
|
sessionId, deviceSn, e.getMessage());
|
||||||
|
|||||||
+3
-3
@@ -16,8 +16,8 @@ import org.springframework.web.socket.WebSocketSession;
|
|||||||
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
|
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
|
||||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import javax.annotation.PreDestroy;
|
import jakarta.annotation.PreDestroy;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -211,7 +211,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
*/
|
*/
|
||||||
private void handleCommandResponseMessage(JSONObject json) {
|
private void handleCommandResponseMessage(JSONObject json) {
|
||||||
String topic = json.getString("topic");
|
String topic = json.getString("topic");
|
||||||
String requestId = json.getString("id");
|
String requestId = json.getString("requestId");
|
||||||
String deviceSn = extractDeviceSn(topic);
|
String deviceSn = extractDeviceSn(topic);
|
||||||
|
|
||||||
log.info("收到命令响应: topic={}, requestId={}, deviceSn={}, json={}", topic, requestId, deviceSn, json.toJSONString());
|
log.info("收到命令响应: topic={}, requestId={}, deviceSn={}, json={}", topic, requestId, deviceSn, json.toJSONString());
|
||||||
|
|||||||
-30
@@ -1,30 +0,0 @@
|
|||||||
package com.central.device.websocket.config;
|
|
||||||
|
|
||||||
import com.central.device.websocket.handler.DeviceControlWebSocketHandler;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
|
||||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
|
||||||
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设备控制WebSocket配置
|
|
||||||
* 用于云台控制和摇杆控制的高频实时通信
|
|
||||||
*
|
|
||||||
* @author lishilin
|
|
||||||
* @date 2025-01-19
|
|
||||||
*/
|
|
||||||
@Configuration
|
|
||||||
@EnableWebSocket
|
|
||||||
public class DeviceControlWebSocketConfig implements WebSocketConfigurer {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private DeviceControlWebSocketHandler deviceControlWebSocketHandler;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
|
||||||
// 注册WebSocket端点,路径格式: /ws/control/{deviceSn}
|
|
||||||
registry.addHandler(deviceControlWebSocketHandler, "/ws/control/*")
|
|
||||||
.setAllowedOrigins("*"); // 生产环境应配置具体域名
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-309
@@ -1,309 +0,0 @@
|
|||||||
package com.central.device.websocket.handler;
|
|
||||||
|
|
||||||
import com.alibaba.fastjson.JSON;
|
|
||||||
import com.alibaba.fastjson.JSONObject;
|
|
||||||
import com.central.device.websocket.client.JetLinksWebSocketClient;
|
|
||||||
import com.central.device.websocket.config.WebSocketProperties;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import org.springframework.web.socket.CloseStatus;
|
|
||||||
import org.springframework.web.socket.TextMessage;
|
|
||||||
import org.springframework.web.socket.WebSocketSession;
|
|
||||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设备控制WebSocket处理器
|
|
||||||
* 处理前端发送的高频控制指令(云台、摇杆)
|
|
||||||
* 直接转发到JetLinks WebSocket
|
|
||||||
*
|
|
||||||
* @author lishilin
|
|
||||||
* @date 2025-01-19
|
|
||||||
*/
|
|
||||||
@Slf4j
|
|
||||||
@Component
|
|
||||||
public class DeviceControlWebSocketHandler extends TextWebSocketHandler {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private JetLinksWebSocketClient jetLinksWebSocketClient;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private WebSocketProperties properties;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 活跃的WebSocket会话: sessionId -> WebSocketSession
|
|
||||||
*/
|
|
||||||
private final Map<String, WebSocketSession> activeSessions = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 会话对应的设备SN: sessionId -> deviceSn
|
|
||||||
*/
|
|
||||||
private final Map<String, String> sessionDeviceMap = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
|
||||||
// 从URL路径中提取deviceSn: /ws/control/{deviceSn}
|
|
||||||
String path = session.getUri().getPath();
|
|
||||||
String deviceSn = extractDeviceSn(path);
|
|
||||||
|
|
||||||
if (deviceSn == null || deviceSn.isEmpty()) {
|
|
||||||
log.warn("无效的WebSocket连接,缺少deviceSn: path={}", path);
|
|
||||||
session.close(CloseStatus.BAD_DATA.withReason("Missing deviceSn"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String sessionId = session.getId();
|
|
||||||
activeSessions.put(sessionId, session);
|
|
||||||
sessionDeviceMap.put(sessionId, deviceSn);
|
|
||||||
|
|
||||||
log.info("设备控制WebSocket连接建立: sessionId={}, deviceSn={}", sessionId, deviceSn);
|
|
||||||
|
|
||||||
// 确保JetLinks WebSocket已连接
|
|
||||||
if (!jetLinksWebSocketClient.isConnected()) {
|
|
||||||
log.info("JetLinks WebSocket未连接,自动建立连接");
|
|
||||||
jetLinksWebSocketClient.connect();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 发送连接成功消息
|
|
||||||
sendResponse(session, "response", true, "连接成功", null);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
|
|
||||||
String sessionId = session.getId();
|
|
||||||
String deviceSn = sessionDeviceMap.get(sessionId);
|
|
||||||
|
|
||||||
if (deviceSn == null) {
|
|
||||||
log.warn("未知会话收到消息: sessionId={}", sessionId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
String payload = message.getPayload();
|
|
||||||
JSONObject json = JSON.parseObject(payload);
|
|
||||||
String type = json.getString("type");
|
|
||||||
|
|
||||||
switch (type) {
|
|
||||||
case "heartbeat":
|
|
||||||
// 心跳响应
|
|
||||||
sendPong(session);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "stick_control":
|
|
||||||
// 摇杆控制
|
|
||||||
handleStickControl(session, deviceSn, json.getJSONObject("data"));
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "gimbal_control":
|
|
||||||
// 云台控制
|
|
||||||
handleGimbalControl(session, deviceSn, json.getJSONObject("data"));
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
log.warn("未知消息类型: type={}, sessionId={}", type, sessionId);
|
|
||||||
sendResponse(session, "error", false, "未知消息类型: " + type, null);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("处理控制消息失败: sessionId={}, error={}", sessionId, e.getMessage());
|
|
||||||
sendResponse(session, "error", false, "消息处理失败: " + e.getMessage(), null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
|
|
||||||
String sessionId = session.getId();
|
|
||||||
String deviceSn = sessionDeviceMap.remove(sessionId);
|
|
||||||
activeSessions.remove(sessionId);
|
|
||||||
|
|
||||||
log.info("设备控制WebSocket连接关闭: sessionId={}, deviceSn={}, status={}",
|
|
||||||
sessionId, deviceSn, status);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
|
|
||||||
String sessionId = session.getId();
|
|
||||||
log.error("设备控制WebSocket传输错误: sessionId={}, error={}", sessionId, exception.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 处理摇杆控制
|
|
||||||
*/
|
|
||||||
private void handleStickControl(WebSocketSession session, String deviceSn, JSONObject data) {
|
|
||||||
if (data == null) {
|
|
||||||
sendResponse(session, "error", false, "缺少控制数据", null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建JetLinks命令
|
|
||||||
JSONObject params = new JSONObject();
|
|
||||||
params.put("roll", data.getIntValue("roll") != 0 ? data.getIntValue("roll") : 1024);
|
|
||||||
params.put("pitch", data.getIntValue("pitch") != 0 ? data.getIntValue("pitch") : 1024);
|
|
||||||
params.put("throttle", data.getIntValue("throttle") != 0 ? data.getIntValue("throttle") : 1024);
|
|
||||||
params.put("yaw", data.getIntValue("yaw") != 0 ? data.getIntValue("yaw") : 1024);
|
|
||||||
|
|
||||||
String commandId = sendToJetLinks(deviceSn, "stick_control", params);
|
|
||||||
|
|
||||||
if (commandId != null) {
|
|
||||||
sendResponse(session, "response", true, "摇杆指令已发送", commandId);
|
|
||||||
} else {
|
|
||||||
sendResponse(session, "error", false, "摇杆指令发送失败", null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 处理云台控制
|
|
||||||
*/
|
|
||||||
private void handleGimbalControl(WebSocketSession session, String deviceSn, JSONObject data) {
|
|
||||||
if (data == null) {
|
|
||||||
sendResponse(session, "error", false, "缺少控制数据", null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建JetLinks命令
|
|
||||||
JSONObject params = new JSONObject();
|
|
||||||
params.put("pitch_speed", data.getDoubleValue("pitchSpeed"));
|
|
||||||
params.put("yaw_speed", data.getDoubleValue("yawSpeed"));
|
|
||||||
params.put("locked", data.getBooleanValue("locked"));
|
|
||||||
|
|
||||||
String commandId = sendToJetLinks(deviceSn, "camera_screen_drag", params);
|
|
||||||
|
|
||||||
if (commandId != null) {
|
|
||||||
sendResponse(session, "response", true, "云台指令已发送", commandId);
|
|
||||||
} else {
|
|
||||||
sendResponse(session, "error", false, "云台指令发送失败", null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送命令到JetLinks
|
|
||||||
*
|
|
||||||
* @return commandId 或 null(失败时)
|
|
||||||
*/
|
|
||||||
private String sendToJetLinks(String deviceSn, String method, JSONObject data) {
|
|
||||||
if (!jetLinksWebSocketClient.isConnected()) {
|
|
||||||
log.warn("JetLinks WebSocket未连接,尝试重连");
|
|
||||||
jetLinksWebSocketClient.connect();
|
|
||||||
|
|
||||||
// 等待连接(最多1秒,避免阻塞高频控制)
|
|
||||||
int waitCount = 0;
|
|
||||||
while (!jetLinksWebSocketClient.isConnected() && waitCount < 10) {
|
|
||||||
try {
|
|
||||||
Thread.sleep(100);
|
|
||||||
waitCount++;
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!jetLinksWebSocketClient.isConnected()) {
|
|
||||||
log.error("JetLinks WebSocket连接失败");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
String commandId = UUID.randomUUID().toString();
|
|
||||||
|
|
||||||
// 构造 properties
|
|
||||||
JSONObject properties = new JSONObject();
|
|
||||||
properties.put("method", method);
|
|
||||||
JSONObject dataWrapper = new JSONObject();
|
|
||||||
dataWrapper.put("data", data);
|
|
||||||
properties.put("data", dataWrapper);
|
|
||||||
|
|
||||||
// 构造 parameter
|
|
||||||
JSONObject parameter = new JSONObject();
|
|
||||||
parameter.put("messageType", "WRITE_PROPERTY");
|
|
||||||
parameter.put("properties", properties);
|
|
||||||
|
|
||||||
JSONObject headers = new JSONObject();
|
|
||||||
headers.put("async", false);
|
|
||||||
parameter.put("headers", headers);
|
|
||||||
|
|
||||||
// 构造完整消息
|
|
||||||
JSONObject message = new JSONObject();
|
|
||||||
message.put("type", "sub");
|
|
||||||
message.put("topic", "/device-message-sender/D-Dock2/" + deviceSn);
|
|
||||||
message.put("parameter", parameter);
|
|
||||||
message.put("id", commandId);
|
|
||||||
|
|
||||||
// 发送
|
|
||||||
String messageJson = message.toJSONString();
|
|
||||||
log.debug("发送实时控制命令: deviceSn={}, method={}, commandId={}", deviceSn, method, commandId);
|
|
||||||
jetLinksWebSocketClient.send(messageJson);
|
|
||||||
|
|
||||||
return commandId;
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("发送JetLinks命令失败: deviceSn={}, method={}, error={}", deviceSn, method, e.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送响应消息
|
|
||||||
*/
|
|
||||||
private void sendResponse(WebSocketSession session, String type, boolean success, String message, String commandId) {
|
|
||||||
try {
|
|
||||||
JSONObject response = new JSONObject();
|
|
||||||
response.put("type", type);
|
|
||||||
response.put("success", success);
|
|
||||||
response.put("message", message);
|
|
||||||
if (commandId != null) {
|
|
||||||
response.put("commandId", commandId);
|
|
||||||
}
|
|
||||||
|
|
||||||
session.sendMessage(new TextMessage(response.toJSONString()));
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("发送响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送心跳响应
|
|
||||||
*/
|
|
||||||
private void sendPong(WebSocketSession session) {
|
|
||||||
try {
|
|
||||||
JSONObject pong = new JSONObject();
|
|
||||||
pong.put("type", "pong");
|
|
||||||
pong.put("timestamp", System.currentTimeMillis());
|
|
||||||
|
|
||||||
session.sendMessage(new TextMessage(pong.toJSONString()));
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("发送心跳响应失败: sessionId={}, error={}", session.getId(), e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从路径中提取deviceSn
|
|
||||||
* 路径格式: /ws/control/{deviceSn}
|
|
||||||
*/
|
|
||||||
private String extractDeviceSn(String path) {
|
|
||||||
if (path == null) return null;
|
|
||||||
|
|
||||||
// 移除末尾的斜杠
|
|
||||||
if (path.endsWith("/")) {
|
|
||||||
path = path.substring(0, path.length() - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 提取最后一段作为deviceSn
|
|
||||||
int lastSlash = path.lastIndexOf('/');
|
|
||||||
if (lastSlash >= 0 && lastSlash < path.length() - 1) {
|
|
||||||
return path.substring(lastSlash + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取活跃连接数
|
|
||||||
*/
|
|
||||||
public int getActiveConnectionCount() {
|
|
||||||
return activeSessions.size();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+5
-6
@@ -12,8 +12,8 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import javax.annotation.PreDestroy;
|
import jakarta.annotation.PreDestroy;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
@@ -411,8 +411,7 @@ public class DeviceMessageHandler {
|
|||||||
alarmDataService.saveMsgAlarmData(deviceSn, msgAlarmData);
|
alarmDataService.saveMsgAlarmData(deviceSn, msgAlarmData);
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}",
|
//log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}",deviceSn, timestamp, droneData.keySet());
|
||||||
deviceSn, timestamp, droneData.keySet());
|
|
||||||
|
|
||||||
// 触发 msg_alarm 回调(用于一次性订阅)
|
// 触发 msg_alarm 回调(用于一次性订阅)
|
||||||
BiConsumer<String, JSONObject> msgAlarmCallback = msgAlarmCallbacks.get(deviceSn);
|
BiConsumer<String, JSONObject> msgAlarmCallback = msgAlarmCallbacks.get(deviceSn);
|
||||||
@@ -430,11 +429,11 @@ public class DeviceMessageHandler {
|
|||||||
// 推送到无人机专用的SSE连接
|
// 推送到无人机专用的SSE连接
|
||||||
if (sseEmitterManager != null) {
|
if (sseEmitterManager != null) {
|
||||||
try {
|
try {
|
||||||
log.info("【handleMsgAlarmEvent】准备推送无人机数据到SSE: deviceSn={}", deviceSn);
|
// log.info("【handleMsgAlarmEvent】准备推送无人机数据到SSE: deviceSn={}", deviceSn);
|
||||||
sseEmitterManager.getClass()
|
sseEmitterManager.getClass()
|
||||||
.getMethod("sendDroneDataUpdate", String.class, DroneRealtimeData.class)
|
.getMethod("sendDroneDataUpdate", String.class, DroneRealtimeData.class)
|
||||||
.invoke(sseEmitterManager, deviceSn, droneRealtimeData);
|
.invoke(sseEmitterManager, deviceSn, droneRealtimeData);
|
||||||
log.info("【handleMsgAlarmEvent】已推送无人机数据到专用SSE连接: deviceSn={}", deviceSn);
|
// log.info("【handleMsgAlarmEvent】已推送无人机数据到专用SSE连接: deviceSn={}", deviceSn);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("【handleMsgAlarmEvent】调用无人机SSE推送失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
log.error("【handleMsgAlarmEvent】调用无人机SSE推送失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e);
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-4
@@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
@@ -253,6 +253,7 @@ public class DeviceCommandManager {
|
|||||||
data.put("pitch", params.getIntValue("pitch"));
|
data.put("pitch", params.getIntValue("pitch"));
|
||||||
data.put("throttle", params.getIntValue("throttle"));
|
data.put("throttle", params.getIntValue("throttle"));
|
||||||
data.put("yaw", params.getIntValue("yaw"));
|
data.put("yaw", params.getIntValue("yaw"));
|
||||||
|
data.put("gimbal_pitch", params.getIntValue("gimbal_pitch"));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case "camera_screen_drag":
|
case "camera_screen_drag":
|
||||||
@@ -269,9 +270,15 @@ public class DeviceCommandManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
properties.put("method", method);
|
properties.put("method", method);
|
||||||
JSONObject dataWrapper = new JSONObject();
|
|
||||||
dataWrapper.put("data", data);
|
// 一键起飞命令需要 data.data 的嵌套结构,其他命令直接使用 data
|
||||||
properties.put("data", dataWrapper);
|
if ("takeoff_to_point".equals(method)) {
|
||||||
|
JSONObject dataWrapper = new JSONObject();
|
||||||
|
dataWrapper.put("data", data);
|
||||||
|
properties.put("data", dataWrapper);
|
||||||
|
} else {
|
||||||
|
properties.put("data", data);
|
||||||
|
}
|
||||||
|
|
||||||
return properties;
|
return properties;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ import okhttp3.*;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import javax.annotation.PreDestroy;
|
import jakarta.annotation.PreDestroy;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
package com.central.oauth.service.impl;
|
package com.central.oauth.service.impl;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import cn.hutool.core.util.StrUtil;
|
||||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.central.common.lock.DistributedLock;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
|
import com.central.common.lock.DistributedLock;
|
||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.service.impl.SuperServiceImpl;
|
import com.central.common.service.impl.SuperServiceImpl;
|
||||||
import com.central.oauth.mapper.ClientMapper;
|
import com.central.oauth.mapper.ClientMapper;
|
||||||
@@ -33,20 +34,34 @@ public class ClientServiceImpl extends SuperServiceImpl<ClientMapper, Client> im
|
|||||||
|
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
private final DistributedLock lock;
|
private final DistributedLock lock;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void saveClient(Client client) throws Exception {
|
public void saveClient(Client client) throws Exception {
|
||||||
client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr()));
|
String clientId = client.getClientId();
|
||||||
String clientId = client.getClientId();
|
if (StrUtil.isBlank(clientId)) {
|
||||||
if (client.getId() == null) {
|
throw new IllegalArgumentException("clientId不能为空");
|
||||||
client.setCreatorId(LoginUserContextHolder.getUser().getId());
|
}
|
||||||
}
|
|
||||||
super.saveOrUpdateIdempotency(client, lock
|
String rawSecret = client.getClientSecretStr();
|
||||||
, LOCK_KEY_CLIENTID+clientId
|
if (StrUtil.isBlank(rawSecret)) {
|
||||||
, new QueryWrapper<Client>().eq("client_id", clientId)
|
// 新增时未传密钥,默认使用clientId作为明文密钥(与初始化数据保持一致)
|
||||||
, clientId + "已存在");
|
if (client.getId() == null && StrUtil.isBlank(client.getClientSecret())) {
|
||||||
}
|
rawSecret = clientId;
|
||||||
|
client.setClientSecretStr(rawSecret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (StrUtil.isNotBlank(rawSecret)) {
|
||||||
|
client.setClientSecret(passwordEncoder.encode(rawSecret));
|
||||||
|
}
|
||||||
|
if (client.getId() == null) {
|
||||||
|
client.setCreatorId(LoginUserContextHolder.getUser().getId());
|
||||||
|
}
|
||||||
|
this.saveOrUpdateIdempotency(client, lock
|
||||||
|
, LOCK_KEY_CLIENTID+clientId
|
||||||
|
, new QueryWrapper<Client>().eq("client_id", clientId)
|
||||||
|
, clientId + "已存在");
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PageResult<Client> listClient(Map<String, Object> params, boolean isPage) {
|
public PageResult<Client> listClient(Map<String, Object> params, boolean isPage) {
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.central.oauth.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||||
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
|
import com.central.common.lock.DistributedLock;
|
||||||
|
import com.central.common.model.LoginAppUser;
|
||||||
|
import com.central.oauth.model.Client;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class ClientServiceImplTest {
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() {
|
||||||
|
LoginUserContextHolder.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void saveClient_新增未传密钥_默认使用clientId并加密() throws Exception {
|
||||||
|
LoginUserContextHolder.setUser(new LoginAppUser(100L, "tester", Collections.emptyList()));
|
||||||
|
|
||||||
|
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||||
|
TestableClientServiceImpl service = new TestableClientServiceImpl(passwordEncoder, null);
|
||||||
|
|
||||||
|
Client client = new Client();
|
||||||
|
client.setClientId("demoApp");
|
||||||
|
client.setClientSecretStr(null);
|
||||||
|
client.setClientSecret(null);
|
||||||
|
|
||||||
|
service.saveClient(client);
|
||||||
|
|
||||||
|
assertEquals(Long.valueOf(100L), client.getCreatorId());
|
||||||
|
assertEquals("demoApp", client.getClientSecretStr());
|
||||||
|
assertNotNull(client.getClientSecret());
|
||||||
|
assertTrue(passwordEncoder.matches("demoApp", client.getClientSecret()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void saveClient_更新未传密钥_不应触发加密避免覆盖() throws Exception {
|
||||||
|
LoginUserContextHolder.setUser(new LoginAppUser(100L, "tester", Collections.emptyList()));
|
||||||
|
|
||||||
|
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||||
|
TestableClientServiceImpl service = new TestableClientServiceImpl(passwordEncoder, null);
|
||||||
|
|
||||||
|
Client client = new Client();
|
||||||
|
client.setId(1L);
|
||||||
|
client.setClientId("demoApp");
|
||||||
|
client.setClientSecretStr(null);
|
||||||
|
client.setClientSecret(null);
|
||||||
|
|
||||||
|
service.saveClient(client);
|
||||||
|
|
||||||
|
assertNull(client.getClientSecretStr());
|
||||||
|
assertNull(client.getClientSecret());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void saveClient_clientId为空_应抛出异常() throws Exception {
|
||||||
|
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||||
|
TestableClientServiceImpl service = new TestableClientServiceImpl(passwordEncoder, null);
|
||||||
|
|
||||||
|
Client client = new Client();
|
||||||
|
client.setClientId(" ");
|
||||||
|
client.setClientSecretStr("abc");
|
||||||
|
|
||||||
|
service.saveClient(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class TestableClientServiceImpl extends ClientServiceImpl {
|
||||||
|
TestableClientServiceImpl(PasswordEncoder passwordEncoder, DistributedLock lock) {
|
||||||
|
super(passwordEncoder, lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean saveOrUpdateIdempotency(Client entity, DistributedLock lock, String lockKey,
|
||||||
|
Wrapper<Client> countWrapper, String msg) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -4,13 +4,19 @@
|
|||||||
* - 生产环境由网关/容器转发,此文件不生效
|
* - 生产环境由网关/容器转发,此文件不生效
|
||||||
*/
|
*/
|
||||||
const GATEWAY = process.env.GATEWAY_ORIGIN || 'http://192.168.2.214:9900';
|
const GATEWAY = process.env.GATEWAY_ORIGIN || 'http://192.168.2.214:9900';
|
||||||
|
// WebSocket 网关地址(与 HTTP 网关相同)
|
||||||
|
const WS_GATEWAY = GATEWAY.replace('http://', 'ws://').replace('https://', 'wss://');
|
||||||
// SRS流媒体服务器地址
|
// SRS流媒体服务器地址
|
||||||
const SRS_SERVER = process.env.SRS_SERVER || 'http://220.205.16.27:8024';
|
const SRS_SERVER = process.env.SRS_SERVER || 'http://220.205.16.27:8024';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
dev: {
|
dev: {
|
||||||
// 单一规则覆盖所有微服务前缀:/api-*
|
// API 请求代理(HTTP)
|
||||||
'/api-': { target: GATEWAY, changeOrigin: true },
|
// 注意:WebSocket 在 deviceControlWs.ts 中直接连接网关,不经过此代理
|
||||||
|
'/api-': {
|
||||||
|
target: GATEWAY,
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
// 3D模型CDN代理 - 解决跨域问题
|
// 3D模型CDN代理 - 解决跨域问题
|
||||||
'/goflymodel': {
|
'/goflymodel': {
|
||||||
target: 'https://minicdn.goflytec.com',
|
target: 'https://minicdn.goflytec.com',
|
||||||
@@ -31,7 +37,11 @@ export default {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
test: {
|
test: {
|
||||||
'/api-': { target: GATEWAY, changeOrigin: true },
|
'/api-': {
|
||||||
|
target: GATEWAY,
|
||||||
|
changeOrigin: true,
|
||||||
|
ws: true,
|
||||||
|
},
|
||||||
'/goflymodel': {
|
'/goflymodel': {
|
||||||
target: 'https://minicdn.goflytec.com',
|
target: 'https://minicdn.goflytec.com',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
@@ -39,7 +49,11 @@ export default {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
pre: {
|
pre: {
|
||||||
'/api-': { target: GATEWAY, changeOrigin: true },
|
'/api-': {
|
||||||
|
target: GATEWAY,
|
||||||
|
changeOrigin: true,
|
||||||
|
ws: true,
|
||||||
|
},
|
||||||
'/goflymodel': {
|
'/goflymodel': {
|
||||||
target: 'https://minicdn.goflytec.com',
|
target: 'https://minicdn.goflytec.com',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
|
|||||||
+930
-306
File diff suppressed because it is too large
Load Diff
+745
-804
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -92,7 +92,7 @@ const RightPanel: React.FC<RightPanelProps> = ({
|
|||||||
const dockData = realtimeData?.rawData?.dockData;
|
const dockData = realtimeData?.rawData?.dockData;
|
||||||
|
|
||||||
// 检查机库状态
|
// 检查机库状态
|
||||||
if (dockData?.mode_code === 1) {
|
if (dockData?.mode_code !== 0) {
|
||||||
message.warning('机库正在执行任务,无法起飞');
|
message.warning('机库正在执行任务,无法起飞');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
+129
-54
@@ -103,6 +103,10 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
|||||||
const clientSessionIdRef = useRef<string>(
|
const clientSessionIdRef = useRef<string>(
|
||||||
`client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
`client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
||||||
);
|
);
|
||||||
|
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
const reconnectAttemptsRef = useRef<number>(0);
|
||||||
|
const maxReconnectAttempts = 10;
|
||||||
|
const shouldReconnectRef = useRef<boolean>(true);
|
||||||
|
|
||||||
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
|
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
|
||||||
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
||||||
@@ -126,6 +130,15 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
|||||||
const disconnectSSE = useCallback(async (deviceSn?: string) => {
|
const disconnectSSE = useCallback(async (deviceSn?: string) => {
|
||||||
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
|
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
|
||||||
|
|
||||||
|
// 禁止自动重连
|
||||||
|
shouldReconnectRef.current = false;
|
||||||
|
|
||||||
|
// 清除重连定时器
|
||||||
|
if (reconnectTimerRef.current) {
|
||||||
|
clearTimeout(reconnectTimerRef.current);
|
||||||
|
reconnectTimerRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
// 1. 取消当前的 fetch 连接 (客户端主动断开)
|
// 1. 取消当前的 fetch 连接 (客户端主动断开)
|
||||||
if (abortControllerRef.current) {
|
if (abortControllerRef.current) {
|
||||||
abortControllerRef.current.abort();
|
abortControllerRef.current.abort();
|
||||||
@@ -140,36 +153,54 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
|||||||
|
|
||||||
setSSEConnected(false);
|
setSSEConnected(false);
|
||||||
currentDeviceSnRef.current = '';
|
currentDeviceSnRef.current = '';
|
||||||
console.log('SSE连接已断开');
|
reconnectAttemptsRef.current = 0;
|
||||||
|
console.log('[DeviceSSE] 连接已断开');
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 处理SSE事件
|
// 处理SSE事件
|
||||||
const handleSSEEvent = useCallback((eventName: string, data: string) => {
|
const handleSSEEvent = useCallback((eventName: string, data: string) => {
|
||||||
try {
|
try {
|
||||||
if (eventName === 'connected') {
|
if (eventName === 'connected') {
|
||||||
console.log('SSE连接确认:', data);
|
console.log('[DeviceSSE] 连接确认:', data);
|
||||||
|
setSSEConnected(true);
|
||||||
} else if (eventName === 'device-data-update') {
|
} else if (eventName === 'device-data-update') {
|
||||||
const parsedData = JSON.parse(data);
|
const parsedData = JSON.parse(data);
|
||||||
setRealtimeData(parsedData);
|
setRealtimeData(parsedData);
|
||||||
} else if (eventName === 'heartbeat') {
|
} else if (eventName === 'heartbeat') {
|
||||||
// 心跳
|
// 心跳 - 静默处理
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('解析SSE数据失败:', error);
|
// 静默处理解析错误
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 连接SSE
|
// 自动重连调度
|
||||||
const connectSSE = useCallback(async (deviceSn: string) => {
|
const scheduleReconnect = useCallback((deviceSn: string) => {
|
||||||
// 如果已经连接了同一个设备,先不断开,或者视需求而定。
|
if (!shouldReconnectRef.current) {
|
||||||
// 这里采取策略:如果 ID 变了,先断开旧的。
|
console.log('[DeviceSSE] 已禁用自动重连');
|
||||||
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
|
return;
|
||||||
await disconnectSSE(currentDeviceSnRef.current);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!deviceSn) return;
|
if (reconnectAttemptsRef.current >= maxReconnectAttempts) {
|
||||||
|
console.error('[DeviceSSE] 重连次数超限,停止重连');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
currentDeviceSnRef.current = deviceSn;
|
reconnectAttemptsRef.current++;
|
||||||
|
const delay = Math.min(2000 * Math.pow(1.5, reconnectAttemptsRef.current - 1), 30000);
|
||||||
|
console.log(`[DeviceSSE] ${delay}ms后重连 (${reconnectAttemptsRef.current}/${maxReconnectAttempts})`);
|
||||||
|
|
||||||
|
reconnectTimerRef.current = setTimeout(() => {
|
||||||
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
|
console.log('[DeviceSSE] 执行自动重连...');
|
||||||
|
doConnect(deviceSn);
|
||||||
|
}
|
||||||
|
}, delay);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 实际连接逻辑
|
||||||
|
const doConnect = useCallback(async (deviceSn: string) => {
|
||||||
|
if (!deviceSn) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const token = sessionStorage.getItem('access_token');
|
const token = sessionStorage.getItem('access_token');
|
||||||
@@ -178,7 +209,7 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
|||||||
const abortController = new AbortController();
|
const abortController = new AbortController();
|
||||||
abortControllerRef.current = abortController;
|
abortControllerRef.current = abortController;
|
||||||
|
|
||||||
console.log('正在建立SSE连接:', deviceSn);
|
console.log('[DeviceSSE] 正在建立连接:', deviceSn);
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -196,7 +227,8 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
|||||||
throw new Error(`SSE连接失败: ${response.status}`);
|
throw new Error(`SSE连接失败: ${response.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
setSSEConnected(true);
|
// 重连成功,重置计数
|
||||||
|
reconnectAttemptsRef.current = 0;
|
||||||
|
|
||||||
const reader = response.body?.getReader();
|
const reader = response.body?.getReader();
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
@@ -204,56 +236,92 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
|||||||
if (!reader) throw new Error('无法读取响应流');
|
if (!reader) throw new Error('无法读取响应流');
|
||||||
|
|
||||||
let buffer = '';
|
let buffer = '';
|
||||||
while (true) {
|
|
||||||
const { done, value } = await reader.read();
|
|
||||||
|
|
||||||
if (done) {
|
// 持续读取SSE流
|
||||||
console.log('SSE连接已关闭');
|
const readStream = async () => {
|
||||||
setSSEConnected(false);
|
try {
|
||||||
break;
|
while (true) {
|
||||||
}
|
const { done, value } = await reader.read();
|
||||||
|
|
||||||
const chunk = decoder.decode(value, { stream: true });
|
if (done) {
|
||||||
buffer += chunk;
|
console.log('[DeviceSSE] 流结束');
|
||||||
|
setSSEConnected(false);
|
||||||
const lines = buffer.split('\n');
|
// 流结束时尝试重连
|
||||||
buffer = lines.pop() || '';
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
|
scheduleReconnect(deviceSn);
|
||||||
let currentEvent = '';
|
}
|
||||||
let currentData = '';
|
break;
|
||||||
|
|
||||||
for (const line of lines) {
|
|
||||||
const trimmedLine = line.trim();
|
|
||||||
if (trimmedLine === '') {
|
|
||||||
if (currentEvent && currentData) {
|
|
||||||
handleSSEEvent(currentEvent, currentData);
|
|
||||||
}
|
}
|
||||||
currentEvent = '';
|
|
||||||
currentData = '';
|
buffer += decoder.decode(value, { stream: true });
|
||||||
} else if (line.startsWith('event:')) {
|
|
||||||
currentEvent = line.substring(6).trim();
|
const lines = buffer.split('\n');
|
||||||
} else if (line.startsWith('data:')) {
|
buffer = lines.pop() || '';
|
||||||
currentData = line.substring(5).trim();
|
|
||||||
|
let currentEvent = 'message';
|
||||||
|
let currentData = '';
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (line.startsWith('event:')) {
|
||||||
|
currentEvent = line.substring(6).trim();
|
||||||
|
} else if (line.startsWith('data:')) {
|
||||||
|
currentData = line.substring(5).trim();
|
||||||
|
} else if (line === '') {
|
||||||
|
if (currentData) {
|
||||||
|
handleSSEEvent(currentEvent, currentData);
|
||||||
|
}
|
||||||
|
currentEvent = 'message';
|
||||||
|
currentData = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error?.name === 'AbortError') {
|
||||||
|
console.log('[DeviceSSE] 连接被主动取消');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('[DeviceSSE] 读取流错误:', error);
|
||||||
|
setSSEConnected(false);
|
||||||
|
// 错误时尝试重连
|
||||||
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
|
scheduleReconnect(deviceSn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
|
readStream();
|
||||||
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
if (error.name === 'AbortError') {
|
if (error?.name === 'AbortError') {
|
||||||
|
console.log('[DeviceSSE] 连接被主动取消');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
console.error('SSE连接错误:', error);
|
console.error('[DeviceSSE] 连接失败:', error);
|
||||||
setSSEConnected(false);
|
setSSEConnected(false);
|
||||||
// message.error('连接实时数据失败'); // 避免频繁报错
|
// 连接失败时尝试重连
|
||||||
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
// 简单重连逻辑
|
scheduleReconnect(deviceSn);
|
||||||
setTimeout(() => {
|
}
|
||||||
if (currentDeviceSnRef.current === deviceSn && !abortControllerRef.current) {
|
|
||||||
// 只有在没有活跃连接时才重连
|
|
||||||
// connectSSE(deviceSn); // 慎用自动重连,可能导致死循环
|
|
||||||
}
|
|
||||||
}, 5000);
|
|
||||||
}
|
}
|
||||||
}, [disconnectSSE, handleSSEEvent]);
|
}, [handleSSEEvent, scheduleReconnect]);
|
||||||
|
|
||||||
|
// 连接SSE(对外暴露的方法)
|
||||||
|
const connectSSE = useCallback(async (deviceSn: string) => {
|
||||||
|
// 如果已经连接了同一个设备,先断开旧的
|
||||||
|
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
|
||||||
|
await disconnectSSE(currentDeviceSnRef.current);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!deviceSn) return;
|
||||||
|
|
||||||
|
// 重置状态
|
||||||
|
currentDeviceSnRef.current = deviceSn;
|
||||||
|
shouldReconnectRef.current = true; // 启用自动重连
|
||||||
|
reconnectAttemptsRef.current = 0;
|
||||||
|
|
||||||
|
// 执行连接
|
||||||
|
doConnect(deviceSn);
|
||||||
|
}, [disconnectSSE, doConnect]);
|
||||||
|
|
||||||
// 监听浏览器刷新/关闭事件 (beforeunload)
|
// 监听浏览器刷新/关闭事件 (beforeunload)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -274,6 +342,13 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
|||||||
// 组件卸载清理 (React Unmount)
|
// 组件卸载清理 (React Unmount)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
|
// 清理重连定时器
|
||||||
|
if (reconnectTimerRef.current) {
|
||||||
|
clearTimeout(reconnectTimerRef.current);
|
||||||
|
reconnectTimerRef.current = null;
|
||||||
|
}
|
||||||
|
shouldReconnectRef.current = false;
|
||||||
|
|
||||||
// 在组件卸载时,也尝试发送断开请求
|
// 在组件卸载时,也尝试发送断开请求
|
||||||
if (currentDeviceSnRef.current) {
|
if (currentDeviceSnRef.current) {
|
||||||
const token = sessionStorage.getItem('access_token');
|
const token = sessionStorage.getItem('access_token');
|
||||||
|
|||||||
+100
-22
@@ -103,6 +103,10 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
`drone_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
`drone_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
||||||
);
|
);
|
||||||
const dataReceivedRef = useRef<boolean>(false); // 用于跟踪是否已收到数据
|
const dataReceivedRef = useRef<boolean>(false); // 用于跟踪是否已收到数据
|
||||||
|
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
const reconnectAttemptsRef = useRef<number>(0);
|
||||||
|
const maxReconnectAttempts = 10;
|
||||||
|
const shouldReconnectRef = useRef<boolean>(true); // 是否应该自动重连
|
||||||
|
|
||||||
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
|
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
|
||||||
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
||||||
@@ -123,6 +127,15 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
const disconnectDroneSSE = useCallback(async (deviceSn?: string) => {
|
const disconnectDroneSSE = useCallback(async (deviceSn?: string) => {
|
||||||
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
|
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
|
||||||
|
|
||||||
|
// 禁止自动重连
|
||||||
|
shouldReconnectRef.current = false;
|
||||||
|
|
||||||
|
// 清除重连定时器
|
||||||
|
if (reconnectTimerRef.current) {
|
||||||
|
clearTimeout(reconnectTimerRef.current);
|
||||||
|
reconnectTimerRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
// 1. 取消当前的 fetch 连接 (客户端主动断开)
|
// 1. 取消当前的 fetch 连接 (客户端主动断开)
|
||||||
if (abortControllerRef.current) {
|
if (abortControllerRef.current) {
|
||||||
abortControllerRef.current.abort();
|
abortControllerRef.current.abort();
|
||||||
@@ -141,6 +154,7 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
setHasData(false);
|
setHasData(false);
|
||||||
dataReceivedRef.current = false;
|
dataReceivedRef.current = false;
|
||||||
currentDeviceSnRef.current = '';
|
currentDeviceSnRef.current = '';
|
||||||
|
reconnectAttemptsRef.current = 0;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 处理SSE事件(专门处理无人机数据)
|
// 处理SSE事件(专门处理无人机数据)
|
||||||
@@ -165,27 +179,39 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 连接无人机SSE
|
// 自动重连
|
||||||
const connectDroneSSE = useCallback(async (deviceSn: string) => {
|
const scheduleReconnect = useCallback((deviceSn: string) => {
|
||||||
// 如果已经连接了同一个设备,先断开旧的
|
if (!shouldReconnectRef.current) {
|
||||||
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
|
console.log('[DroneSSE] 已禁用自动重连');
|
||||||
await disconnectDroneSSE(currentDeviceSnRef.current);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!deviceSn) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 重置状态
|
if (reconnectAttemptsRef.current >= maxReconnectAttempts) {
|
||||||
setDroneData(null);
|
console.error('[DroneSSE] 重连次数超限,停止重连');
|
||||||
setHasData(false);
|
return;
|
||||||
dataReceivedRef.current = false;
|
}
|
||||||
currentDeviceSnRef.current = deviceSn;
|
|
||||||
|
reconnectAttemptsRef.current++;
|
||||||
|
const delay = Math.min(2000 * Math.pow(1.5, reconnectAttemptsRef.current - 1), 30000);
|
||||||
|
console.log(`[DroneSSE] ${delay}ms后重连 (${reconnectAttemptsRef.current}/${maxReconnectAttempts})`);
|
||||||
|
|
||||||
|
reconnectTimerRef.current = setTimeout(() => {
|
||||||
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
|
console.log('[DroneSSE] 执行自动重连...');
|
||||||
|
doConnect(deviceSn);
|
||||||
|
}
|
||||||
|
}, delay);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 实际连接逻辑
|
||||||
|
const doConnect = useCallback(async (deviceSn: string) => {
|
||||||
|
if (!deviceSn) return;
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const token = sessionStorage.getItem('access_token');
|
const token = sessionStorage.getItem('access_token');
|
||||||
const url = `/api-device/sse/drone-telemetry/${deviceSn}`; // 使用无人机SSE接口
|
const url = `/api-device/sse/drone-telemetry/${deviceSn}`;
|
||||||
|
|
||||||
// 创建 AbortController 用于取消请求
|
// 创建 AbortController 用于取消请求
|
||||||
const abortController = new AbortController();
|
const abortController = new AbortController();
|
||||||
@@ -208,6 +234,9 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
throw new Error(`无人机SSE连接失败: ${response.status}`);
|
throw new Error(`无人机SSE连接失败: ${response.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 重连成功,重置计数
|
||||||
|
reconnectAttemptsRef.current = 0;
|
||||||
|
|
||||||
// 读取SSE流
|
// 读取SSE流
|
||||||
const reader = response.body?.getReader();
|
const reader = response.body?.getReader();
|
||||||
const decoder = new TextDecoder();
|
const decoder = new TextDecoder();
|
||||||
@@ -225,7 +254,12 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
const { done, value } = await reader.read();
|
const { done, value } = await reader.read();
|
||||||
|
|
||||||
if (done) {
|
if (done) {
|
||||||
|
console.log('[DroneSSE] 流结束');
|
||||||
setSSEConnected(false);
|
setSSEConnected(false);
|
||||||
|
// 流结束时尝试重连
|
||||||
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
|
scheduleReconnect(deviceSn);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,7 +267,7 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
|
|
||||||
// 解析SSE消息
|
// 解析SSE消息
|
||||||
const lines = buffer.split('\n');
|
const lines = buffer.split('\n');
|
||||||
buffer = lines.pop() || ''; // 保留未完成的行
|
buffer = lines.pop() || '';
|
||||||
|
|
||||||
let eventName = 'message';
|
let eventName = 'message';
|
||||||
let data = '';
|
let data = '';
|
||||||
@@ -244,7 +278,6 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
} else if (line.startsWith('data:')) {
|
} else if (line.startsWith('data:')) {
|
||||||
data = line.substring(5).trim();
|
data = line.substring(5).trim();
|
||||||
} else if (line === '') {
|
} else if (line === '') {
|
||||||
// 空行表示消息结束
|
|
||||||
if (data) {
|
if (data) {
|
||||||
handleSSEEvent(eventName, data);
|
handleSSEEvent(eventName, data);
|
||||||
}
|
}
|
||||||
@@ -253,23 +286,62 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
|
// 如果是主动取消的,不重连
|
||||||
|
if (error?.name === 'AbortError') {
|
||||||
|
console.log('[DroneSSE] 连接被主动取消');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('[DroneSSE] 读取流错误:', error);
|
||||||
setSSEConnected(false);
|
setSSEConnected(false);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
// 错误时尝试重连
|
||||||
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
|
scheduleReconnect(deviceSn);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
readStream();
|
readStream();
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
|
// 如果是主动取消的,不重连
|
||||||
|
if (error?.name === 'AbortError') {
|
||||||
|
console.log('[DroneSSE] 连接被主动取消');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('[DroneSSE] 连接失败:', error);
|
||||||
setSSEConnected(false);
|
setSSEConnected(false);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
// 连接失败时尝试重连
|
||||||
if (error instanceof Error) {
|
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||||
message.error(`无人机SSE连接失败: ${error.message}`);
|
scheduleReconnect(deviceSn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [disconnectDroneSSE, handleSSEEvent]);
|
}, [handleSSEEvent, scheduleReconnect]);
|
||||||
|
|
||||||
|
// 连接无人机SSE
|
||||||
|
const connectDroneSSE = useCallback(async (deviceSn: string) => {
|
||||||
|
// 如果已经连接了同一个设备,先断开旧的
|
||||||
|
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
|
||||||
|
await disconnectDroneSSE(currentDeviceSnRef.current);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!deviceSn) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重置状态
|
||||||
|
setDroneData(null);
|
||||||
|
setHasData(false);
|
||||||
|
dataReceivedRef.current = false;
|
||||||
|
currentDeviceSnRef.current = deviceSn;
|
||||||
|
shouldReconnectRef.current = true; // 启用自动重连
|
||||||
|
reconnectAttemptsRef.current = 0;
|
||||||
|
|
||||||
|
// 执行连接
|
||||||
|
doConnect(deviceSn);
|
||||||
|
}, [disconnectDroneSSE, doConnect]);
|
||||||
|
|
||||||
// 重置无人机数据
|
// 重置无人机数据
|
||||||
const resetDroneData = useCallback(() => {
|
const resetDroneData = useCallback(() => {
|
||||||
@@ -281,6 +353,12 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
|||||||
// 组件卸载时自动断开连接
|
// 组件卸载时自动断开连接
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
|
// 清理重连定时器
|
||||||
|
if (reconnectTimerRef.current) {
|
||||||
|
clearTimeout(reconnectTimerRef.current);
|
||||||
|
reconnectTimerRef.current = null;
|
||||||
|
}
|
||||||
|
shouldReconnectRef.current = false;
|
||||||
if (currentDeviceSnRef.current) {
|
if (currentDeviceSnRef.current) {
|
||||||
disconnectDroneSSE(currentDeviceSnRef.current);
|
disconnectDroneSSE(currentDeviceSnRef.current);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,10 +15,28 @@ export interface AppFormProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const AppForm: React.FC<AppFormProps> = ({ open, title, initialValues, onOpenChange, onFinish }) => {
|
const AppForm: React.FC<AppFormProps> = ({ open, title, initialValues, onOpenChange, onFinish }) => {
|
||||||
const initial: Partial<AppFormValues> = initialValues || {};
|
const defaultInitial: Partial<AppFormValues> = {
|
||||||
if (initial.authorizedGrantTypes && !initial.authorizedGrantTypeCodes) {
|
autoapprove: 'true',
|
||||||
initial.authorizedGrantTypeCodes = (initial.authorizedGrantTypes || '').split(',').filter(Boolean);
|
accessTokenValiditySeconds: 18000,
|
||||||
|
refreshTokenValiditySeconds: 28800,
|
||||||
|
tokenFormat: 'reference',
|
||||||
|
authorizedGrantTypeCodes: [
|
||||||
|
'authorization_code',
|
||||||
|
'password',
|
||||||
|
'client_credentials',
|
||||||
|
'implicit',
|
||||||
|
'refresh_token',
|
||||||
|
'password_code',
|
||||||
|
'openId',
|
||||||
|
'mobile_password',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const initialFromProps: Partial<AppFormValues> = { ...(initialValues || {}) };
|
||||||
|
if (initialFromProps.authorizedGrantTypes && !initialFromProps.authorizedGrantTypeCodes) {
|
||||||
|
initialFromProps.authorizedGrantTypeCodes = (initialFromProps.authorizedGrantTypes || '').split(',').filter(Boolean);
|
||||||
}
|
}
|
||||||
|
const initial: Partial<AppFormValues> = { ...defaultInitial, ...initialFromProps };
|
||||||
return (
|
return (
|
||||||
<ModalForm<AppFormValues>
|
<ModalForm<AppFormValues>
|
||||||
title={title}
|
title={title}
|
||||||
@@ -37,7 +55,16 @@ const AppForm: React.FC<AppFormProps> = ({ open, title, initialValues, onOpenCha
|
|||||||
name="authorizedGrantTypeCodes"
|
name="authorizedGrantTypeCodes"
|
||||||
label="授权方式"
|
label="授权方式"
|
||||||
mode="multiple"
|
mode="multiple"
|
||||||
valueEnum={{ password: 'password', authorization_code: 'authorization_code', client_credentials: 'client_credentials', refresh_token: 'refresh_token' }}
|
valueEnum={{
|
||||||
|
authorization_code: '授权码模式',
|
||||||
|
password: '密码模式',
|
||||||
|
client_credentials: '客户端模式',
|
||||||
|
implicit: '简化模式',
|
||||||
|
refresh_token: '刷新Token',
|
||||||
|
password_code: '密码验证码模式',
|
||||||
|
openId: 'openId模式',
|
||||||
|
mobile_password: '手机号密码模式',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<ProFormSelect
|
<ProFormSelect
|
||||||
name="autoapprove"
|
name="autoapprove"
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
/**
|
/**
|
||||||
* 设备实时控制WebSocket服务
|
* 设备实时控制服务
|
||||||
* 用于高频率的云台控制和摇杆控制(5-10Hz)
|
* 用于云台控制和摇杆控制
|
||||||
|
* 使用HTTP API实现(替代WebSocket)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { request } from 'umi';
|
||||||
|
|
||||||
export interface StickControlData {
|
export interface StickControlData {
|
||||||
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
|
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
|
||||||
roll?: number;
|
roll?: number;
|
||||||
@@ -23,211 +26,90 @@ export interface GimbalControlData {
|
|||||||
locked?: boolean;
|
locked?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ControlMessage {
|
|
||||||
type: 'stick_control' | 'gimbal_control' | 'heartbeat';
|
|
||||||
deviceSn: string;
|
|
||||||
data?: StickControlData | GimbalControlData;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ControlResponse {
|
|
||||||
type: 'response' | 'error' | 'pong';
|
|
||||||
success?: boolean;
|
|
||||||
message?: string;
|
|
||||||
commandId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
type MessageHandler = (message: ControlResponse) => void;
|
|
||||||
type StatusHandler = (connected: boolean) => void;
|
type StatusHandler = (connected: boolean) => void;
|
||||||
|
|
||||||
class DeviceControlWebSocket {
|
class DeviceControlService {
|
||||||
private ws: WebSocket | null = null;
|
|
||||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
|
||||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
|
||||||
private reconnectAttempts = 0;
|
|
||||||
private maxReconnectAttempts = 5;
|
|
||||||
private reconnectDelay = 2000;
|
|
||||||
private heartbeatInterval = 15000;
|
|
||||||
|
|
||||||
private messageHandlers: MessageHandler[] = [];
|
|
||||||
private statusHandlers: StatusHandler[] = [];
|
private statusHandlers: StatusHandler[] = [];
|
||||||
|
|
||||||
private currentDeviceSn: string | null = null;
|
private currentDeviceSn: string | null = null;
|
||||||
private manualClose = false;
|
private isActive = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 连接WebSocket
|
* 连接设备(标记为活跃状态)
|
||||||
* @param deviceSn 设备SN
|
|
||||||
*/
|
*/
|
||||||
connect(deviceSn: string): void {
|
connect(deviceSn: string): void {
|
||||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
||||||
if (this.currentDeviceSn === deviceSn) {
|
|
||||||
console.log('[ControlWS] 已连接到该设备');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// 切换设备,先断开
|
|
||||||
this.disconnect();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.currentDeviceSn = deviceSn;
|
this.currentDeviceSn = deviceSn;
|
||||||
this.reconnectAttempts = 0;
|
this.isActive = true;
|
||||||
this.manualClose = false;
|
console.log('[ControlHTTP] 已连接设备:', deviceSn);
|
||||||
this.doConnect();
|
this.notifyStatusHandlers(true);
|
||||||
}
|
|
||||||
|
|
||||||
private doConnect(): void {
|
|
||||||
if (!this.currentDeviceSn) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
// WebSocket地址,通过网关代理到device-center
|
|
||||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
||||||
const host = window.location.host;
|
|
||||||
const url = `${protocol}//${host}/api-device/ws/control/${this.currentDeviceSn}`;
|
|
||||||
|
|
||||||
console.log('[ControlWS] 连接:', url);
|
|
||||||
this.ws = new WebSocket(url);
|
|
||||||
|
|
||||||
this.ws.onopen = () => {
|
|
||||||
console.log('[ControlWS] 连接成功');
|
|
||||||
this.reconnectAttempts = 0;
|
|
||||||
this.startHeartbeat();
|
|
||||||
this.notifyStatusHandlers(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
this.ws.onmessage = (event) => {
|
|
||||||
try {
|
|
||||||
const message = JSON.parse(event.data) as ControlResponse;
|
|
||||||
if (message.type !== 'pong') {
|
|
||||||
console.log('[ControlWS] 收到消息:', message);
|
|
||||||
}
|
|
||||||
this.notifyMessageHandlers(message);
|
|
||||||
} catch (e) {
|
|
||||||
console.warn('[ControlWS] 解析消息失败:', e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
this.ws.onclose = (event) => {
|
|
||||||
console.log('[ControlWS] 断开:', event.code, event.reason);
|
|
||||||
this.stopHeartbeat();
|
|
||||||
this.notifyStatusHandlers(false);
|
|
||||||
|
|
||||||
// 非手动关闭,尝试重连
|
|
||||||
if (!this.manualClose && this.currentDeviceSn) {
|
|
||||||
this.scheduleReconnect();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
this.ws.onerror = (error) => {
|
|
||||||
console.error('[ControlWS] 错误:', error);
|
|
||||||
};
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[ControlWS] 创建失败:', e);
|
|
||||||
this.scheduleReconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private scheduleReconnect(): void {
|
|
||||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
||||||
console.error('[ControlWS] 重连次数超限,停止重连');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.reconnectAttempts++;
|
|
||||||
const delay = this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1);
|
|
||||||
console.log(`[ControlWS] ${delay}ms后重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
|
|
||||||
|
|
||||||
this.reconnectTimer = setTimeout(() => {
|
|
||||||
this.doConnect();
|
|
||||||
}, delay);
|
|
||||||
}
|
|
||||||
|
|
||||||
private startHeartbeat(): void {
|
|
||||||
this.stopHeartbeat();
|
|
||||||
this.heartbeatTimer = setInterval(() => {
|
|
||||||
if (this.currentDeviceSn) {
|
|
||||||
this.send({ type: 'heartbeat', deviceSn: this.currentDeviceSn });
|
|
||||||
}
|
|
||||||
}, this.heartbeatInterval);
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopHeartbeat(): void {
|
|
||||||
if (this.heartbeatTimer) {
|
|
||||||
clearInterval(this.heartbeatTimer);
|
|
||||||
this.heartbeatTimer = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 断开连接
|
* 断开连接(标记为非活跃状态)
|
||||||
*/
|
*/
|
||||||
disconnect(): void {
|
disconnect(): void {
|
||||||
this.manualClose = true;
|
console.log('[ControlHTTP] 断开连接');
|
||||||
|
this.isActive = false;
|
||||||
this.currentDeviceSn = null;
|
this.currentDeviceSn = null;
|
||||||
this.stopHeartbeat();
|
this.notifyStatusHandlers(false);
|
||||||
|
|
||||||
if (this.reconnectTimer) {
|
|
||||||
clearTimeout(this.reconnectTimer);
|
|
||||||
this.reconnectTimer = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.ws) {
|
|
||||||
this.ws.close(1000, 'Manual disconnect');
|
|
||||||
this.ws = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送消息
|
|
||||||
*/
|
|
||||||
private send(message: ControlMessage): boolean {
|
|
||||||
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
||||||
console.warn('[ControlWS] 未连接,无法发送');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
this.ws.send(JSON.stringify(message));
|
|
||||||
return true;
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[ControlWS] 发送失败:', e);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发送摇杆控制指令
|
* 发送摇杆控制指令
|
||||||
*/
|
*/
|
||||||
sendStickControl(data: StickControlData): boolean {
|
sendStickControl(data: StickControlData): boolean {
|
||||||
if (!this.currentDeviceSn) {
|
if (!this.currentDeviceSn || !this.isActive) {
|
||||||
console.warn('[ControlWS] 未设置设备SN');
|
console.warn('[ControlHTTP] 未连接设备');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return this.send({
|
|
||||||
type: 'stick_control',
|
// 使用异步请求,不等待响应(提高控制频率)
|
||||||
deviceSn: this.currentDeviceSn,
|
request('/api-device/device/command/drc/stick', {
|
||||||
data,
|
method: 'POST',
|
||||||
|
data: {
|
||||||
|
deviceSn: this.currentDeviceSn,
|
||||||
|
roll: data.roll ?? 1024,
|
||||||
|
pitch: data.pitch ?? 1024,
|
||||||
|
throttle: data.throttle ?? 1024,
|
||||||
|
yaw: data.yaw ?? 1024,
|
||||||
|
gimbalPitch: 1024,
|
||||||
|
},
|
||||||
|
}).catch(e => {
|
||||||
|
console.warn('[ControlHTTP] 摇杆指令发送失败:', e);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发送云台控制指令
|
* 发送云台控制指令
|
||||||
*/
|
*/
|
||||||
sendGimbalControl(data: GimbalControlData): boolean {
|
sendGimbalControl(data: GimbalControlData): boolean {
|
||||||
if (!this.currentDeviceSn) {
|
if (!this.currentDeviceSn || !this.isActive) {
|
||||||
console.warn('[ControlWS] 未设置设备SN');
|
console.warn('[ControlHTTP] 未连接设备');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return this.send({
|
|
||||||
type: 'gimbal_control',
|
// 使用异步请求,不等待响应
|
||||||
deviceSn: this.currentDeviceSn,
|
request('/api-device/device/command/gimbal', {
|
||||||
data,
|
method: 'POST',
|
||||||
|
data: {
|
||||||
|
deviceSn: this.currentDeviceSn,
|
||||||
|
pitchSpeed: data.pitchSpeed ?? 0,
|
||||||
|
yawSpeed: data.yawSpeed ?? 0,
|
||||||
|
locked: data.locked ?? false,
|
||||||
|
},
|
||||||
|
}).catch(e => {
|
||||||
|
console.warn('[ControlHTTP] 云台指令发送失败:', e);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查是否已连接
|
* 检查是否已连接
|
||||||
*/
|
*/
|
||||||
isConnected(): boolean {
|
isConnected(): boolean {
|
||||||
return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
|
return this.isActive && this.currentDeviceSn !== null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -237,16 +119,6 @@ class DeviceControlWebSocket {
|
|||||||
return this.currentDeviceSn;
|
return this.currentDeviceSn;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 添加消息处理器
|
|
||||||
*/
|
|
||||||
onMessage(handler: MessageHandler): () => void {
|
|
||||||
this.messageHandlers.push(handler);
|
|
||||||
return () => {
|
|
||||||
this.messageHandlers = this.messageHandlers.filter(h => h !== handler);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 添加状态处理器
|
* 添加状态处理器
|
||||||
*/
|
*/
|
||||||
@@ -257,26 +129,16 @@ class DeviceControlWebSocket {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private notifyMessageHandlers(message: ControlResponse): void {
|
|
||||||
this.messageHandlers.forEach(handler => {
|
|
||||||
try {
|
|
||||||
handler(message);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[ControlWS] 消息处理器错误:', e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private notifyStatusHandlers(connected: boolean): void {
|
private notifyStatusHandlers(connected: boolean): void {
|
||||||
this.statusHandlers.forEach(handler => {
|
this.statusHandlers.forEach(handler => {
|
||||||
try {
|
try {
|
||||||
handler(connected);
|
handler(connected);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[ControlWS] 状态处理器错误:', e);
|
console.error('[ControlHTTP] 状态处理器错误:', e);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 导出单例
|
// 导出单例(保持与原WebSocket版本相同的接口名)
|
||||||
export const deviceControlWs = new DeviceControlWebSocket();
|
export const deviceControlWs = new DeviceControlService();
|
||||||
|
|||||||
Reference in New Issue
Block a user