feat: 无人机控制指令
This commit is contained in:
+930
-306
File diff suppressed because it is too large
Load Diff
+745
-804
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -92,7 +92,7 @@ const RightPanel: React.FC<RightPanelProps> = ({
|
||||
const dockData = realtimeData?.rawData?.dockData;
|
||||
|
||||
// 检查机库状态
|
||||
if (dockData?.mode_code === 1) {
|
||||
if (dockData?.mode_code !== 0) {
|
||||
message.warning('机库正在执行任务,无法起飞');
|
||||
return;
|
||||
}
|
||||
|
||||
+129
-54
@@ -103,6 +103,10 @@ export function useDeviceSSE(): UseDeviceSSEResult {
|
||||
const clientSessionIdRef = useRef<string>(
|
||||
`client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
||||
);
|
||||
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const reconnectAttemptsRef = useRef<number>(0);
|
||||
const maxReconnectAttempts = 10;
|
||||
const shouldReconnectRef = useRef<boolean>(true);
|
||||
|
||||
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
|
||||
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
||||
@@ -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');
|
||||
|
||||
+100
-22
@@ -103,6 +103,10 @@ export const useDroneSSE = (): UseDroneSSEReturn => {
|
||||
`drone_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
||||
);
|
||||
const dataReceivedRef = useRef<boolean>(false); // 用于跟踪是否已收到数据
|
||||
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const reconnectAttemptsRef = useRef<number>(0);
|
||||
const maxReconnectAttempts = 10;
|
||||
const shouldReconnectRef = useRef<boolean>(true); // 是否应该自动重连
|
||||
|
||||
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
|
||||
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -15,10 +15,28 @@ export interface AppFormProps {
|
||||
}
|
||||
|
||||
const AppForm: React.FC<AppFormProps> = ({ open, title, initialValues, onOpenChange, onFinish }) => {
|
||||
const initial: Partial<AppFormValues> = initialValues || {};
|
||||
if (initial.authorizedGrantTypes && !initial.authorizedGrantTypeCodes) {
|
||||
initial.authorizedGrantTypeCodes = (initial.authorizedGrantTypes || '').split(',').filter(Boolean);
|
||||
const defaultInitial: Partial<AppFormValues> = {
|
||||
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<AppFormValues> = { ...(initialValues || {}) };
|
||||
if (initialFromProps.authorizedGrantTypes && !initialFromProps.authorizedGrantTypeCodes) {
|
||||
initialFromProps.authorizedGrantTypeCodes = (initialFromProps.authorizedGrantTypes || '').split(',').filter(Boolean);
|
||||
}
|
||||
const initial: Partial<AppFormValues> = { ...defaultInitial, ...initialFromProps };
|
||||
return (
|
||||
<ModalForm<AppFormValues>
|
||||
title={title}
|
||||
@@ -37,7 +55,16 @@ const AppForm: React.FC<AppFormProps> = ({ 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: '手机号密码模式',
|
||||
}}
|
||||
/>
|
||||
<ProFormSelect
|
||||
name="autoapprove"
|
||||
|
||||
Reference in New Issue
Block a user