航线任务 无人机实时轨迹优化显示 优化websocket优化 设备状态界面显示

This commit is contained in:
mmc
2026-06-05 15:57:36 +08:00
parent 58d251aa68
commit 9e6280866c
6 changed files with 239 additions and 188 deletions

View File

@@ -716,7 +716,14 @@ export default function CesiumMap({ realtimePosition, realtimeType, pathPoints =
const focusEntityRef = useRef(null);
useEffect(() => {
if (!viewerRef.current || !focusLocation) {
// 如果有 realtimePosition,不显示 focusEntity
const hasRealtime =
realtimePosition?.lon &&
realtimePosition?.lat &&
!isNaN(Number(realtimePosition.lon)) &&
!isNaN(Number(realtimePosition.lat));
if (!viewerRef.current || !focusLocation || hasRealtime) {
if (focusEntityRef.current) {
viewerRef.current?.entities.remove(focusEntityRef.current);
focusEntityRef.current = null;
@@ -1108,7 +1115,8 @@ export default function CesiumMap({ realtimePosition, realtimeType, pathPoints =
}, window.Cesium.ScreenSpaceEventType.LEFT_CLICK);
handler.setInputAction((movement) => {
if (from !== "device-control") return;
//if (from !== "device-control")
return;
const cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
if (!cartesian) return;
const cartographic = window.Cesium.Cartographic.fromCartesian(cartesian);
@@ -1214,9 +1222,26 @@ export default function CesiumMap({ realtimePosition, realtimeType, pathPoints =
return;
}
// ====================================
// 情况2:有实时数据 -> 隐藏 focusEntity
// ====================================
if (focusEntityRef.current) {
viewer.entities.remove(focusEntityRef.current);
focusEntityRef.current = null;
}
// ====================================
// 解析实时坐标
// ====================================
entityMapRef.current.forEach((entity) => {
if (entity.billboard) entity.billboard.show = false;
});
alarmMapRef.current.forEach((entity) => {
if (entity.billboard) entity.billboard.show = false;
});
iotMapRef.current.forEach((entity) => {
if (entity.billboard) entity.billboard.show = false;
});
const lon = Number(realtimePosition.lon);
const lat = Number(realtimePosition.lat);
@@ -1302,8 +1327,7 @@ export default function CesiumMap({ realtimePosition, realtimeType, pathPoints =
// 需要将地理航向转换为 Cesium rotation
// 地理 0° 北 → Cesium 需要 -90° 或者 270°(因为 Cesium 0° 是右/东)
let headingDeg = Number(realtimePosition.heading);
// 将地理航向转换:北(0°) → 上(270° 或 -90°)
rotation = Cesium.Math.toRadians(headingDeg - 90);
rotation = Cesium.Math.toRadians(headingDeg);
}
if (!realtimeCarEntityRef.current) {

View File

@@ -5,231 +5,230 @@ type WSStatus = 'disconnected' | 'connecting' | 'connected';
type MessageHandler = (data: any) => void;
interface WSMessage {
type: string;
[key: string]: any;
type: string;
[key: string]: any;
}
class WebSocketManager {
private static instance: WebSocketManager | null = null;
private static instance: WebSocketManager | null = null;
private ws: WebSocket | null = null;
private status: WSStatus = 'disconnected';
private messageHandlers: MessageHandler[] = [];
private reconnectTimer: NodeJS.Timeout | null = null;
private currentSerialRef: string | null = null;
private isManualCloseRef: boolean = false;
private wsSerialRef: string | null = null;
private ws: WebSocket | null = null;
private status: WSStatus = 'disconnected';
private messageHandlers: MessageHandler[] = [];
private reconnectTimer: NodeJS.Timeout | null = null;
private currentSerialRef: string | null = null;
private isManualCloseRef: boolean = false;
private wsSerialRef: string | null = null;
// 状态监听器
private statusListeners: ((status: WSStatus) => void)[] = [];
// 状态监听器
private statusListeners: ((status: WSStatus) => void)[] = [];
// 🔒 私有构造函数,防止外部 new
private constructor() {}
// 🔒 私有构造函数,防止外部 new
private constructor() { }
// 🎯 获取单例实例
public static getInstance(): WebSocketManager {
if (!WebSocketManager.instance) {
WebSocketManager.instance = new WebSocketManager();
}
return WebSocketManager.instance;
}
// 🎯 获取单例实例
public static getInstance(): WebSocketManager {
if (!WebSocketManager.instance) {
WebSocketManager.instance = new WebSocketManager();
}
return WebSocketManager.instance;
}
// ==================== 状态管理 ====================
// ==================== 状态管理 ====================
public getStatus(): WSStatus {
return this.status;
}
public getStatus(): WSStatus {
return this.status;
}
public setStatus(status: WSStatus) {
this.status = status;
// 通知所有状态监听器
this.statusListeners.forEach(listener => listener(status));
}
public setStatus(status: WSStatus) {
this.status = status;
// 通知所有状态监听器
this.statusListeners.forEach(listener => listener(status));
}
public onStatusChange(listener: (status: WSStatus) => void): () => void {
this.statusListeners.push(listener);
listener(this.status);
// 返回取消订阅函数
return () => {
const index = this.statusListeners.indexOf(listener);
if (index > -1) {
this.statusListeners.splice(index, 1);
}
};
}
public onStatusChange(listener: (status: WSStatus) => void): () => void {
this.statusListeners.push(listener);
listener(this.status);
// 返回取消订阅函数
return () => {
const index = this.statusListeners.indexOf(listener);
if (index > -1) {
this.statusListeners.splice(index, 1);
}
};
}
// ==================== 连接管理 ====================
// ==================== 连接管理 ====================
public connect(serialNumber: string, wsUrl: string): void {
console.log("创建开始");//ws://192.168.2.56:9002/ws/
// 清除之前的重连计时器
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
public connect(serialNumber: string, wsUrl: string): void {
console.log("创建开始");//ws://192.168.2.56:9002/ws/
// 清除之前的重连计时器
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
// 如果序列号相同且已连接,跳过
if (this.ws && this.currentSerialRef === serialNumber && this.status === 'connected') {
console.log('WebSocket already connected for this device');
return;
}
// 如果序列号相同且已连接,跳过
if (this.ws && this.currentSerialRef === serialNumber && this.status === 'connected') {
console.log('WebSocket already connected for this device');
return;
}
// 如果序列号不同,先关闭旧连接
if (this.ws && this.currentSerialRef !== serialNumber) {
this.close();
}
// 如果序列号不同,先关闭旧连接
if (this.ws && this.currentSerialRef !== serialNumber) {
this.close();
}
this.currentSerialRef = serialNumber;
this.setStatus('connecting');
this.isManualCloseRef = false;
this.currentSerialRef = serialNumber;
this.setStatus('connecting');
this.isManualCloseRef = false;
console.log('Connecting WebSocket for', serialNumber);
console.log('Connecting WebSocket for', serialNumber);
if (serialNumber == null || serialNumber.trim() === "") {
console.log("serialNumber 是空/空白,停止执行");
return;
}
if (serialNumber == null || serialNumber.trim() === "") {
console.log("serialNumber 是空/空白,停止执行");
return;
}
this.ws = new WebSocket(wsUrl);
this.wsSerialRef = serialNumber;
this.ws = new WebSocket(wsUrl);
this.wsSerialRef = serialNumber;
this.ws.onopen = () => {
console.log('WebSocket Connected');
this.setStatus('connected');
this.ws.onopen = () => {
console.log('WebSocket Connected');
this.setStatus('connected');
const dataStr = localStorage.getItem('userInfo');
if(!dataStr){
const dataStr = localStorage.getItem('userInfo');
if (!dataStr) {
console.error('用户信息未找到,无法发送认证包');
return;
}
let parse = JSON.parse(dataStr);
var token=parse?.token;
let parse = JSON.parse(dataStr);
var token = parse?.token;
console.log('WebSocket%',token);
console.log('WebSocket%',parse);
console.log("开始发送认证包");//ws://192.168.2.56:9002/ws/
// 发送 AUTH 认证消息
this.send({
type: 'AUTH',
token: token,
userName: parse.username,
deviceId: serialNumber,
});
console.log('WebSocket%', token);
console.log('WebSocket%', parse);
console.log("开始发送认证包");//ws://192.168.2.56:9002/ws/
// 发送 AUTH 认证消息
this.send({
type: 'AUTH',
token: token,
userName: parse.username,
deviceId: serialNumber,
});
};
};
this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
this.handleMessage(data);
} catch (e) {
console.error('WS message parse error', e);
}
};
this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
this.handleMessage(data);
} catch (e) {
console.error('WS message parse error', e);
}
};
this.ws.onerror = (err) => {
console.error('WebSocket error', err);
};
this.ws.onerror = (err) => {
console.error('WebSocket error', err);
};
this.ws.onclose = (event) => {
const { code, reason, wasClean } = event;
console.log('[WebSocket closed]', 'code =', code, 'reason =', reason || '(no reason)', 'wasClean =', wasClean);
this.ws.onclose = (event) => {
const { code, reason, wasClean } = event;
console.log('[WebSocket closed]', 'code =', code, 'reason =', reason || '(no reason)', 'wasClean =', wasClean);
// 如果不是当前设备的 ws,忽略
if (this.wsSerialRef !== this.currentSerialRef) {
console.log('🟡 ignore old ws close');
return;
}
// 如果不是当前设备的 ws,忽略
if (this.wsSerialRef !== this.currentSerialRef) {
console.log('🟡 ignore old ws close');
return;
}
this.ws = null;
this.setStatus('disconnected');
this.ws = null;
this.setStatus('disconnected');
// 主动关闭不重连
if (this.isManualCloseRef || !this.currentSerialRef) {
return;
}
// 主动关闭不重连
if (this.isManualCloseRef || !this.currentSerialRef) {
return;
}
// 5 秒后自动重连
this.reconnectTimer = setTimeout(() => {
if (this.currentSerialRef === this.wsSerialRef) {
this.connect(this.currentSerialRef, wsUrl);
}
}, 5000);
};
}
// 5 秒后自动重连
this.reconnectTimer = setTimeout(() => {
if (this.currentSerialRef === this.wsSerialRef) {
this.connect(this.currentSerialRef, wsUrl);
}
}, 5000);
};
}
// ==================== 断开连接 ====================
// ==================== 断开连接 ====================
public close(): void {
this.isManualCloseRef = true;
public close(): void {
this.isManualCloseRef = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
console.log('Closing WebSocket');
this.ws.close();
this.ws = null;
}
if (this.ws) {
console.log('Closing WebSocket');
this.ws.close();
this.ws = null;
}
this.currentSerialRef = null;
this.wsSerialRef = null;
this.setStatus('disconnected');
}
this.currentSerialRef = null;
this.wsSerialRef = null;
this.setStatus('disconnected');
}
// ==================== 消息发送 ====================
// ==================== 消息发送 ====================
public send(data: WSMessage): boolean {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
console.log('WebSocket not connected, cannot send message');
return false;
}
console.log('WebSocket send message');
this.ws.send(JSON.stringify(data));
return true;
}
public send(data: WSMessage): boolean {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
console.log('WebSocket not connected, cannot send message');
return false;
}
console.log('WebSocket send message');
this.ws.send(JSON.stringify(data));
return true;
}
// ==================== 消息接收 ====================
// ==================== 消息接收 ====================
private handleMessage(data: WSMessage): void {
console.log('WS message received', data);
// 通知所有消息处理器
this.messageHandlers.forEach(handler => handler(data));
}
private handleMessage(data: WSMessage): void {
// 通知所有消息处理器
this.messageHandlers.forEach(handler => handler(data));
}
public onMessage(handler: MessageHandler): () => void {
this.messageHandlers.push(handler);
// 返回取消订阅函数
return () => {
const index = this.messageHandlers.indexOf(handler);
if (index > -1) {
this.messageHandlers.splice(index, 1);
}
};
}
public onMessage(handler: MessageHandler): () => void {
this.messageHandlers.push(handler);
// 返回取消订阅函数
return () => {
const index = this.messageHandlers.indexOf(handler);
if (index > -1) {
this.messageHandlers.splice(index, 1);
}
};
}
// ==================== 工具方法 ====================
// ==================== 工具方法 ====================
public getCurrentSerial(): string | null {
return this.currentSerialRef;
}
public getCurrentSerial(): string | null {
return this.currentSerialRef;
}
public isConnected(): boolean {
return this.status === 'connected' && this.ws?.readyState === WebSocket.OPEN;
}
public isConnected(): boolean {
return this.status === 'connected' && this.ws?.readyState === WebSocket.OPEN;
}
// ==================== 销毁单例(测试用)====================
// ==================== 销毁单例(测试用)====================
public static destroyInstance(): void {
if (WebSocketManager.instance) {
WebSocketManager.instance.close();
WebSocketManager.instance = null;
}
}
public static destroyInstance(): void {
if (WebSocketManager.instance) {
WebSocketManager.instance.close();
WebSocketManager.instance = null;
}
}
}
// 🎯 导出单例实例

View File

@@ -302,6 +302,15 @@ export default function DeviceStatusPage({
const timerRef = useRef<any>(null);
const runningStatus = useMemo(() => {
// 判断对象是否为空
if ((!wsDeviceInfo || Object.keys(wsDeviceInfo).length === 0) && !isUAV) {
return {};
}
if (isUAV) {
return {
...wsDeviceInfo,
};
}
const base = device?.lastRunningStatus || {};
return isUAV
@@ -376,6 +385,7 @@ export default function DeviceStatusPage({
useEffect(() => {
if (!device || !controllerRef.current || !device?.serialNumber || isUAV) return;
setWsDeviceInfo({});
controllerRef.current.connectDevice(device);

View File

@@ -67,6 +67,8 @@ export default function RobotTaskPage() {
useEffect(() => {
const controller = new DeviceController(userInfo, messageApi);
controller.init();
controllerRef.current = controller;
return () => {
if (controllerRef.current) {
@@ -440,6 +442,7 @@ export default function RobotTaskPage() {
}
}, [filterForm, stationId]);
// 监听任务池筛选条件变化
useEffect(() => {
if (stationId) {

View File

@@ -556,6 +556,16 @@ export default function WayLinePage({ onRefresh }) {
useEffect(() => {
getBoardTask();
}, [boardDrone, boardDateRange, planedevices?.length]);
const realtimePosition = React.useMemo(() => {
if (persistentDroneData?.longitude && persistentDroneData?.latitude) {
return {
lon: persistentDroneData.longitude,
lat: persistentDroneData.latitude,
heading: persistentDroneData.heading || 0,
};
}
}, [persistentDroneData]);
// 任务状态标签
const getStatusTag = (status) => {
@@ -634,6 +644,7 @@ export default function WayLinePage({ onRefresh }) {
}
};
// 执行航线按钮点击(改为图标)
const handleExecuteClick = (e, wayline) => {
e.stopPropagation();
@@ -852,7 +863,8 @@ export default function WayLinePage({ onRefresh }) {
style={{ ...cardStyle, marginBottom: 10 }}
>
<div style={{ width: '100%', height: 420, background: '#e8f3ff url(https://picsum.photos/seed/solar_map_v2/1600/1000) center/cover', position: 'relative' }}>
<CesiumMap devices={planedevices} points={points} focusLocation={focusLocation} from="device-control" />
<CesiumMap realtimePosition={realtimePosition}
points={points} focusLocation={focusLocation} from="device-control" realtimeType='plane' />
<div style={{ position: 'absolute', top: 16, left: 16, background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(8px)', padding: '14px 16px', borderRadius: 10, width: 150, boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }}>
<div style={{ fontSize: fontSmall, display: 'flex', flexDirection: 'column', gap: 10 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ width: 14, height: 2, background: '#165DFF' }}></span> 无人机航线</div>

View File

@@ -56,7 +56,7 @@ export default class DeviceController {
document.addEventListener('visibilitychange', this.handleVisibilityChange);
// ========== 【集成】后台保活定时 ==========
this.startKeepAlive();
//this.startKeepAlive();
}
// ========== 【集成】页面切前台重连 ==========
@@ -165,16 +165,17 @@ export default class DeviceController {
token: this.userInfo.token,
});
this.hasControlRight = res?.code === 200;
this.hasControlRight = res?.code === 200 && res.data == true;
this.onHasControlRightChange?.(this.hasControlRight);
wsManager.connect(sn, this.wsUrl);
this.connectedDeviceSn = sn;
if (!this.hasControlRight) {
this.messageApi.warning('其他端正在控制');
return;
}
wsManager.connect(sn, this.wsUrl);
this.connectedDeviceSn = sn;
await this.getControl(sn);
@@ -225,7 +226,7 @@ export default class DeviceController {
this.onRequestControlStatusChange?.(false);
this.messageApi.destroy('control');
this.messageApi.error('控制请求超时');
}, 10000);
}, 20000);
}
clearControlTimeout() {
@@ -266,17 +267,18 @@ export default class DeviceController {
}
case 'switchResult': {
console.log('🔌 控制结果111111111111111:', msg);
this.clearControlTimeout();
this.isRequestControl = false;
this.onRequestControlStatusChange?.(false);
if (msg.success === false || msg.switchResult === false) {
if (msg.success === false || msg?.respond?.switchResult === false) {
this.isControlled = false;
this.onControlStatusChange?.(false);
this.messageApi.error({ key: 'control', content: msg.message || '控制失败' });
return;
}
this.isControlled = true;
this.onControlStatusChange?.(true);
this.messageApi.success({ key: 'control', content: '控制成功' });
@@ -284,8 +286,9 @@ export default class DeviceController {
}
case 'switchPermission': {
console.log('🔌 控制结果111111111111111222222222:', msg);
const platform = (msg.platform || '').toLowerCase();
if (!platform || platform === 'web' || platform === 'null') return;
if (!platform || platform === 'null') return;
this.requestDeviceId = msg.deviceId;
this.onPermissionRequest?.({