diff --git a/.claude/settings.local.json b/.claude/settings.local.json index a02e96fe..fac9514a 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -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-web\\react-web-next\\src\\services\\deviceControlWs.ts\")", "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": [], "ask": [] diff --git a/zlt-business/device-center/3.png b/zlt-business/device-center/3.png index 76df4cc2..decb13ad 100644 Binary files a/zlt-business/device-center/3.png and b/zlt-business/device-center/3.png differ diff --git a/zlt-business/device-center/pom.xml b/zlt-business/device-center/pom.xml index c5cba8a3..02037ef6 100644 --- a/zlt-business/device-center/pom.xml +++ b/zlt-business/device-center/pom.xml @@ -107,16 +107,16 @@ 4.12.0 - + org.springframework.boot spring-boot-starter-websocket + - javax.servlet - javax.servlet-api - 4.0.1 - compile + jakarta.servlet + jakarta.servlet-api + provided diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java index da4a7c93..63edceda 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/DeviceCommandController.java @@ -336,8 +336,8 @@ public class DeviceCommandController { @Operation(summary = "DRC杆量控制") @PostMapping("/drc/stick") public Result stickControl(@RequestBody StickControlRequest request) { - log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}", - request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw()); + log.info("收到杆量控制命令: device={}, roll={}, pitch={}, throttle={}, yaw={}, gimbalPitch={}", + request.getDeviceSn(), request.getRoll(), request.getPitch(), request.getThrottle(), request.getYaw(), request.getGimbalPitch()); try { JSONObject params = new JSONObject(); @@ -345,6 +345,7 @@ public class DeviceCommandController { params.put("pitch", request.getPitch() != null ? request.getPitch() : 1024); params.put("throttle", request.getThrottle() != null ? request.getThrottle() : 1024); params.put("yaw", request.getYaw() != null ? request.getYaw() : 1024); + params.put("gimbal_pitch", request.getGimbalPitch() != null ? request.getGimbalPitch() : 1024); String commandId = commandManager.sendCommand( request.getDeviceSn(), @@ -461,6 +462,8 @@ public class DeviceCommandController { private Integer throttle; /** 偏航通道(624-1424,1024为中值) */ private Integer yaw; + /** 云台俯仰(624-1424,1024为中值) */ + private Integer gimbalPitch; } /** diff --git a/zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java b/zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java index b2f8081a..994462fc 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java +++ b/zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java @@ -16,7 +16,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/zlt-business/device-center/src/main/java/com/central/device/service/DeviceAlarmDataService.java b/zlt-business/device-center/src/main/java/com/central/device/service/DeviceAlarmDataService.java index a3b90b60..9d8c294a 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/service/DeviceAlarmDataService.java +++ b/zlt-business/device-center/src/main/java/com/central/device/service/DeviceAlarmDataService.java @@ -6,7 +6,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.util.concurrent.TimeUnit; /** diff --git a/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java b/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java index d2e167bd..a90a8238 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java +++ b/zlt-business/device-center/src/main/java/com/central/device/sse/manager/SseEmitterManager.java @@ -11,7 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; @@ -464,8 +464,7 @@ public class SseEmitterManager { .filter(w -> deviceSn.equals(w.getDeviceSn()) && Boolean.TRUE.equals(w.getIsDroneTelemetry())) .count(); - log.info("【无人机数据推送】deviceSn={}, 无人机SSE连接数={}, 总连接数={}", - deviceSn, droneConnectionCount, emitters.size()); + // log.info("【无人机数据推送】deviceSn={}, 无人机SSE连接数={}, 总连接数={}",deviceSn, droneConnectionCount, emitters.size()); if (droneConnectionCount == 0) { log.warn("【无人机数据推送】没有找到无人机SSE连接: deviceSn={}", deviceSn); @@ -488,7 +487,7 @@ public class SseEmitterManager { .id("drone-" + System.currentTimeMillis()); wrapper.getEmitter().send(event); - log.info("✅ 发送无人机数据更新成功: session={}, deviceSn={}", sessionId, deviceSn); + // log.info("✅ 发送无人机数据更新成功: session={}, deviceSn={}", sessionId, deviceSn); } catch (Exception e) { log.warn("发送无人机数据更新失败,连接可能已关闭: session={}, deviceSn={}, error={}", sessionId, deviceSn, e.getMessage()); diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java index 3f4b83c9..1da59751 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/client/JetLinksWebSocketClient.java @@ -16,8 +16,8 @@ import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import org.springframework.web.socket.handler.TextWebSocketHandler; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import java.util.HashSet; import java.util.Set; import java.util.UUID; @@ -211,7 +211,7 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler { */ private void handleCommandResponseMessage(JSONObject json) { String topic = json.getString("topic"); - String requestId = json.getString("id"); + String requestId = json.getString("requestId"); String deviceSn = extractDeviceSn(topic); log.info("收到命令响应: topic={}, requestId={}, deviceSn={}, json={}", topic, requestId, deviceSn, json.toJSONString()); diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/config/DeviceControlWebSocketConfig.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/config/DeviceControlWebSocketConfig.java deleted file mode 100644 index 7f9d2a19..00000000 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/config/DeviceControlWebSocketConfig.java +++ /dev/null @@ -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("*"); // 生产环境应配置具体域名 - } -} diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceControlWebSocketHandler.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceControlWebSocketHandler.java deleted file mode 100644 index 5e7e2960..00000000 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceControlWebSocketHandler.java +++ /dev/null @@ -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 activeSessions = new ConcurrentHashMap<>(); - - /** - * 会话对应的设备SN: sessionId -> deviceSn - */ - private final Map 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(); - } -} diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java index 98bc2afd..ce8e86ef 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/handler/DeviceMessageHandler.java @@ -12,8 +12,8 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -411,8 +411,7 @@ public class DeviceMessageHandler { alarmDataService.saveMsgAlarmData(deviceSn, msgAlarmData); } - log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}", - deviceSn, timestamp, droneData.keySet()); + //log.info("处理 msg_alarm 事件: deviceSn={}, timestamp={}, droneData字段: {}",deviceSn, timestamp, droneData.keySet()); // 触发 msg_alarm 回调(用于一次性订阅) BiConsumer msgAlarmCallback = msgAlarmCallbacks.get(deviceSn); @@ -430,11 +429,11 @@ public class DeviceMessageHandler { // 推送到无人机专用的SSE连接 if (sseEmitterManager != null) { try { - log.info("【handleMsgAlarmEvent】准备推送无人机数据到SSE: deviceSn={}", deviceSn); + // log.info("【handleMsgAlarmEvent】准备推送无人机数据到SSE: deviceSn={}", deviceSn); sseEmitterManager.getClass() .getMethod("sendDroneDataUpdate", String.class, DroneRealtimeData.class) .invoke(sseEmitterManager, deviceSn, droneRealtimeData); - log.info("【handleMsgAlarmEvent】已推送无人机数据到专用SSE连接: deviceSn={}", deviceSn); + // log.info("【handleMsgAlarmEvent】已推送无人机数据到专用SSE连接: deviceSn={}", deviceSn); } catch (Exception e) { log.error("【handleMsgAlarmEvent】调用无人机SSE推送失败: deviceSn={}, error={}", deviceSn, e.getMessage(), e); } diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java index 3b3f272d..88b51070 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/DeviceCommandManager.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.Optional; import java.util.UUID; import java.util.concurrent.*; @@ -253,6 +253,7 @@ public class DeviceCommandManager { data.put("pitch", params.getIntValue("pitch")); data.put("throttle", params.getIntValue("throttle")); data.put("yaw", params.getIntValue("yaw")); + data.put("gimbal_pitch", params.getIntValue("gimbal_pitch")); break; case "camera_screen_drag": @@ -269,9 +270,15 @@ public class DeviceCommandManager { } properties.put("method", method); - JSONObject dataWrapper = new JSONObject(); - dataWrapper.put("data", data); - properties.put("data", dataWrapper); + + // 一键起飞命令需要 data.data 的嵌套结构,其他命令直接使用 data + 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; } diff --git a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/TokenManager.java b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/TokenManager.java index 29ce90a2..f517bfaa 100644 --- a/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/TokenManager.java +++ b/zlt-business/device-center/src/main/java/com/central/device/websocket/manager/TokenManager.java @@ -8,7 +8,7 @@ import okhttp3.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.annotation.PreDestroy; +import jakarta.annotation.PreDestroy; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java index 4ba7a8e9..0577929c 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java @@ -1,10 +1,11 @@ -package com.central.oauth.service.impl; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.central.common.context.LoginUserContextHolder; -import com.central.common.lock.DistributedLock; +package com.central.oauth.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.context.LoginUserContextHolder; +import com.central.common.lock.DistributedLock; import com.central.common.model.PageResult; import com.central.common.service.impl.SuperServiceImpl; import com.central.oauth.mapper.ClientMapper; @@ -33,20 +34,34 @@ public class ClientServiceImpl extends SuperServiceImpl im private final PasswordEncoder passwordEncoder; - private final DistributedLock lock; - - @Override - public void saveClient(Client client) throws Exception { - client.setClientSecret(passwordEncoder.encode(client.getClientSecretStr())); - String clientId = client.getClientId(); - if (client.getId() == null) { - client.setCreatorId(LoginUserContextHolder.getUser().getId()); - } - super.saveOrUpdateIdempotency(client, lock - , LOCK_KEY_CLIENTID+clientId - , new QueryWrapper().eq("client_id", clientId) - , clientId + "已存在"); - } + private final DistributedLock lock; + + @Override + public void saveClient(Client client) throws Exception { + String clientId = client.getClientId(); + if (StrUtil.isBlank(clientId)) { + throw new IllegalArgumentException("clientId不能为空"); + } + + String rawSecret = client.getClientSecretStr(); + if (StrUtil.isBlank(rawSecret)) { + // 新增时未传密钥,默认使用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().eq("client_id", clientId) + , clientId + "已存在"); + } @Override public PageResult listClient(Map params, boolean isPage) { diff --git a/zlt-uaa/src/test/java/com/central/oauth/service/impl/ClientServiceImplTest.java b/zlt-uaa/src/test/java/com/central/oauth/service/impl/ClientServiceImplTest.java new file mode 100644 index 00000000..f5f47d51 --- /dev/null +++ b/zlt-uaa/src/test/java/com/central/oauth/service/impl/ClientServiceImplTest.java @@ -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 countWrapper, String msg) { + return true; + } + } +} + diff --git a/zlt-web/react-web-next/config/proxy.ts b/zlt-web/react-web-next/config/proxy.ts index d4e57076..97cc1df4 100644 --- a/zlt-web/react-web-next/config/proxy.ts +++ b/zlt-web/react-web-next/config/proxy.ts @@ -4,13 +4,19 @@ * - 生产环境由网关/容器转发,此文件不生效 */ 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流媒体服务器地址 const SRS_SERVER = process.env.SRS_SERVER || 'http://220.205.16.27:8024'; export default { dev: { - // 单一规则覆盖所有微服务前缀:/api-* - '/api-': { target: GATEWAY, changeOrigin: true }, + // API 请求代理(HTTP) + // 注意:WebSocket 在 deviceControlWs.ts 中直接连接网关,不经过此代理 + '/api-': { + target: GATEWAY, + changeOrigin: true, + }, // 3D模型CDN代理 - 解决跨域问题 '/goflymodel': { target: 'https://minicdn.goflytec.com', @@ -31,7 +37,11 @@ export default { }, }, test: { - '/api-': { target: GATEWAY, changeOrigin: true }, + '/api-': { + target: GATEWAY, + changeOrigin: true, + ws: true, + }, '/goflymodel': { target: 'https://minicdn.goflytec.com', changeOrigin: true, @@ -39,7 +49,11 @@ export default { }, }, pre: { - '/api-': { target: GATEWAY, changeOrigin: true }, + '/api-': { + target: GATEWAY, + changeOrigin: true, + ws: true, + }, '/goflymodel': { target: 'https://minicdn.goflytec.com', changeOrigin: true, diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.less b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.less index 764f5710..6a89cc2e 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.less +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.less @@ -1,27 +1,70 @@ @import '~antd/lib/style/themes/default.less'; -@cyan: #00f0ff; -@bg-dark: rgba(10, 20, 30, 0.95); -@border-color: rgba(0, 240, 255, 0.3); +// 主题色 +@primary: #00d4ff; +@primary-dark: #0099cc; +@accent: #00ff88; +@danger: #ff4757; +@warning: #ffa502; +@bg-dark: rgba(8, 15, 25, 0.95); +@bg-glass: rgba(15, 25, 40, 0.85); +@border-glow: rgba(0, 212, 255, 0.3); +@text-primary: #ffffff; +@text-secondary: rgba(255, 255, 255, 0.7); +@text-muted: rgba(255, 255, 255, 0.5); -.leftPanel { +// 玻璃拟态效果 +.glass-effect { + background: @bg-glass; + backdrop-filter: blur(12px); + border: 1px solid @border-glow; +} + +// 悬浮驾驶舱容器 +.controlPanelContainer { position: absolute; - top: 64px; - left: 0; - bottom: 0; - width: 400px; - background: @bg-dark; - backdrop-filter: blur(20px); - border-right: 1px solid @border-color; + left: 20px; + top: 80px; + width: 820px; + height: 520px; + z-index: 999; display: flex; flex-direction: column; - transform: translateX(-100%); - transition: transform 0.4s cubic-bezier(0.2, 0.8, 0.2, 1); - z-index: 900; - box-shadow: 10px 0 30px rgba(0, 0, 0, 0.5); + opacity: 0; + visibility: hidden; + pointer-events: none; + border-radius: 16px; + overflow: hidden; + box-shadow: + 0 25px 80px rgba(0, 0, 0, 0.6), + 0 0 40px rgba(0, 212, 255, 0.1), + inset 0 1px 0 rgba(255, 255, 255, 0.05); + will-change: transform; &.visible { - transform: translateX(0); + opacity: 1; + visibility: visible; + pointer-events: auto; + transition: opacity 0.3s ease, visibility 0.3s ease; + } + + // 放大模式 + &.large { + position: fixed; + top: 50%; + left: 50%; + right: auto; + bottom: auto; + transform: translate(-50%, -50%) !important; + width: 90vw; + height: 85vh; + max-width: 1600px; + max-height: 900px; + z-index: 1001; + + .videoLayer { + border-radius: 16px; + } } // 全屏模式 @@ -31,353 +74,918 @@ left: 0; right: 0; bottom: 0; - width: 100%; - height: 100%; - z-index: 9999; - transform: none; + width: 100vw !important; + height: 100vh !important; + max-width: none; + max-height: none; + border-radius: 0; + transform: none !important; - .videoContainer { - flex: 1; - aspect-ratio: unset; + .videoLayer { + border-radius: 0; + top: 0; } - .header, .flightDashboard, .controlsContent { - display: none; + .topBar { + border-radius: 0; } } - &::after { - content: ''; + // 视频层 + .videoLayer { position: absolute; top: 0; + left: 0; right: 0; bottom: 0; - width: 1px; - background: linear-gradient(180deg, transparent, @cyan, transparent); - box-shadow: 0 0 10px @cyan; - } - - .header { - padding: 12px 16px; - display: flex; - justify-content: space-between; - align-items: center; - border-bottom: 1px solid rgba(255, 255, 255, 0.1); - background: rgba(0, 240, 255, 0.05); - - .title { - font-size: 14px; - font-weight: 700; - color: #fff; - display: flex; - align-items: center; - gap: 8px; - - .liveTag { - font-size: 10px; - background: #ff4d4f; - padding: 1px 6px; - border-radius: 2px; - animation: blink 2s infinite; - } - } - - .closeBtn { - background: none; - border: 1px solid rgba(255, 255, 255, 0.2); - color: rgba(255, 255, 255, 0.6); - width: 24px; - height: 24px; - display: flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: all 0.3s; - &:hover { border-color: #ff4d4f; color: #ff4d4f; } - } - } - - .videoContainer { - width: 100%; - aspect-ratio: 16/9; - background: #000; - position: relative; - border-bottom: 1px solid @border-color; + border-radius: 16px; overflow: hidden; + background: linear-gradient(135deg, #0a1520 0%, #0d1a28 50%, #051015 100%); + + video { + width: 100%; + height: 100%; + object-fit: cover; + } + + // 扫描线效果 + &::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: repeating-linear-gradient( + 0deg, + transparent, + transparent 2px, + rgba(0, 0, 0, 0.03) 2px, + rgba(0, 0, 0, 0.03) 4px + ); + pointer-events: none; + z-index: 1; + } + + // 边缘暗角 + &::after { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: radial-gradient(ellipse at center, transparent 40%, rgba(0, 0, 0, 0.4) 100%); + pointer-events: none; + z-index: 2; + } .videoPlaceholder { width: 100%; height: 100%; display: flex; - flex-direction: column; align-items: center; justify-content: center; - color: rgba(0, 240, 255, 0.5); - background: radial-gradient(circle at center, rgba(0, 40, 60, 0.5) 0%, #000 100%); - background-image: linear-gradient(rgba(0, 240, 255, 0.1) 1px, transparent 1px), - linear-gradient(90deg, rgba(0, 240, 255, 0.1) 1px, transparent 1px); - background-size: 20px 20px; - .icon { font-size: 48px; margin-bottom: 12px; filter: drop-shadow(0 0 10px @cyan); } - } + background: radial-gradient(ellipse at center, rgba(0, 50, 70, 0.5) 0%, transparent 70%); - // 简化的HUD样式 - .hudTopLeft { - position: absolute; - top: 8px; - left: 8px; - font-size: 11px; - font-family: 'Consolas', monospace; - pointer-events: none; + .placeholderContent { + display: flex; + flex-direction: column; + align-items: center; + gap: 16px; - .statusLine { - color: rgba(255, 255, 255, 0.9); - text-shadow: 0 0 4px rgba(0, 0, 0, 0.8); - margin-bottom: 2px; + .icon { + font-size: 64px; + color: @primary; + filter: drop-shadow(0 0 20px @primary); + animation: pulse 2s ease-in-out infinite; + } + + span { + font-size: 16px; + color: @text-secondary; + letter-spacing: 2px; + } + + .loadingDots { + display: flex; + gap: 8px; + + span { + width: 8px; + height: 8px; + background: @primary; + border-radius: 50%; + animation: dotPulse 1.4s ease-in-out infinite; + + &:nth-child(2) { animation-delay: 0.2s; } + &:nth-child(3) { animation-delay: 0.4s; } + } + } } } - .statusOk { color: #00ff88; } - .statusErr { color: #ff4444; } - - .hudTopRight { + // 视频控制按钮 + .videoControls { position: absolute; - top: 8px; - right: 8px; - text-align: right; - font-size: 14px; - font-family: 'Consolas', monospace; - font-weight: bold; - text-shadow: 0 0 4px rgba(0, 0, 0, 0.8); - pointer-events: none; - - span { - display: block; - } - } - - .hudBottom { - position: absolute; - bottom: 8px; - left: 50%; - transform: translateX(-50%); - display: flex; - gap: 16px; - font-size: 11px; - font-family: 'Consolas', monospace; - color: rgba(255, 255, 255, 0.85); - text-shadow: 0 0 4px rgba(0, 0, 0, 0.8); - background: rgba(0, 0, 0, 0.4); - padding: 4px 12px; - border-radius: 4px; - pointer-events: none; - } - - .hudBottomLeft { - position: absolute; - bottom: 8px; - left: 8px; - font-size: 10px; - font-family: 'Consolas', monospace; - color: rgba(0, 255, 255, 0.7); - text-shadow: 0 0 4px rgba(0, 0, 0, 0.8); - pointer-events: none; - } - - // 浮动控制按钮 - .floatingControls { - position: absolute; - top: 50%; - right: 8px; - transform: translateY(-50%); + top: 56px; + right: 16px; display: flex; flex-direction: column; gap: 8px; - } + z-index: 20; + pointer-events: auto; - .floatBtn { - width: 36px; - height: 36px; - border-radius: 50%; - background: rgba(0, 0, 0, 0.6); - border: 1px solid rgba(255, 255, 255, 0.3); - color: #fff; - cursor: pointer; + .videoBtn { + width: 36px; + height: 36px; + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.2); + background: rgba(0, 0, 0, 0.5); + backdrop-filter: blur(8px); + color: @text-primary; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + transition: all 0.2s; + + &:hover { + background: rgba(0, 212, 255, 0.2); + border-color: @primary; + color: @primary; + transform: scale(1.05); + } + } + } + } + + // UI 覆盖层 + .uiOverlay { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 10; + pointer-events: none; + } + + // 顶部栏 + .topBar { + position: absolute; + top: 0; + left: 0; + right: 0; + height: 48px; + display: flex; + justify-content: space-between; + align-items: center; + padding: 0 16px; + background: linear-gradient(180deg, rgba(0, 0, 0, 0.8) 0%, transparent 100%); + pointer-events: auto; + cursor: move; + z-index: 20; + border-radius: 16px 16px 0 0; + + .topLeft { display: flex; align-items: center; - justify-content: center; - font-size: 16px; - transition: all 0.2s; + gap: 16px; - &:hover { - background: rgba(0, 240, 255, 0.3); - border-color: @cyan; - color: @cyan; - transform: scale(1.1); + .modeTag { + display: flex; + align-items: center; + gap: 8px; + background: rgba(0, 212, 255, 0.15); + border: 1px solid rgba(0, 212, 255, 0.4); + color: @primary; + padding: 6px 14px; + border-radius: 20px; + font-size: 12px; + font-weight: 600; + letter-spacing: 1px; + user-select: none; + + .modeDot { + width: 8px; + height: 8px; + border-radius: 50%; + background: @accent; + box-shadow: 0 0 10px @accent; + animation: blink 2s ease-in-out infinite; + } + + &.manual { + background: rgba(255, 165, 2, 0.15); + border-color: rgba(255, 165, 2, 0.5); + color: @warning; + + .modeDot { + background: @warning; + box-shadow: 0 0 10px @warning; + } + } } + .statusGroup { + display: flex; + gap: 12px; + + .statusItem { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: @text-secondary; + padding: 4px 10px; + background: rgba(0, 0, 0, 0.4); + border-radius: 12px; + user-select: none; + + .dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: @text-muted; + } + + .value { + font-weight: 600; + color: @text-primary; + font-family: 'Consolas', monospace; + } + + &.online { + .dot { background: @accent; box-shadow: 0 0 8px @accent; } + color: @accent; + } + + &.offline { + .dot { background: @danger; box-shadow: 0 0 8px @danger; } + color: @danger; + } + + &.good { + .value { color: @accent; } + } + + &.warn { + .value { color: @warning; } + } + + .fix { + color: @accent !important; + } + } + } + + // 键盘操控提示 + .keyboardHint { + display: flex; + align-items: center; + gap: 6px; + padding: 4px 12px; + background: rgba(0, 212, 255, 0.1); + border: 1px solid rgba(0, 212, 255, 0.3); + border-radius: 12px; + font-size: 12px; + color: @primary; + cursor: help; + user-select: none; + transition: all 0.2s; + + .keyIcon { + font-size: 14px; + } + + &:hover { + background: rgba(0, 212, 255, 0.2); + border-color: @primary; + } + + // 键盘已启用状态 + &.active { + background: rgba(0, 255, 136, 0.15); + border-color: @accent; + color: @accent; + animation: keyboardPulse 2s ease-in-out infinite; + + .keyIcon { + animation: keyBlink 1s ease-in-out infinite; + } + } + } + } + + .topRight { + display: flex; + align-items: center; + gap: 16px; + + .flightTime { + display: flex; + align-items: center; + gap: 6px; + padding: 6px 12px; + background: rgba(0, 0, 0, 0.4); + border-radius: 12px; + color: @warning; + font-size: 14px; + user-select: none; + + .time { + font-family: 'Consolas', monospace; + font-weight: bold; + letter-spacing: 1px; + } + } + + .batteryDisplay { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 12px; + background: rgba(0, 0, 0, 0.4); + border-radius: 12px; + user-select: none; + + .batteryIcon { + width: 32px; + height: 14px; + border: 2px solid @accent; + border-radius: 3px; + position: relative; + overflow: hidden; + + &::after { + content: ''; + position: absolute; + right: -5px; + top: 50%; + transform: translateY(-50%); + width: 3px; + height: 6px; + background: @accent; + border-radius: 0 2px 2px 0; + } + + .batteryLevel { + height: 100%; + background: linear-gradient(90deg, @accent, lighten(@accent, 10%)); + transition: width 0.3s; + } + } + + .batteryInfo { + display: flex; + flex-direction: column; + align-items: flex-end; + + .percent { + font-size: 14px; + font-weight: bold; + color: @accent; + font-family: 'Consolas', monospace; + line-height: 1; + } + + .voltage { + font-size: 10px; + color: @text-muted; + } + } + } + + .closeBtn { + width: 32px; + height: 32px; + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.15); + background: rgba(0, 0, 0, 0.4); + color: @text-primary; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s; + + &:hover { + background: @danger; + border-color: @danger; + box-shadow: 0 0 15px @danger; + transform: scale(1.05); + } + } + } + } + + // 中心HUD瞄准器 + .centerHUD { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + pointer-events: none; + + .crosshair { + position: relative; + width: 120px; + height: 80px; + + .horizontalLine { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 60px; + height: 1px; + background: linear-gradient(90deg, transparent, @accent, transparent); + } + + .verticalLine { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 1px; + height: 40px; + background: linear-gradient(180deg, transparent, @accent, transparent); + } + + .centerDot { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 6px; + height: 6px; + background: @danger; + border-radius: 50%; + box-shadow: 0 0 10px @danger, 0 0 20px rgba(255, 71, 87, 0.3); + } + + .cornerBracket { + position: absolute; + width: 16px; + height: 16px; + border: 2px solid @accent; + opacity: 0.6; + + &.topLeft { + top: 0; + left: 0; + border-right: none; + border-bottom: none; + } + + &.topRight { + top: 0; + right: 0; + border-left: none; + border-bottom: none; + } + + &.bottomLeft { + bottom: 0; + left: 0; + border-right: none; + border-top: none; + } + + &.bottomRight { + bottom: 0; + right: 0; + border-left: none; + border-top: none; + } + } + } + } + + // 左侧数据面板 + .leftDataPanel { + position: absolute; + left: 16px; + top: 50%; + transform: translateY(-50%); + pointer-events: none; + + .dataCard { + .glass-effect(); + padding: 16px; + border-radius: 12px; + min-width: 140px; + + .dataRow { + display: flex; + justify-content: space-between; + align-items: baseline; + padding: 6px 0; + + .label { + font-size: 11px; + color: @text-muted; + } + + .value { + font-size: 18px; + font-weight: bold; + color: @text-primary; + font-family: 'Consolas', monospace; + + .unit { + font-size: 11px; + color: @text-muted; + margin-left: 2px; + } + } + } + + .divider { + height: 1px; + background: linear-gradient(90deg, transparent, @border-glow, transparent); + margin: 8px 0; + } + } + } + + // 右侧数据面板 + .rightDataPanel { + position: absolute; + right: 16px; + top: 50%; + transform: translateY(-50%); + pointer-events: none; + + .dataCard { + .glass-effect(); + padding: 16px; + border-radius: 12px; + min-width: 140px; + + .dataRow { + display: flex; + justify-content: space-between; + align-items: baseline; + padding: 6px 0; + + .label { + font-size: 11px; + color: @text-muted; + } + + .value { + font-size: 18px; + font-weight: bold; + color: @text-primary; + font-family: 'Consolas', monospace; + + .unit { + font-size: 11px; + color: @text-muted; + margin-left: 2px; + } + } + } + + .divider { + height: 1px; + background: linear-gradient(90deg, transparent, @border-glow, transparent); + margin: 8px 0; + } + + .attitudeRow { + display: flex; + gap: 12px; + + .attItem { + display: flex; + flex-direction: column; + align-items: center; + + .attLabel { + font-size: 10px; + color: @primary; + font-weight: 600; + } + + .attValue { + font-size: 13px; + color: @text-primary; + font-family: 'Consolas', monospace; + } + } + } + } + } + + // 底部控制栏 + .bottomControls { + position: absolute; + bottom: 0; + left: 0; + right: 0; + height: 100px; + display: flex; + justify-content: space-between; + align-items: center; + padding: 0 20px 12px; + background: linear-gradient(0deg, rgba(0, 0, 0, 0.9) 0%, rgba(0, 0, 0, 0.6) 60%, transparent 100%); + pointer-events: auto; + + .quickActions { + display: flex; + gap: 8px; + + .actionBtn { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 4px; + width: 56px; + height: 56px; + background: rgba(0, 20, 40, 0.8); + border: 1px solid @border-glow; + border-radius: 12px; + color: @primary; + cursor: pointer; + transition: all 0.2s; + font-size: 18px; + + span { + font-size: 10px; + color: @text-muted; + } + + &:hover { + background: rgba(0, 212, 255, 0.15); + border-color: @primary; + transform: translateY(-2px); + box-shadow: 0 4px 20px rgba(0, 212, 255, 0.3); + + span { + color: @text-primary; + } + } + + &.danger { + border-color: rgba(255, 71, 87, 0.4); + color: @danger; + + &:hover { + background: rgba(255, 71, 87, 0.15); + border-color: @danger; + box-shadow: 0 4px 20px rgba(255, 71, 87, 0.3); + } + } + } + } + + // 中心信息区域 + .centerInfo { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + } + + // 控制按钮行(手动控制 + 速度切换) + .controlRow { + display: flex; + align-items: center; + gap: 12px; + } + + // 手动控制按钮 + .drcControlBtn { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 16px; + background: rgba(255, 165, 2, 0.15); + border: 1px solid rgba(255, 165, 2, 0.4); + border-radius: 20px; + color: @warning; + font-size: 12px; + cursor: pointer; + transition: all 0.2s; + white-space: nowrap; + + &:hover:not(:disabled) { + background: rgba(255, 165, 2, 0.25); + border-color: @warning; + box-shadow: 0 0 15px rgba(255, 165, 2, 0.3); + } + + &.active { + background: rgba(0, 255, 136, 0.2); + border-color: @accent; + color: @accent; + animation: drcPulse 2s ease-in-out infinite; + + &:hover:not(:disabled) { + background: rgba(0, 255, 136, 0.3); + box-shadow: 0 0 15px rgba(0, 255, 136, 0.4); + } + } + + &.disabled, &:disabled { opacity: 0.5; cursor: not-allowed; - } + background: rgba(0, 0, 0, 0.3); + border-color: rgba(255, 255, 255, 0.1); + color: @text-muted; - &.recording { - background: rgba(255, 0, 0, 0.6); - border-color: #ff4444; - animation: recordPulse 1s infinite; + &:hover { + box-shadow: none; + background: rgba(0, 0, 0, 0.3); + } } } - // 连接状态指示 - .connectionStatus { - position: absolute; - bottom: 8px; - right: 8px; + .coordsDisplay { + display: flex; + gap: 24px; + padding: 10px 20px; + background: rgba(0, 0, 0, 0.5); + border-radius: 20px; + border: 1px solid rgba(255, 255, 255, 0.1); + + .coord { + display: flex; + flex-direction: column; + align-items: center; + + .coordLabel { + font-size: 10px; + color: @text-muted; + text-transform: uppercase; + letter-spacing: 1px; + } + + .coordValue { + font-size: 13px; + color: @primary; + font-family: 'Consolas', monospace; + font-weight: 500; + } + } + } + + // 速度指示器 + .speedIndicator { display: flex; align-items: center; - font-size: 12px; + gap: 8px; + padding: 6px 14px; background: rgba(0, 0, 0, 0.5); - padding: 4px 8px; - border-radius: 4px; - } + border-radius: 16px; + border: 1px solid rgba(255, 255, 255, 0.1); + cursor: pointer; + transition: all 0.2s; - .hudOverlay { - position: absolute; - top: 10px; left: 10px; right: 10px; bottom: 10px; - pointer-events: none; - border: 1px solid rgba(0, 240, 255, 0.3); + &:hover { + background: rgba(0, 0, 0, 0.7); + border-color: @primary; + } - .crosshair { - position: absolute; - top: 50%; left: 50%; width: 20px; height: 20px; - border: 1px solid rgba(0, 255, 0, 0.5); - transform: translate(-50%, -50%); - &::before { content: ''; position: absolute; top: 9px; left: 0; width: 100%; height: 1px; background: rgba(0, 255, 0, 0.8); } - &::after { content: ''; position: absolute; left: 9px; top: 0; height: 100%; width: 1px; background: rgba(0, 255, 0, 0.8); } + .speedLabel { + font-size: 11px; + color: @text-muted; + text-transform: uppercase; + letter-spacing: 1px; + } + + .speedBars { + display: flex; + gap: 3px; + align-items: flex-end; + + .speedBar { + width: 6px; + height: 8px; + background: rgba(255, 255, 255, 0.2); + border-radius: 2px; + transition: all 0.2s; + + &:nth-child(1) { + height: 8px; + } + &:nth-child(2) { + height: 12px; + } + &:nth-child(3) { + height: 16px; + } + + &.active { + background: @accent; + box-shadow: 0 0 6px @accent; + } + } + } + + .speedText { + font-size: 12px; + font-weight: 600; + color: @accent; + min-width: 20px; + text-align: center; + } + + // 未进入DRC模式时的禁用状态 + &.disabled { + opacity: 0.5; + cursor: not-allowed; + + .speedBar.active { + background: @text-muted; + box-shadow: none; + } + + .speedText { + color: @text-muted; + } } } - } - // 飞行仪表盘 - 更紧凑 - .flightDashboard { - display: grid; - grid-template-columns: repeat(6, 1fr); - gap: 4px; - padding: 8px 12px; - background: rgba(0,0,0,0.2); - border-bottom: 1px solid rgba(255,255,255,0.05); + .cameraControls { + display: flex; + gap: 12px; - .dashItem { - background: rgba(255,255,255,0.05); - padding: 6px 4px; - border-radius: 4px; - text-align: center; - - .dashLabel { font-size: 9px; color: rgba(255,255,255,0.4); margin-bottom: 2px; } - .dashValue { font-size: 12px; font-weight: bold; color: #fff; font-family: 'Consolas', monospace; } - } - } - - .controlsContent { - flex: 1; - overflow-y: auto; - padding: 12px 16px; - - .controlGroup { - margin-bottom: 16px; - - .groupTitle { - font-size: 12px; - color: rgba(255, 255, 255, 0.5); - margin-bottom: 10px; + .cameraBtn { + width: 52px; + height: 52px; + border-radius: 50%; + background: rgba(0, 20, 40, 0.8); + border: 2px solid @primary; + color: @primary; + cursor: pointer; display: flex; align-items: center; - &::after { content: ''; flex: 1; height: 1px; background: rgba(255, 255, 255, 0.1); margin-left: 8px; } - } + justify-content: center; + font-size: 20px; + transition: all 0.2s; + box-shadow: 0 0 15px rgba(0, 212, 255, 0.2); - .flightActions { - display: grid; - grid-template-columns: 1fr 1fr 1fr 1fr; - gap: 6px; + &:hover:not(:disabled) { + transform: scale(1.1); + box-shadow: 0 0 25px rgba(0, 212, 255, 0.4); + background: rgba(0, 212, 255, 0.2); + } - button { - height: 32px; - font-size: 12px; - background: rgba(0, 240, 255, 0.1); - border: 1px solid rgba(0, 240, 255, 0.3); - color: @cyan; - cursor: pointer; - border-radius: 4px; - transition: all 0.2s; - &:hover { background: rgba(0, 240, 255, 0.2); } - &.danger { - background: rgba(255, 77, 79, 0.1); - border-color: rgba(255, 77, 79, 0.3); - color: #ff4d4f; - &:hover { background: rgba(255, 77, 79, 0.2); } + &.disabled, + &:disabled { + opacity: 0.6; + cursor: not-allowed; + transform: none !important; + } + + &.recordBtn { + border-color: @danger; + + .recordDot { + width: 20px; + height: 20px; + background: @danger; + border-radius: 4px; + transition: all 0.2s; } - } - } - // 键盘控制说明样式 - .keyboardHint { - background: rgba(0, 0, 0, 0.3); - border: 1px solid rgba(255, 255, 255, 0.1); - border-radius: 6px; - padding: 12px; - - .keyGroup { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 4px; - margin-bottom: 8px; - font-size: 11px; - color: rgba(255, 255, 255, 0.6); - - &:last-child { - margin-bottom: 0; + &:hover:not(:disabled) { + box-shadow: 0 0 25px rgba(255, 71, 87, 0.4); + background: rgba(255, 71, 87, 0.2); } - } - .keyLabel { - color: rgba(255, 255, 255, 0.4); - margin-right: 4px; - min-width: 36px; - } + &.recording { + background: rgba(255, 71, 87, 0.3); + animation: recordPulse 1.5s ease-in-out infinite; - kbd { - display: inline-block; - padding: 2px 6px; - font-size: 11px; - font-family: 'Consolas', monospace; - background: rgba(255, 255, 255, 0.1); - border: 1px solid rgba(255, 255, 255, 0.2); - border-radius: 3px; - color: #fff; - min-width: 20px; - text-align: center; - } - - .activeKeyDisplay { - margin-top: 8px; - padding-top: 8px; - border-top: 1px solid rgba(255, 255, 255, 0.1); - display: flex; - gap: 4px; - flex-wrap: wrap; - } - - .activeKey { - background: @cyan; - border-color: @cyan; - color: #000; - font-weight: bold; - box-shadow: 0 0 8px @cyan; - animation: keyGlow 0.3s ease; + .recordDot { + border-radius: 50%; + animation: recordBlink 1s ease-in-out infinite; + } + } } } } } + +} + +// 动画 +@keyframes pulse { + 0%, 100% { opacity: 0.6; transform: scale(1); } + 50% { opacity: 1; transform: scale(1.05); } +} + +@keyframes dotPulse { + 0%, 80%, 100% { transform: scale(0.6); opacity: 0.5; } + 40% { transform: scale(1); opacity: 1; } } @keyframes blink { @@ -386,11 +994,27 @@ } @keyframes recordPulse { - 0%, 100% { box-shadow: 0 0 0 0 rgba(255, 0, 0, 0.5); } - 50% { box-shadow: 0 0 10px 4px rgba(255, 0, 0, 0.3); } + 0% { box-shadow: 0 0 0 0 rgba(255, 71, 87, 0.6); } + 70% { box-shadow: 0 0 0 15px rgba(255, 71, 87, 0); } + 100% { box-shadow: 0 0 0 0 rgba(255, 71, 87, 0); } } -@keyframes keyGlow { - from { transform: scale(1.2); } - to { transform: scale(1); } +@keyframes recordBlink { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.3; } +} + +@keyframes drcPulse { + 0%, 100% { box-shadow: 0 0 0 0 rgba(0, 255, 136, 0.4); } + 50% { box-shadow: 0 0 15px 3px rgba(0, 255, 136, 0.3); } +} + +@keyframes keyboardPulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.8; } +} + +@keyframes keyBlink { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.5; } } diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx index a6ad58e1..b66cece8 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/LeftControlPanel.tsx @@ -5,20 +5,18 @@ import { StopOutlined, HomeOutlined, CameraOutlined, - CompassOutlined, - WifiOutlined, - LoadingOutlined, - PlayCircleOutlined, PauseCircleOutlined, - LinkOutlined, - DisconnectOutlined, CaretRightOutlined, FullscreenOutlined, FullscreenExitOutlined, + ExpandOutlined, + CompressOutlined, + LoadingOutlined, + ClockCircleOutlined, AimOutlined, - ThunderboltOutlined, + DisconnectOutlined, } from '@ant-design/icons'; -import { message, Tooltip, Modal, Tag } from 'antd'; +import { message, Modal, Tooltip, Spin } from 'antd'; import { deviceApi } from '@/services/device'; import { deviceControlWs } from '@/services/deviceControlWs'; import { useDroneSSE } from '../hooks/useDroneSSE'; @@ -30,22 +28,9 @@ interface LeftControlPanelProps { onClose: () => void; device: any; realtimeData: any; - /** 视频流完整地址(WHEP URL) */ videoStreamUrl?: string; } -// 飞行模式映射 -const FLIGHT_MODE_MAP: Record = { - 0: '待机', - 1: '起飞', - 2: '降落', - 3: '悬停', - 4: '航点飞行', - 5: '返航', - 6: '手动控制', - 7: '紧急制动', -}; - const LeftControlPanel: React.FC = ({ visible, onClose, @@ -55,858 +40,814 @@ const LeftControlPanel: React.FC = ({ }) => { const dockData = realtimeData?.rawData?.dockData; const rawDroneData = realtimeData?.rawData?.droneData; - - // 获取设备SN const deviceSn = device?.deviceSn; - // 【重要】使用独立的无人机SSE连接 - 必须在 flightData useMemo 之前定义 - const { - droneData, - sseConnected: droneSseConnected, - loading: droneSseLoading, - hasData: droneHasData, - connectDroneSSE, - disconnectDroneSSE, - resetDroneData, - } = useDroneSSE(); + const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE(); - // 从 droneData (独立SSE连接) 或 rawDroneData (props) 获取无人机实时飞行数据 - // 优先使用独立SSE连接的 droneData,因为它专门接收无人机遥测数据 const flightData = useMemo(() => { - // 优先使用独立SSE的droneData,其次使用rawDroneData - const effectiveDroneData = droneData || rawDroneData; - - // 获取云台payload数据 - 遍历查找带有 gimbal_pitch 的子对象 - let gimbalPayload: any = {}; - if (effectiveDroneData) { - // 常见的 payload 索引 - const payloadKeys = ['98-0-0', '39-0-0', '42-0-0', '43-0-0', '52-0-0', '53-0-0', '165-0-0']; - for (const key of payloadKeys) { - if (effectiveDroneData[key] && (effectiveDroneData[key].gimbal_pitch !== undefined || effectiveDroneData[key].gimbal_yaw !== undefined)) { - gimbalPayload = effectiveDroneData[key]; - break; - } - } - // 如果常见索引没找到,遍历所有数字格式的key - if (!gimbalPayload.gimbal_pitch && !gimbalPayload.gimbal_yaw) { - for (const key of Object.keys(effectiveDroneData)) { - if (/^\d+-\d+-\d+$/.test(key) && effectiveDroneData[key]?.gimbal_pitch !== undefined) { - gimbalPayload = effectiveDroneData[key]; - break; - } - } - } + const data = droneData || rawDroneData; + let gimbal: any = {}; + if (data) { + ['98-0-0','39-0-0','42-0-0','43-0-0','52-0-0','53-0-0'].some(k => { + if (data[k]?.gimbal_pitch !== undefined) { gimbal = data[k]; return true; } + return false; + }); } - // 使用 effectiveDroneData 获取所有飞行数据 - const pitch = effectiveDroneData?.attitude_pitch ?? 0; - const roll = effectiveDroneData?.attitude_roll ?? 0; - const yaw = effectiveDroneData?.attitude_head ?? 0; - const hSpeed = effectiveDroneData?.horizontal_speed ?? effectiveDroneData?.ground_speed ?? 0; - const vSpeed = effectiveDroneData?.vertical_speed ?? 0; - const altitude = effectiveDroneData?.height ?? effectiveDroneData?.elevation ?? realtimeData?.gps?.altitude ?? 0; - const distance = effectiveDroneData?.home_distance ?? 0; + // 获取电池数据 - 兼容多种数据结构 + // 1. 直接结构: battery.capacity_percent, battery.voltage + // 2. 数组结构: battery.batteries[0].capacity_percent, battery.batteries[0].voltage + // 3. 机库数据: drone_battery_maintenance_info.batteries[0] + let batteryPercent = 0; + let batteryVoltage = 0; - // GPS/RTK卫星数据 - const satellites = effectiveDroneData?.position_state?.gps_number ?? dockData?.position_state?.gps_number ?? 0; - const rtkSatellites = effectiveDroneData?.position_state?.rtk_number ?? dockData?.position_state?.rtk_number ?? 0; - const isFixed = effectiveDroneData?.position_state?.is_fixed ?? dockData?.position_state?.is_fixed ?? 0; - const rtkStatus = isFixed === 2 ? 'FIX' : (isFixed === 1 ? 'FLOAT' : (rtkSatellites > 0 ? 'FLOAT' : 'NONE')); + if (data?.battery?.capacity_percent !== undefined) { + batteryPercent = data.battery.capacity_percent; + batteryVoltage = data.battery.voltage ?? 0; + } else if (data?.battery?.batteries?.[0]) { + batteryPercent = data.battery.batteries[0].capacity_percent ?? 0; + batteryVoltage = data.battery.batteries[0].voltage ?? 0; + } else if (data?.drone_battery_maintenance_info?.batteries?.[0]) { + batteryPercent = data.drone_battery_maintenance_info.batteries[0].capacity_percent ?? 0; + batteryVoltage = data.drone_battery_maintenance_info.batteries[0].voltage ?? 0; + } - // 电池数据 - 支持两种结构:直接的battery对象 或 嵌套的batteries数组 - const batteryData = effectiveDroneData?.battery; - const batteryPercent = batteryData?.capacity_percent ?? realtimeData?.battery ?? 0; - // 电压可能在 battery.voltage 或 battery.batteries[0].voltage - const batteryVoltage = batteryData?.voltage ?? batteryData?.batteries?.[0]?.voltage ?? 0; - // 温度可能在 battery.temperature 或 battery.batteries[0].temperature - const batteryTemp = batteryData?.temperature ?? batteryData?.batteries?.[0]?.temperature ?? 0; - const remainFlightTime = batteryData?.remain_flight_time ?? 0; - - // 信号强度 - const signal = dockData?.wireless_link?.dongle_number ?? dockData?.sdr?.upward_quality ?? 0; - - // 飞行模式 - const modeCode = effectiveDroneData?.mode_code ?? 0; - const flightMode = FLIGHT_MODE_MAP[modeCode] || `模式${modeCode}`; - - // 云台角度 - 优先从 payload 中获取,否则从根级别获取 - const gimbalPitch = gimbalPayload?.gimbal_pitch ?? effectiveDroneData?.gimbal_pitch ?? 0; - const gimbalYaw = gimbalPayload?.gimbal_yaw ?? effectiveDroneData?.gimbal_yaw ?? 0; - const windSpeed = effectiveDroneData?.wind_speed ?? 0; - - // 无人机实时经纬度 - 从 effectiveDroneData 获取 - const droneLat = effectiveDroneData?.latitude ?? 0; - const droneLng = effectiveDroneData?.longitude ?? 0; + // 计算飞行剩余时间(基于电池百分比和平均消耗) + // 假设满电可飞行约30分钟,根据剩余电量计算 + const remainMinutes = Math.floor((batteryPercent / 100) * 30); + const remainSeconds = Math.floor(((batteryPercent / 100) * 30 - remainMinutes) * 60); return { - pitch: Number(pitch).toFixed(1), - roll: Number(roll).toFixed(1), - yaw: Number(yaw).toFixed(1), - hSpeed: Number(hSpeed).toFixed(1), - vSpeed: Number(vSpeed).toFixed(1), - altitude: Number(altitude).toFixed(1), - distance: Number(distance).toFixed(1), - satellites, - rtkSatellites, - rtkStatus, - signal, - batteryPercent, - batteryVoltage: (batteryVoltage / 1000).toFixed(2), - batteryTemp, - remainFlightTime: Math.floor(remainFlightTime / 60), - flightMode, - modeCode, - gimbalPitch: Number(gimbalPitch).toFixed(1), - gimbalYaw: Number(gimbalYaw).toFixed(1), - windSpeed: Number(windSpeed).toFixed(1), - // 无人机实时位置 - latitude: Number(droneLat).toFixed(6), - longitude: Number(droneLng).toFixed(6), + pitch: Number(data?.attitude_pitch ?? 0).toFixed(1), + roll: Number(data?.attitude_roll ?? 0).toFixed(1), + yaw: Number(data?.attitude_head ?? 0).toFixed(1), + hSpeed: Number(data?.horizontal_speed ?? 0).toFixed(1), + vSpeed: Number(data?.vertical_speed ?? 0).toFixed(1), + alt: Number(data?.height ?? data?.elevation ?? 0).toFixed(1), + dist: Number(data?.home_distance ?? 0).toFixed(1), + sat: data?.position_state?.gps_number ?? 0, + rtk: data?.position_state?.is_fixed === 2 ? 'FIX' : 'FLOAT', + bat: batteryPercent, + vol: (batteryVoltage / 1000).toFixed(1), + mode: data?.mode_code === 6 ? '手动操控' : '自动航线', + gimbalP: Number(gimbal?.gimbal_pitch ?? data?.gimbal_pitch ?? 0).toFixed(1), + gimbalY: Number(gimbal?.gimbal_yaw ?? data?.gimbal_yaw ?? 0).toFixed(1), + lat: Number(data?.latitude ?? 0).toFixed(6), + lng: Number(data?.longitude ?? 0).toFixed(6), + remainTime: `${remainMinutes}:${remainSeconds.toString().padStart(2, '0')}`, + remainMinutes, }; - }, [droneData, rawDroneData, dockData, realtimeData]); + }, [droneData, rawDroneData]); - // 指令发送状态 const [loading, setLoading] = useState(null); const [isRecording, setIsRecording] = useState(false); - const [cameraMode, setCameraMode] = useState<'photo' | 'video'>('photo'); // 相机模式 - - // WebSocket连接状态 const [wsConnected, setWsConnected] = useState(false); - - // 视频流连接状态 - const [videoConnected, setVideoConnected] = useState(false); - - // 视频全屏状态 - const [isFullscreen, setIsFullscreen] = useState(false); - const videoContainerRef = useRef(null); - - // 键盘控制状态 const [activeKeys, setActiveKeys] = useState>(new Set()); - const keyIntervalRef = useRef(null); - - // DRC模式状态 - 只需进入一次即可持续控制 const [drcMode, setDrcMode] = useState(false); - const drcModeRef = useRef(false); // 用于在回调中访问最新状态 + const drcModeRef = useRef(false); + const keyIntervalRef = useRef(null); + const [drcLoading, setDrcLoading] = useState(false); + + // 速度档位: 1=低速(偏移150), 2=高速(偏移300) + // 低档: 1024±150 -> 874/1174 + // 高档: 1024±300 -> 724/1324 + const [speedLevel, setSpeedLevel] = useState<1 | 2>(1); + const speedLevelRef = useRef<1 | 2>(1); + + // 相机模式状态: 0=拍照模式, 1=录像模式, null=未知 + const [cameraMode, setCameraMode] = useState(null); + // 相机操作loading状态 + const [cameraLoading, setCameraLoading] = useState(false); + + // 视频尺寸状态 + const [videoSize, setVideoSize] = useState<'normal' | 'large' | 'fullscreen'>('normal'); + + // 拖拽状态 + const [position, setPosition] = useState({ x: 0, y: 0 }); + const draggingRef = useRef(false); + const lastPosRef = useRef({ x: 0, y: 0 }); + const containerRef = useRef(null); + const panelRef = useRef(null); - // WebSocket连接管理 + 无人机SSE连接管理 useEffect(() => { if (visible && deviceSn) { - // 1. 连接实时控制WebSocket - deviceControlWs.connect(deviceSn); - - // 2. 建立独立的无人机SSE连接(专门接收无人机遥测数据) - connectDroneSSE(deviceSn); - - const unsubscribe = deviceControlWs.onStatusChange((connected) => { - setWsConnected(connected); - if (!connected) { - // 断开时重置DRC模式状态 - setDrcMode(false); - drcModeRef.current = false; - } + // 先注册状态监听,再连接(确保能收到连接成功的通知) + const sub = deviceControlWs.onStatusChange(c => { + setWsConnected(c); + if(!c) { setDrcMode(false); drcModeRef.current = false; } }); - + deviceControlWs.connect(deviceSn); + connectDroneSSE(deviceSn); return () => { - unsubscribe(); + sub(); deviceControlWs.disconnect(); - - // 清理DRC模式状态 - setDrcMode(false); - drcModeRef.current = false; - - // 断开无人机SSE连接 disconnectDroneSSE(deviceSn); resetDroneData(); }; + } else { + setPosition({ x: 0, y: 0 }); + setVideoSize('normal'); } - }, [visible, deviceSn, connectDroneSSE, disconnectDroneSSE, resetDroneData]); + }, [visible, deviceSn]); - // 监控无人机SSE连接状态(静默) + // 全屏状态监听 useEffect(() => { - // 清理函数 - return () => {}; - }, [visible, deviceSn, droneSseConnected, droneSseLoading, droneHasData, droneData]); - - // 进入DRC模式(只需调用一次) - const enterDrcMode = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return false; - } - - if (drcModeRef.current) { - return true; // 已经在DRC模式中 - } - - setLoading('drc'); - try { - const res = await deviceApi.enterDrcMode(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - setDrcMode(true); - drcModeRef.current = true; - message.success('已进入指令飞行模式'); - return true; - } else { - message.error(msg || '进入指令飞行模式失败'); - return false; + const handleFullscreenChange = () => { + if (!document.fullscreenElement && videoSize === 'fullscreen') { + setVideoSize('normal'); } - } catch (error: any) { - let errorMsg = '进入指令飞行模式失败'; - if (error.response) { - const data = error.response.data; - errorMsg = data?.resp_msg || data?.msg || error.response.statusText || errorMsg; - } else if (error.message) { - errorMsg = error.message; - } else if (error.msg) { - errorMsg = error.msg; - } else if (error.resp_msg) { - errorMsg = error.resp_msg; - } - message.error(errorMsg); - return false; - } finally { - setLoading(null); - } - }, [deviceSn]); + }; + document.addEventListener('fullscreenchange', handleFullscreenChange); + return () => document.removeEventListener('fullscreenchange', handleFullscreenChange); + }, [videoSize]); - // 一键返航 - const handleReturnHome = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - Modal.confirm({ - title: '确认返航', - content: '确定要让无人机执行一键返航吗?', - onOk: async () => { - setLoading('return'); - try { - const res = await deviceApi.returnHome(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - message.success('返航命令已发送'); - } else { - message.error(msg || '返航命令发送失败'); - } - } catch (error: any) { - message.error(error.message || '返航命令发送失败'); - } finally { - setLoading(null); - } - }, - }); - }, [deviceSn]); - - // 取消返航 - const handleCancelReturn = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - setLoading('cancelReturn'); - try { - const res = await deviceApi.cancelReturnHome(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - message.success('取消返航命令已发送'); - } else { - message.error(msg || '取消返航命令发送失败'); - } - } catch (error: any) { - message.error(error.message || '取消返航命令发送失败'); - } finally { - setLoading(null); - } - }, [deviceSn]); - - // 航线暂停(紧急悬停) - const handlePause = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - setLoading('pause'); - try { - const res = await deviceApi.pause(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - message.success('航线暂停/悬停命令已发送'); - } else { - message.error(msg || '暂停命令发送失败'); - } - } catch (error: any) { - message.error(error.message || '暂停命令发送失败'); - } finally { - setLoading(null); - } - }, [deviceSn]); - - // 航线恢复 - const handleResume = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - setLoading('resume'); - try { - const res = await deviceApi.resume(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - message.success('航线恢复命令已发送'); - } else { - message.error(msg || '恢复命令发送失败'); - } - } catch (error: any) { - message.error(error.message || '恢复命令发送失败'); - } finally { - setLoading(null); - } - }, [deviceSn]); - - // 切换相机模式 - const handleSwitchCameraMode = useCallback(async (mode: 'photo' | 'video') => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - setLoading('switchMode'); - try { - // camera_mode: 0=拍照模式, 1=录像模式 - const cameraModeValue = mode === 'photo' ? 0 : 1; - const res = await deviceApi.switchCameraMode(deviceSn, cameraModeValue); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res?.resp_code !== undefined ? res.resp_code : res?.code; - const msg = res?.resp_msg !== undefined ? res.resp_msg : res?.msg; - - if (code === 0) { - setCameraMode(mode); - message.success(`已切换到${mode === 'photo' ? '拍照' : '录像'}模式`); - } else { - message.error(msg || '切换相机模式失败'); - } - } catch (error: any) { - message.error(error.message || '切换相机模式失败'); - } finally { - setLoading(null); - } - }, [deviceSn]); - - // 拍照 - const handleTakePhoto = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - // 如果当前是录像模式,先切换到拍照模式 - if (cameraMode !== 'photo') { - await handleSwitchCameraMode('photo'); - } - - setLoading('photo'); - try { - const res = await deviceApi.takePhoto(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - message.success('拍照命令已发送'); - } else { - message.error(msg || '拍照命令发送失败'); - } - } catch (error: any) { - message.error(error.message || '拍照命令发送失败'); - } finally { - setLoading(null); - } - }, [deviceSn, cameraMode, handleSwitchCameraMode]); - - // 开始录像 - const handleStartRecording = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - // 先切换到录像模式 - if (cameraMode !== 'video') { - await handleSwitchCameraMode('video'); - } - - setLoading('recording'); - try { - const res = await deviceApi.startRecording(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - setIsRecording(true); - message.success('开始录像命令已发送'); - } else { - message.error(msg || '开始录像命令发送失败'); - } - } catch (error: any) { - message.error(error.message || '开始录像命令发送失败'); - } finally { - setLoading(null); - } - }, [deviceSn, cameraMode, handleSwitchCameraMode]); - - // 停止录像 - const handleStopRecording = useCallback(async () => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - setLoading('recording'); - try { - const res = await deviceApi.stopRecording(deviceSn); - // 兼容两种响应格式:resp_code/resp_msg 或 code/msg - const code = res.resp_code !== undefined ? res.resp_code : res.code; - const msg = res.resp_msg !== undefined ? res.resp_msg : res.msg; - - if (code === 0) { - setIsRecording(false); - message.success('停止录像命令已发送'); - } else { - message.error(msg || '停止录像命令发送失败'); - } - } catch (error: any) { - message.error(error.message || '停止录像命令发送失败'); - } finally { - setLoading(null); - } - }, [deviceSn]); - - // DRC杆量控制 (使用WebSocket实时发送,需先进入DRC模式) - const handleStickControl = useCallback(async (direction: string) => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - if (!wsConnected) { - message.warning('实时控制通道未连接,正在重连...'); - deviceControlWs.connect(deviceSn); - return; - } - - // 检查是否已进入DRC模式,如果没有则先进入 - if (!drcModeRef.current) { - const entered = await enterDrcMode(); - if (!entered) return; - } - - const offset = 300; - let params = { roll: 1024, pitch: 1024, throttle: 1024, yaw: 1024 }; - - switch (direction) { - case 'up': params.throttle = 1024 + offset; break; - case 'down': params.throttle = 1024 - offset; break; - case 'left': params.yaw = 1024 - offset; break; - case 'right': params.yaw = 1024 + offset; break; - case 'forward': params.pitch = 1024 + offset; break; - case 'backward': params.pitch = 1024 - offset; break; - case 'moveLeft': params.roll = 1024 - offset; break; - case 'moveRight': params.roll = 1024 + offset; break; - default: break; - } - - const success = deviceControlWs.sendStickControl(params); - if (!success) { - message.error('摇杆指令发送失败'); - } - }, [deviceSn, wsConnected, enterDrcMode]); - - // 云台控制 (使用WebSocket实时发送,需先进入DRC模式) - const handleGimbalControl = useCallback(async (direction: string) => { - if (!deviceSn) { - message.error('未选择设备'); - return; - } - - if (!wsConnected) { - message.warning('实时控制通道未连接,正在重连...'); - deviceControlWs.connect(deviceSn); - return; - } - - // 检查是否已进入DRC模式,如果没有则先进入 - if (!drcModeRef.current) { - const entered = await enterDrcMode(); - if (!entered) return; - } - - const speed = 20; - let params = { pitchSpeed: 0, yawSpeed: 0, locked: false }; - - switch (direction) { - case 'up': params.pitchSpeed = speed; break; - case 'down': params.pitchSpeed = -speed; break; - case 'left': params.yawSpeed = -speed; break; - case 'right': params.yawSpeed = speed; break; - default: break; - } - - const success = deviceControlWs.sendGimbalControl(params); - if (!success) { - message.error('云台指令发送失败'); - } - }, [deviceSn, wsConnected, enterDrcMode]); - - // 键盘按键映射 - const keyMappings: Record = { - 'w': { type: 'stick', direction: 'forward' }, // 前进 - 's': { type: 'stick', direction: 'backward' }, // 后退 - 'a': { type: 'stick', direction: 'left' }, // 左转 - 'd': { type: 'stick', direction: 'right' }, // 右转 - 'q': { type: 'stick', direction: 'moveLeft' }, // 向左平移 - 'e': { type: 'stick', direction: 'moveRight' }, // 向右平移 - 'r': { type: 'stick', direction: 'up' }, // 上升 - 'f': { type: 'stick', direction: 'down' }, // 下降 - 'arrowup': { type: 'gimbal', direction: 'up' }, // 云台上仰 - 'arrowdown': { type: 'gimbal', direction: 'down' },// 云台下俯 - 'arrowleft': { type: 'gimbal', direction: 'left' },// 云台左转 - 'arrowright': { type: 'gimbal', direction: 'right' },// 云台右转 - }; - - // 处理键盘控制 - const handleKeyboardControl = useCallback(() => { - if (activeKeys.size === 0) return; - - activeKeys.forEach(key => { - const mapping = keyMappings[key]; - if (mapping) { - if (mapping.type === 'stick') { - handleStickControl(mapping.direction); - } else { - handleGimbalControl(mapping.direction); - } - } - }); - }, [activeKeys, handleStickControl, handleGimbalControl]); - - // 键盘事件监听 + // ESC退出放大模式 useEffect(() => { - if (!visible || !wsConnected) return; + const handleEsc = (e: KeyboardEvent) => { + if (e.key === 'Escape' && videoSize === 'large') { + setVideoSize('normal'); + } + }; + window.addEventListener('keydown', handleEsc); + return () => window.removeEventListener('keydown', handleEsc); + }, [videoSize]); - const handleKeyDown = (e: KeyboardEvent) => { - const key = e.key.toLowerCase(); - if (keyMappings[key] && !activeKeys.has(key)) { - e.preventDefault(); - setActiveKeys(prev => new Set(prev).add(key)); + // 自动聚焦面板,确保键盘事件能够响应 + useEffect(() => { + if (!visible) return; + + // 面板可见时自动聚焦 + const focusPanel = () => { + if (panelRef.current && document.activeElement !== panelRef.current) { + panelRef.current.focus(); } }; - const handleKeyUp = (e: KeyboardEvent) => { - const key = e.key.toLowerCase(); - if (keyMappings[key]) { + // 初始聚焦 + setTimeout(focusPanel, 100); + + // 窗口重新获得焦点时自动聚焦面板 + const handleWindowFocus = () => { + setTimeout(focusPanel, 50); + }; + + // 页面可见性变化时自动聚焦面板 + const handleVisibilityChange = () => { + if (document.visibilityState === 'visible') { + setTimeout(focusPanel, 50); + } + }; + + window.addEventListener('focus', handleWindowFocus); + document.addEventListener('visibilitychange', handleVisibilityChange); + + return () => { + window.removeEventListener('focus', handleWindowFocus); + document.removeEventListener('visibilitychange', handleVisibilityChange); + }; + }, [visible]); + + const cmd = async (func: Function, key: string, msg: string) => { + if (!deviceSn) return; + setLoading(key); + try { + await func(deviceSn); + message.success(msg); + } catch (e) { + message.error('指令失败'); + } finally { + setLoading(null); + } + }; + + // 等待一段时间(用于命令间隔) + const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + + // 切换相机模式 + const switchCameraMode = async (targetMode: number): Promise => { + if (!deviceSn) return false; + try { + const res = await deviceApi.switchCameraMode(deviceSn, targetMode); + if (res.code === 0 || res.resp_code === 0) { + setCameraMode(targetMode); + return true; + } + return false; + } catch (e) { + console.error('切换相机模式失败:', e); + return false; + } + }; + + // 拍照(先切换到拍照模式,再拍照) + const handleTakePhoto = async () => { + if (!deviceSn || cameraLoading) return; + setCameraLoading(true); + + try { + // 1. 先切换到拍照模式 (mode=0) + message.loading({ content: '切换拍照模式...', key: 'photo', duration: 0 }); + const switchResult = await switchCameraMode(0); + if (!switchResult) { + message.error({ content: '切换拍照模式失败', key: 'photo' }); + return; + } + + // 2. 等待500ms让设备切换完成 + await delay(500); + + // 3. 执行拍照 + message.loading({ content: '正在拍照...', key: 'photo', duration: 0 }); + const photoRes = await deviceApi.takePhoto(deviceSn); + if (photoRes.code === 0 || photoRes.resp_code === 0) { + message.success({ content: '拍照成功', key: 'photo' }); + } else { + message.error({ content: '拍照失败', key: 'photo' }); + } + } catch (e) { + message.error({ content: '拍照失败', key: 'photo' }); + } finally { + setCameraLoading(false); + } + }; + + // 开始录像(先切换到录像模式,再开始录像) + const handleStartRecording = async () => { + if (!deviceSn || cameraLoading) return; + setCameraLoading(true); + + try { + // 1. 先切换到录像模式 (mode=1) + message.loading({ content: '切换录像模式...', key: 'record', duration: 0 }); + const switchResult = await switchCameraMode(1); + if (!switchResult) { + message.error({ content: '切换录像模式失败', key: 'record' }); + return; + } + + // 2. 等待500ms让设备切换完成 + await delay(500); + + // 3. 执行开始录像 + message.loading({ content: '开始录像...', key: 'record', duration: 0 }); + const recordRes = await deviceApi.startRecording(deviceSn); + if (recordRes.code === 0 || recordRes.resp_code === 0) { + setIsRecording(true); + message.success({ content: '开始录像', key: 'record' }); + } else { + message.error({ content: '开始录像失败', key: 'record' }); + } + } catch (e) { + message.error({ content: '开始录像失败', key: 'record' }); + } finally { + setCameraLoading(false); + } + }; + + // 停止录像 + const handleStopRecording = async () => { + if (!deviceSn || cameraLoading) return; + setCameraLoading(true); + + try { + message.loading({ content: '停止录像...', key: 'record', duration: 0 }); + const res = await deviceApi.stopRecording(deviceSn); + if (res.code === 0 || res.resp_code === 0) { + setIsRecording(false); + message.success({ content: '停止录像成功', key: 'record' }); + } else { + message.error({ content: '停止录像失败', key: 'record' }); + } + } catch (e) { + message.error({ content: '停止录像失败', key: 'record' }); + } finally { + setCameraLoading(false); + } + }; + + // 处理录像按钮点击 + const handleRecordClick = () => { + if (isRecording) { + handleStopRecording(); + } else { + handleStartRecording(); + } + }; + + // 进入指令飞行模式(DRC模式) + const handleEnterDrcMode = async () => { + if (!deviceSn || !wsConnected || drcLoading) return; + + setDrcLoading(true); + try { + message.loading({ content: '正在进入指令飞行模式...', key: 'drc', duration: 0 }); + const res = await deviceApi.enterDrcMode(deviceSn); + if (res.code === 0 || res.resp_code === 0) { + setDrcMode(true); + drcModeRef.current = true; + message.success({ content: '已进入指令飞行模式,可使用键盘控制无人机', key: 'drc' }); + } else { + message.error({ content: res.msg || '进入指令飞行模式失败', key: 'drc' }); + } + } catch (e) { + message.error({ content: '进入指令飞行模式失败', key: 'drc' }); + } finally { + setDrcLoading(false); + } + }; + + // 退出指令飞行模式 + const handleExitDrcMode = () => { + setDrcMode(false); + drcModeRef.current = false; + setActiveKeys(new Set()); + message.info('已退出指令飞行模式'); + }; + + // 根据速度档位获取偏移量 + // 低档: ±150 -> 874/1174 + // 高档: ±300 -> 724/1324 + const getSpeedOffset = useCallback(() => { + return speedLevelRef.current === 1 ? 150 : 300; + }, []); + + // 切换速度档位 (X键) + const cycleSpeedLevel = useCallback(() => { + const nextLevel = speedLevelRef.current === 1 ? 2 : 1 as 1 | 2; + speedLevelRef.current = nextLevel; + setSpeedLevel(nextLevel); + const speedNames = { 1: '低速', 2: '高速' }; + message.info(`速度切换: ${speedNames[nextLevel]}`); + }, []); + + const handleStick = useCallback(async (dir: string, type: 'stick'|'gimbal') => { + if (!deviceSn || !wsConnected) return; + // 必须先进入DRC模式才能控制 + if (!drcModeRef.current) { + return; + } + const offset = getSpeedOffset(); + let p: any = { roll: 1024, pitch: 1024, throttle: 1024, yaw: 1024 }; + if (type === 'gimbal') { + const s = 20; + p = { pitchSpeed: 0, yawSpeed: 0 }; + if (dir === 'up') p.pitchSpeed = s; // 云台上仰 + if (dir === 'down') p.pitchSpeed = -s; // 云台下俯 + if (dir === 'left') p.yawSpeed = -s; // 云台左转 + if (dir === 'right') p.yawSpeed = s; // 云台右转 + deviceControlWs.sendGimbalControl(p); + } else { + // W/S - 前进/后退 (pitch) + if (dir === 'fwd') p.pitch += offset; + if (dir === 'back') p.pitch -= offset; + // A/D - 向左/向右平移 (roll) + if (dir === 'left') p.roll -= offset; + if (dir === 'right') p.roll += offset; + // Q/E - 机头向左/向右转 (yaw) + if (dir === 'yawLeft') p.yaw -= offset; + if (dir === 'yawRight') p.yaw += offset; + // Z/C - 降低/升高 (throttle) + if (dir === 'up') p.throttle += offset; + if (dir === 'down') p.throttle -= offset; + deviceControlWs.sendStickControl(p); + } + }, [deviceSn, wsConnected, getSpeedOffset]); + + // 键盘控制映射 + // 飞行器控制: W前进 S后退 A左移 D右移 Q机头左转 E机头右转 Z降低 C升高 X切换速度 + // 云台控制: 上下左右箭头 + useEffect(() => { + if (!visible) return; + const map: Record = { + // 飞行器控制 + 'w': ['fwd', 'stick'], // 前进 + 's': ['back', 'stick'], // 后退 + 'a': ['left', 'stick'], // 向左平移 + 'd': ['right', 'stick'], // 向右平移 + 'q': ['yawLeft', 'stick'], // 机头向左转 + 'e': ['yawRight', 'stick'], // 机头向右转 + 'z': ['down', 'stick'], // 降低高度 + 'c': ['up', 'stick'], // 升高高度 + // 云台控制 + 'arrowup': ['up', 'gimbal'], // 云台上仰 + 'arrowdown': ['down', 'gimbal'], // 云台下俯 + 'arrowleft': ['left', 'gimbal'], // 云台左转 + 'arrowright': ['right', 'gimbal'] // 云台右转 + }; + + const down = (e: KeyboardEvent) => { + const k = e.key.toLowerCase(); + // X键切换速度档位 (只在按下时触发一次) + if (k === 'x' && !e.repeat) { + cycleSpeedLevel(); + return; + } + // 阻止方向键的默认滚动行为 + if (['arrowup', 'arrowdown', 'arrowleft', 'arrowright'].includes(k)) { e.preventDefault(); - setActiveKeys(prev => { - const newSet = new Set(prev); - newSet.delete(key); - return newSet; + } + if (map[k] && !activeKeys.has(k)) { + setActiveKeys(p => new Set(p).add(k)); + } + }; + + const up = (e: KeyboardEvent) => { + const k = e.key.toLowerCase(); + if (map[k]) { + setActiveKeys(p => { + const n = new Set(p); + n.delete(k); + return n; }); } }; - window.addEventListener('keydown', handleKeyDown); - window.addEventListener('keyup', handleKeyUp); + window.addEventListener('keydown', down); + window.addEventListener('keyup', up); + + keyIntervalRef.current = setInterval(() => { + activeKeys.forEach(k => { + if (map[k]) { + const [dir, type] = map[k]; + handleStick(dir, type); + } + }); + }, 100); return () => { - window.removeEventListener('keydown', handleKeyDown); - window.removeEventListener('keyup', handleKeyUp); - setActiveKeys(new Set()); + window.removeEventListener('keydown', down); + window.removeEventListener('keyup', up); + if (keyIntervalRef.current) clearInterval(keyIntervalRef.current); }; - }, [visible, wsConnected]); + }, [visible, activeKeys, wsConnected, handleStick, cycleSpeedLevel]); - // 持续发送控制指令 - useEffect(() => { - if (activeKeys.size > 0 && wsConnected) { - // 立即执行一次 - handleKeyboardControl(); - // 然后每100ms执行一次 - keyIntervalRef.current = setInterval(handleKeyboardControl, 100); - } else { - if (keyIntervalRef.current) { - clearInterval(keyIntervalRef.current); - keyIntervalRef.current = null; - } - } + // 拖拽处理 - 使用 RAF 优化性能 + const rafRef = useRef(null); + const pendingPosRef = useRef({ x: 0, y: 0 }); - return () => { - if (keyIntervalRef.current) { - clearInterval(keyIntervalRef.current); - keyIntervalRef.current = null; - } - }; - }, [activeKeys, wsConnected, handleKeyboardControl]); + const handleMouseDown = (e: React.MouseEvent) => { + if (videoSize !== 'normal') return; + e.preventDefault(); + draggingRef.current = true; + lastPosRef.current = { x: e.clientX, y: e.clientY }; + pendingPosRef.current = { ...position }; + document.body.style.userSelect = 'none'; + document.body.style.cursor = 'grabbing'; + document.addEventListener('mousemove', handleMouseMove); + document.addEventListener('mouseup', handleMouseUp); + }; - // 全屏切换 - const toggleFullscreen = useCallback(() => { - if (!videoContainerRef.current) return; - - if (!isFullscreen) { - if (videoContainerRef.current.requestFullscreen) { - videoContainerRef.current.requestFullscreen(); - } - } else { - if (document.exitFullscreen) { - document.exitFullscreen(); - } - } - }, [isFullscreen]); - - // 监听全屏变化 - useEffect(() => { - const handleFullscreenChange = () => { - setIsFullscreen(!!document.fullscreenElement); + const handleMouseMove = useCallback((e: MouseEvent) => { + if (!draggingRef.current) return; + const dx = e.clientX - lastPosRef.current.x; + const dy = e.clientY - lastPosRef.current.y; + lastPosRef.current = { x: e.clientX, y: e.clientY }; + pendingPosRef.current = { + x: pendingPosRef.current.x + dx, + y: pendingPosRef.current.y + dy }; - document.addEventListener('fullscreenchange', handleFullscreenChange); - return () => { - document.removeEventListener('fullscreenchange', handleFullscreenChange); - }; + if (rafRef.current) cancelAnimationFrame(rafRef.current); + rafRef.current = requestAnimationFrame(() => { + setPosition({ ...pendingPosRef.current }); + }); }, []); + const handleMouseUp = useCallback(() => { + draggingRef.current = false; + document.body.style.userSelect = ''; + document.body.style.cursor = ''; + document.removeEventListener('mousemove', handleMouseMove); + document.removeEventListener('mouseup', handleMouseUp); + if (rafRef.current) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + }, [handleMouseMove]); + + // 视频尺寸切换 + const handleVideoSizeToggle = () => { + if (videoSize === 'normal') { + setVideoSize('large'); + } else { + setVideoSize('normal'); + } + }; + + // 全屏切换 + const handleFullscreen = async () => { + if (videoSize === 'fullscreen') { + if (document.fullscreenElement) { + await document.exitFullscreen(); + } + setVideoSize('normal'); + } else { + if (containerRef.current) { + await containerRef.current.requestFullscreen(); + setVideoSize('fullscreen'); + } + } + }; + + // 获取尺寸类名 + const getSizeClassName = () => { + if (videoSize === 'large') return styles.large; + if (videoSize === 'fullscreen') return styles.fullscreen; + return ''; + }; + return ( -
-
-
- - 实时监控 / LIVE VIEW - LIVE -
- -
- - -
- {/* 使用 WHEP WebRTC 播放器 */} +
{ + containerRef.current = el; + panelRef.current = el; + }} + tabIndex={-1} + className={`${styles.controlPanelContainer} ${visible ? styles.visible : ''} ${getSizeClassName()}`} + style={{ + transform: visible && videoSize === 'normal' ? `translate(${position.x}px, ${position.y}px)` : undefined, + outline: 'none', // 移除聚焦时的默认轮廓 + }} + > + {/* 视频层 */} +
{videoStreamUrl ? ( - + ) : (
- - 未配置视频流地址 - {device?.deviceSn || '未选择设备'} +
+ + 等待视频信号... +
+ +
+
)} - {/* 简化的HUD - 左上角状态指示 */} -
-
- ● - {flightData.flightMode} -
-
- ● - 图传 -
-
- - {/* 简化的HUD - 右上角电池 */} -
- 30 ? '#0f0' : '#f00'}}> - {flightData.batteryPercent}% - - {flightData.batteryVoltage}V -
- - {/* 简化的HUD - 底部数据条 */} -
- H:{flightData.altitude}m - D:{flightData.distance}m - HS:{flightData.hSpeed} - VS:{flightData.vSpeed} -
- - {/* 云台角度指示 - 左下角小字 */} -
- P{flightData.gimbalPitch}° Y{flightData.gimbalYaw}° -
- - {/* 浮动控制按钮组 - 右侧 */} -
- {/* 全屏按钮 */} - - - - {/* 拍照按钮 */} - - - - {/* 录像按钮 */} - - - -
- - {/* DRC模式和连接状态指示 - 左下 */} -
- {wsConnected ? ( - - ) : ( - - )} - {drcMode && DRC}
- {/* 飞行仪表盘区域 - 更紧凑 */} -
- -
-
PITCH
-
{flightData.pitch}°
+ {/* UI 覆盖层 */} +
+ {/* 顶部栏 */} +
+
+
+ + {drcMode ? '手动接管' : '自动巡航'}
- - -
-
ROLL
-
{flightData.roll}°
-
-
- -
-
YAW
-
{flightData.yaw}°
-
-
- -
-
RTK
-
- {flightData.rtkStatus} -
-
-
- -
-
SAT
-
= 10 ? '#00ff88' : - flightData.satellites >= 6 ? '#ffaa00' : '#ff4444' - }}> - {flightData.satellites} -
-
-
- -
-
LINK
-
= 70 ? '#00ff88' : - flightData.signal >= 40 ? '#ffaa00' : '#ff4444' - }}> - {flightData.signal}% -
-
-
-
- -
- {/* 飞行控制指令 */} -
-
飞行控制
-
- - - - -
-
- - {/* 键盘控制说明 */} -
-
- 键盘控制 - - {wsConnected ? '已连接' : '未连接'} - -
-
-
- 飞行: - WASD - | - QE 平移 - | - RF 升降 -
-
- 云台: - ↑↓←→ -
- {/* 当前按下的键 */} - {activeKeys.size > 0 && ( -
- {Array.from(activeKeys).map(key => ( - {key.toUpperCase()} - ))} +
+
+ + {wsConnected ? '控制链路' : '链路断开'}
- )} +
10 ? styles.good : styles.warn}`}> + GPS + {flightData.sat} +
+
+ RTK + {flightData.rtk} +
+
+ {/* 键盘快捷键提示 */} + + {!drcMode ? ( +
请先点击底部"手动控制"按钮进入指令飞行模式
+ ) : ( + <> +
飞行控制:
+
W/S: 前进/后退
+
A/D: 左移/右移
+
Q/E: 机头左转/右转
+
Z/C: 降低/升高
+
X: 切换速度档位
+
云台控制:
+
方向键: 上/下/左/右
+ + )} +
+ } + placement="bottom" + > +
+ ⌨ + {drcMode ? '键盘已启用' : '键盘操控'} +
+ +
+
+
+ + {flightData.remainTime} +
+
+
+
+
+
+ {flightData.bat}% + {flightData.vol}V +
+
+
+ + {/* 中心HUD */} +
+
+
+
+
+
+
+
+
+
+
+ + {/* 左侧飞行数据 */} +
+
+
+ 水平速度 + {flightData.hSpeed}m/s +
+
+ 垂直速度 + {flightData.vSpeed}m/s +
+
+
+ 返航距离 + {flightData.dist}m +
+
+
+ + {/* 右侧姿态数据 */} +
+
+
+ 高度 + {flightData.alt}m +
+
+
+
+ P + {flightData.pitch}° +
+
+ R + {flightData.roll}° +
+
+ Y + {flightData.yaw}° +
+
+
+
+ + {/* 底部控制栏 */} +
+ {/* 左侧快捷操作 */} +
+ + + + + + + + + + + + +
+ + {/* 中间坐标和控制显示 */} +
+
+ + 经度 + {flightData.lng} + + + 纬度 + {flightData.lat} + +
+ {/* 手动控制和速度切换 */} +
+ {/* 手动控制按钮 */} + + + + {/* 速度切换 */} + +
+ 速度 +
+ = 1 ? styles.active : ''}`}> + = 2 ? styles.active : ''}`}> +
+ + {speedLevel === 1 ? '低' : '高'} + +
+
+
+
+ + {/* 右侧相机控制 */} +
+ + + + + + +
+
+
); diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx index ec325f61..f3be9208 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/BottomPanel/RightPanel.tsx @@ -92,7 +92,7 @@ const RightPanel: React.FC = ({ const dockData = realtimeData?.rawData?.dockData; // 检查机库状态 - if (dockData?.mode_code === 1) { + if (dockData?.mode_code !== 0) { message.warning('机库正在执行任务,无法起飞'); return; } diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts index 682c8572..866e840c 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDeviceSSE.ts @@ -103,6 +103,10 @@ export function useDeviceSSE(): UseDeviceSSEResult { const clientSessionIdRef = useRef( `client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}` ); + const reconnectTimerRef = useRef(null); + const reconnectAttemptsRef = useRef(0); + const maxReconnectAttempts = 10; + const shouldReconnectRef = useRef(true); // 核心断开逻辑,提取为纯函数以便在不同生命周期调用 const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => { @@ -126,6 +130,15 @@ export function useDeviceSSE(): UseDeviceSSEResult { const disconnectSSE = useCallback(async (deviceSn?: string) => { const snToDisconnect = deviceSn || currentDeviceSnRef.current; + // 禁止自动重连 + shouldReconnectRef.current = false; + + // 清除重连定时器 + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + reconnectTimerRef.current = null; + } + // 1. 取消当前的 fetch 连接 (客户端主动断开) if (abortControllerRef.current) { abortControllerRef.current.abort(); @@ -140,36 +153,54 @@ export function useDeviceSSE(): UseDeviceSSEResult { setSSEConnected(false); currentDeviceSnRef.current = ''; - console.log('SSE连接已断开'); + reconnectAttemptsRef.current = 0; + console.log('[DeviceSSE] 连接已断开'); }, []); // 处理SSE事件 const handleSSEEvent = useCallback((eventName: string, data: string) => { try { if (eventName === 'connected') { - console.log('SSE连接确认:', data); + console.log('[DeviceSSE] 连接确认:', data); + setSSEConnected(true); } else if (eventName === 'device-data-update') { const parsedData = JSON.parse(data); setRealtimeData(parsedData); } else if (eventName === 'heartbeat') { - // 心跳 + // 心跳 - 静默处理 } } catch (error) { - console.error('解析SSE数据失败:', error); + // 静默处理解析错误 } }, []); - // 连接SSE - const connectSSE = useCallback(async (deviceSn: string) => { - // 如果已经连接了同一个设备,先不断开,或者视需求而定。 - // 这里采取策略:如果 ID 变了,先断开旧的。 - if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) { - await disconnectSSE(currentDeviceSnRef.current); + // 自动重连调度 + const scheduleReconnect = useCallback((deviceSn: string) => { + if (!shouldReconnectRef.current) { + console.log('[DeviceSSE] 已禁用自动重连'); + return; } - 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 { const token = sessionStorage.getItem('access_token'); @@ -178,7 +209,7 @@ export function useDeviceSSE(): UseDeviceSSEResult { const abortController = new AbortController(); abortControllerRef.current = abortController; - console.log('正在建立SSE连接:', deviceSn); + console.log('[DeviceSSE] 正在建立连接:', deviceSn); const response = await fetch(url, { method: 'GET', @@ -196,7 +227,8 @@ export function useDeviceSSE(): UseDeviceSSEResult { throw new Error(`SSE连接失败: ${response.status}`); } - setSSEConnected(true); + // 重连成功,重置计数 + reconnectAttemptsRef.current = 0; const reader = response.body?.getReader(); const decoder = new TextDecoder(); @@ -204,56 +236,92 @@ export function useDeviceSSE(): UseDeviceSSEResult { if (!reader) throw new Error('无法读取响应流'); let buffer = ''; - while (true) { - const { done, value } = await reader.read(); - if (done) { - console.log('SSE连接已关闭'); - setSSEConnected(false); - break; - } + // 持续读取SSE流 + const readStream = async () => { + try { + while (true) { + const { done, value } = await reader.read(); - const chunk = decoder.decode(value, { stream: true }); - buffer += chunk; - - const lines = buffer.split('\n'); - buffer = lines.pop() || ''; - - let currentEvent = ''; - let currentData = ''; - - for (const line of lines) { - const trimmedLine = line.trim(); - if (trimmedLine === '') { - if (currentEvent && currentData) { - handleSSEEvent(currentEvent, currentData); + if (done) { + console.log('[DeviceSSE] 流结束'); + setSSEConnected(false); + // 流结束时尝试重连 + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + scheduleReconnect(deviceSn); + } + break; } - currentEvent = ''; - currentData = ''; - } else if (line.startsWith('event:')) { - currentEvent = line.substring(6).trim(); - } else if (line.startsWith('data:')) { - currentData = line.substring(5).trim(); + + buffer += decoder.decode(value, { stream: true }); + + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + 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) { - if (error.name === 'AbortError') { + if (error?.name === 'AbortError') { + console.log('[DeviceSSE] 连接被主动取消'); return; } - console.error('SSE连接错误:', error); + console.error('[DeviceSSE] 连接失败:', error); setSSEConnected(false); - // message.error('连接实时数据失败'); // 避免频繁报错 - - // 简单重连逻辑 - setTimeout(() => { - if (currentDeviceSnRef.current === deviceSn && !abortControllerRef.current) { - // 只有在没有活跃连接时才重连 - // connectSSE(deviceSn); // 慎用自动重连,可能导致死循环 - } - }, 5000); + // 连接失败时尝试重连 + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + scheduleReconnect(deviceSn); + } } - }, [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) useEffect(() => { @@ -274,6 +342,13 @@ export function useDeviceSSE(): UseDeviceSSEResult { // 组件卸载清理 (React Unmount) useEffect(() => { return () => { + // 清理重连定时器 + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + reconnectTimerRef.current = null; + } + shouldReconnectRef.current = false; + // 在组件卸载时,也尝试发送断开请求 if (currentDeviceSnRef.current) { const token = sessionStorage.getItem('access_token'); diff --git a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts index f820a7a4..f406890b 100644 --- a/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts +++ b/zlt-web/react-web-next/src/pages/device/mapDashboard/components/MapContainer/3d/hooks/useDroneSSE.ts @@ -103,6 +103,10 @@ export const useDroneSSE = (): UseDroneSSEReturn => { `drone_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}` ); const dataReceivedRef = useRef(false); // 用于跟踪是否已收到数据 + const reconnectTimerRef = useRef(null); + const reconnectAttemptsRef = useRef(0); + const maxReconnectAttempts = 10; + const shouldReconnectRef = useRef(true); // 是否应该自动重连 // 核心断开逻辑,提取为纯函数以便在不同生命周期调用 const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => { @@ -123,6 +127,15 @@ export const useDroneSSE = (): UseDroneSSEReturn => { const disconnectDroneSSE = useCallback(async (deviceSn?: string) => { const snToDisconnect = deviceSn || currentDeviceSnRef.current; + // 禁止自动重连 + shouldReconnectRef.current = false; + + // 清除重连定时器 + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + reconnectTimerRef.current = null; + } + // 1. 取消当前的 fetch 连接 (客户端主动断开) if (abortControllerRef.current) { abortControllerRef.current.abort(); @@ -141,6 +154,7 @@ export const useDroneSSE = (): UseDroneSSEReturn => { setHasData(false); dataReceivedRef.current = false; currentDeviceSnRef.current = ''; + reconnectAttemptsRef.current = 0; }, []); // 处理SSE事件(专门处理无人机数据) @@ -165,27 +179,39 @@ export const useDroneSSE = (): UseDroneSSEReturn => { } }, []); - // 连接无人机SSE - const connectDroneSSE = useCallback(async (deviceSn: string) => { - // 如果已经连接了同一个设备,先断开旧的 - if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) { - await disconnectDroneSSE(currentDeviceSnRef.current); - } - - if (!deviceSn) { + // 自动重连 + const scheduleReconnect = useCallback((deviceSn: string) => { + if (!shouldReconnectRef.current) { + console.log('[DroneSSE] 已禁用自动重连'); return; } - // 重置状态 - setDroneData(null); - setHasData(false); - dataReceivedRef.current = false; - currentDeviceSnRef.current = deviceSn; + if (reconnectAttemptsRef.current >= maxReconnectAttempts) { + console.error('[DroneSSE] 重连次数超限,停止重连'); + return; + } + + 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); try { const token = sessionStorage.getItem('access_token'); - const url = `/api-device/sse/drone-telemetry/${deviceSn}`; // 使用无人机SSE接口 + const url = `/api-device/sse/drone-telemetry/${deviceSn}`; // 创建 AbortController 用于取消请求 const abortController = new AbortController(); @@ -208,6 +234,9 @@ export const useDroneSSE = (): UseDroneSSEReturn => { throw new Error(`无人机SSE连接失败: ${response.status}`); } + // 重连成功,重置计数 + reconnectAttemptsRef.current = 0; + // 读取SSE流 const reader = response.body?.getReader(); const decoder = new TextDecoder(); @@ -225,7 +254,12 @@ export const useDroneSSE = (): UseDroneSSEReturn => { const { done, value } = await reader.read(); if (done) { + console.log('[DroneSSE] 流结束'); setSSEConnected(false); + // 流结束时尝试重连 + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + scheduleReconnect(deviceSn); + } break; } @@ -233,7 +267,7 @@ export const useDroneSSE = (): UseDroneSSEReturn => { // 解析SSE消息 const lines = buffer.split('\n'); - buffer = lines.pop() || ''; // 保留未完成的行 + buffer = lines.pop() || ''; let eventName = 'message'; let data = ''; @@ -244,7 +278,6 @@ export const useDroneSSE = (): UseDroneSSEReturn => { } else if (line.startsWith('data:')) { data = line.substring(5).trim(); } else if (line === '') { - // 空行表示消息结束 if (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); setLoading(false); + // 错误时尝试重连 + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + scheduleReconnect(deviceSn); + } } }; readStream(); - } catch (error) { + } catch (error: any) { + // 如果是主动取消的,不重连 + if (error?.name === 'AbortError') { + console.log('[DroneSSE] 连接被主动取消'); + return; + } + console.error('[DroneSSE] 连接失败:', error); setSSEConnected(false); setLoading(false); - - if (error instanceof Error) { - message.error(`无人机SSE连接失败: ${error.message}`); + // 连接失败时尝试重连 + if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) { + 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(() => { @@ -281,6 +353,12 @@ export const useDroneSSE = (): UseDroneSSEReturn => { // 组件卸载时自动断开连接 useEffect(() => { return () => { + // 清理重连定时器 + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + reconnectTimerRef.current = null; + } + shouldReconnectRef.current = false; if (currentDeviceSnRef.current) { disconnectDroneSSE(currentDeviceSnRef.current); } diff --git a/zlt-web/react-web-next/src/pages/system/App/components/AppForm.tsx b/zlt-web/react-web-next/src/pages/system/App/components/AppForm.tsx index 8c9c3c92..127e3e52 100644 --- a/zlt-web/react-web-next/src/pages/system/App/components/AppForm.tsx +++ b/zlt-web/react-web-next/src/pages/system/App/components/AppForm.tsx @@ -15,10 +15,28 @@ export interface AppFormProps { } const AppForm: React.FC = ({ open, title, initialValues, onOpenChange, onFinish }) => { - const initial: Partial = initialValues || {}; - if (initial.authorizedGrantTypes && !initial.authorizedGrantTypeCodes) { - initial.authorizedGrantTypeCodes = (initial.authorizedGrantTypes || '').split(',').filter(Boolean); + const defaultInitial: Partial = { + autoapprove: 'true', + accessTokenValiditySeconds: 18000, + refreshTokenValiditySeconds: 28800, + tokenFormat: 'reference', + authorizedGrantTypeCodes: [ + 'authorization_code', + 'password', + 'client_credentials', + 'implicit', + 'refresh_token', + 'password_code', + 'openId', + 'mobile_password', + ], + }; + + const initialFromProps: Partial = { ...(initialValues || {}) }; + if (initialFromProps.authorizedGrantTypes && !initialFromProps.authorizedGrantTypeCodes) { + initialFromProps.authorizedGrantTypeCodes = (initialFromProps.authorizedGrantTypes || '').split(',').filter(Boolean); } + const initial: Partial = { ...defaultInitial, ...initialFromProps }; return ( title={title} @@ -37,7 +55,16 @@ const AppForm: React.FC = ({ open, title, initialValues, onOpenCha name="authorizedGrantTypeCodes" label="授权方式" 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: '手机号密码模式', + }} /> void; type StatusHandler = (connected: boolean) => void; -class DeviceControlWebSocket { - 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[] = []; +class DeviceControlService { private statusHandlers: StatusHandler[] = []; - private currentDeviceSn: string | null = null; - private manualClose = false; + private isActive = false; /** - * 连接WebSocket - * @param deviceSn 设备SN + * 连接设备(标记为活跃状态) */ 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.reconnectAttempts = 0; - this.manualClose = false; - this.doConnect(); - } - - 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; - } + this.isActive = true; + console.log('[ControlHTTP] 已连接设备:', deviceSn); + this.notifyStatusHandlers(true); } /** - * 断开连接 + * 断开连接(标记为非活跃状态) */ disconnect(): void { - this.manualClose = true; + console.log('[ControlHTTP] 断开连接'); + this.isActive = false; this.currentDeviceSn = null; - this.stopHeartbeat(); - - 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; - } + this.notifyStatusHandlers(false); } /** * 发送摇杆控制指令 */ sendStickControl(data: StickControlData): boolean { - if (!this.currentDeviceSn) { - console.warn('[ControlWS] 未设置设备SN'); + if (!this.currentDeviceSn || !this.isActive) { + console.warn('[ControlHTTP] 未连接设备'); return false; } - return this.send({ - type: 'stick_control', - deviceSn: this.currentDeviceSn, - data, + + // 使用异步请求,不等待响应(提高控制频率) + request('/api-device/device/command/drc/stick', { + 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 { - if (!this.currentDeviceSn) { - console.warn('[ControlWS] 未设置设备SN'); + if (!this.currentDeviceSn || !this.isActive) { + console.warn('[ControlHTTP] 未连接设备'); return false; } - return this.send({ - type: 'gimbal_control', - deviceSn: this.currentDeviceSn, - data, + + // 使用异步请求,不等待响应 + request('/api-device/device/command/gimbal', { + 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 { - return this.ws !== null && this.ws.readyState === WebSocket.OPEN; + return this.isActive && this.currentDeviceSn !== null; } /** @@ -237,16 +119,6 @@ class DeviceControlWebSocket { 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 { this.statusHandlers.forEach(handler => { try { handler(connected); } catch (e) { - console.error('[ControlWS] 状态处理器错误:', e); + console.error('[ControlHTTP] 状态处理器错误:', e); } }); } } -// 导出单例 -export const deviceControlWs = new DeviceControlWebSocket(); +// 导出单例(保持与原WebSocket版本相同的接口名) +export const deviceControlWs = new DeviceControlService();