{
+ 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}°
-
-
- {/* 浮动控制按钮组 - 右侧 */}
-
- {/* 全屏按钮 */}
-
-
- {/* 飞行仪表盘区域 - 更紧凑 */}
-
-
-
-
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}%
-
-
-
-
-
-
- {/* 飞行控制指令 */}
-
-
飞行控制
-
-
- {loading === 'return' ? : } 返航
-
-
- {loading === 'cancelReturn' ? : } 取消
-
-
- {loading === 'pause' ? : } 暂停
-
-
- {loading === 'resume' ? : } 恢复
-
-
-
-
- {/* 键盘控制说明 */}
-
-
- 键盘控制
-
- {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
+
+
+
e.stopPropagation()}>
+
+
+
+ {/* 中心HUD */}
+
+
+ {/* 左侧飞行数据 */}
+
+
+
+ 水平速度
+ {flightData.hSpeed}m/s
+
+
+ 垂直速度
+ {flightData.vSpeed}m/s
+
+
+
+ 返航距离
+ {flightData.dist}m
+
+
+
+
+ {/* 右侧姿态数据 */}
+
+
+
+ 高度
+ {flightData.alt}m
+
+
+
+
+ P
+ {flightData.pitch}°
+
+
+ R
+ {flightData.roll}°
+
+
+ Y
+ {flightData.yaw}°
+
+
+
+
+
+ {/* 底部控制栏 */}
+
+ {/* 左侧快捷操作 */}
+
+
+ Modal.confirm({
+ title: '确认返航?',
+ content: '无人机将自动返回起飞点',
+ okText: '确认',
+ cancelText: '取消',
+ onOk: () => cmd(deviceApi.returnHome, 'ret', '返航指令已发送')
+ })}
+ >
+
+ 返航
+
+
+
+ cmd(deviceApi.cancelReturnHome, 'cret', '取消返航')}>
+
+ 取消
+
+
+
+ cmd(deviceApi.pause, 'p', '悬停')}>
+
+ 悬停
+
+
+
+ cmd(deviceApi.resume, 'r', '恢复航线')}>
+
+ 继续
+
+
+
+
+ {/* 中间坐标和控制显示 */}
+
+
+
+ 经度
+ {flightData.lng}
+
+
+ 纬度
+ {flightData.lat}
+
+
+ {/* 手动控制和速度切换 */}
+
+ {/* 手动控制按钮 */}
+
+
+ {drcLoading ? : (drcMode ? : )}
+ {drcMode ? '退出控制' : '手动控制'}
+
+
+ {/* 速度切换 */}
+
+
+
速度
+
+ = 1 ? styles.active : ''}`}>
+ = 2 ? styles.active : ''}`}>
+
+
+ {speedLevel === 1 ? '低' : '高'}
+
+
+
+
+
+
+ {/* 右侧相机控制 */}
+
+
+
+ {cameraLoading && !isRecording ? (
+
+ ) : (
+
+ )}
+
+
+
+
+ {cameraLoading && (isRecording || cameraMode === 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();