feat: 无人机控制指令
This commit is contained in:
@@ -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,
|
||||
|
||||
+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"
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
/**
|
||||
* 设备实时控制WebSocket服务
|
||||
* 用于高频率的云台控制和摇杆控制(5-10Hz)
|
||||
* 设备实时控制服务
|
||||
* 用于云台控制和摇杆控制
|
||||
* 使用HTTP API实现(替代WebSocket)
|
||||
*/
|
||||
|
||||
import { request } from 'umi';
|
||||
|
||||
export interface StickControlData {
|
||||
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
|
||||
roll?: number;
|
||||
@@ -23,211 +26,90 @@ export interface GimbalControlData {
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
export interface ControlMessage {
|
||||
type: 'stick_control' | 'gimbal_control' | 'heartbeat';
|
||||
deviceSn: string;
|
||||
data?: StickControlData | GimbalControlData;
|
||||
}
|
||||
|
||||
export interface ControlResponse {
|
||||
type: 'response' | 'error' | 'pong';
|
||||
success?: boolean;
|
||||
message?: string;
|
||||
commandId?: string;
|
||||
}
|
||||
|
||||
type MessageHandler = (message: ControlResponse) => void;
|
||||
type StatusHandler = (connected: boolean) => void;
|
||||
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user