From 831e1086d358f5c2b8c43d7dd29ee737f82e38c4 Mon Sep 17 00:00:00 2001 From: mmc <1556375442@qq.com> Date: Sat, 14 Nov 2026 18:23:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E4=B8=8D=E5=90=8C=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=20=20=E6=98=BE=E7=A4=BA=E7=9A=84=E9=A6=96=E9=A1=B5?= =?UTF-8?q?=E4=BC=98=E5=8C=96=20=20=E8=A7=84=E5=88=92=E7=95=8C=E9=9D=A2=20?= =?UTF-8?q?=E6=82=AC=E6=B5=AE=E6=98=BE=E7=A4=BA=20=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=20=20=20=20=E5=85=A8=E5=B1=80=E6=80=A5?= =?UTF-8?q?=E5=81=9C=E7=8A=B6=E6=80=81=E7=BB=9F=E4=B8=80=20=20=20=20?= =?UTF-8?q?=E5=89=B2=E5=88=80=20=E6=A0=B9=E6=8D=AE=E6=96=B0=E6=96=B9?= =?UTF-8?q?=E6=A1=88=E5=AF=B9=E6=8E=A5=20=20=E4=B8=A4=E4=B8=AA=E7=8A=B6?= =?UTF-8?q?=E6=80=81=20=20=E4=BB=BB=E5=8A=A1=E8=B7=AF=E7=BA=BF=20=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E4=B8=BA=20=E6=8A=BD=E6=8B=89=E5=BC=8F=E4=B8=80?= =?UTF-8?q?=E8=A1=8C=E4=B8=80=E4=B8=AA=20=20xbox=E7=BB=84=E4=BB=B6?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=95=B0=E6=8D=AE=E5=8F=91=E9=80=81=EF=BC=8C?= =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Layout.tsx | 25 ++ src/components/Map.jsx | 269 ++++++++++-------- src/components/devices/DPadControl.tsx | 56 ++-- src/components/devices/DeviceOverviewPage.tsx | 54 +++- src/components/devices/DeviceStatusPage.tsx | 94 +++++- src/components/devices/MapEditorView.tsx | 4 +- src/components/devices/Steerbutton.tsx | 132 ++------- src/components/devices/TaskPlanningView.tsx | 109 ++++--- src/components/devices/XboxController.tsx | 100 ++++++- .../devices/emergencyStopControl.ts | 90 ++++-- src/locales/zh/index.ts | 8 +- src/router/routes.tsx | 7 +- 12 files changed, 566 insertions(+), 382 deletions(-) diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx index effa38b..ce861e6 100644 --- a/src/components/Layout.tsx +++ b/src/components/Layout.tsx @@ -172,6 +172,31 @@ export default function AppLayout() { return () => clearInterval(timer); }, [userInfo, timezone, dateFormat]); + // 当前账号没有默认首页(/ 或 /overview)权限时,自动跳转到第一个有权限的菜单页面 + useEffect(() => { + if (!Array.isArray(menuList) || menuList.length === 0) return; + const pathname = location.pathname; + if (pathname !== '/' && pathname !== '/overview') return; + + const leafPaths: string[] = []; + const collect = (items: any[]) => { + items.forEach(item => { + if (item.children && item.children.length > 0) { + collect(item.children); + } else if (typeof item.key === 'string' && item.key.startsWith('/') && !item.key.startsWith('/menu/')) { + leafPaths.push(item.key); + } + }); + }; + collect(menuList); + + const hasHomePermission = leafPaths.includes('/') || leafPaths.includes('/overview'); + const firstPath = leafPaths[0]; + if (!hasHomePermission && firstPath && firstPath !== pathname) { + navigate(firstPath, { replace: true }); + } + }, [menuList, location.pathname, navigate]); + useEffect(() => { setTime(nowInTz(timezone, dateFormat)); }, [timezone, dateFormat]); diff --git a/src/components/Map.jsx b/src/components/Map.jsx index 26a64e3..b32eb36 100644 --- a/src/components/Map.jsx +++ b/src/components/Map.jsx @@ -425,14 +425,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, if (!viewer || !Cesium) return; - console.log(message, "障碍物信息") const payload = message; const objects = Array.isArray(payload) ? payload : Array.isArray(payload?.objects) ? payload.objects : []; - console.log(objects, "障碍物信息2222") + console.log(objects, "障碍物信息") // 全量替换:先把地图上所有 live-obstacle 实体按 id 前缀全部移除 // 不依赖 liveObstacleEntities Map(避免历史孤儿实体残留) const toRemove = []; @@ -825,6 +824,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, // 特点:多层扩散动画光圈,独立一套 id // ============================================================ function ensureRealtimeHalo(viewer, position, color, size = 100, haloId = 'realtime_car_halo') { + return; const haloBaseId = haloId; const RING_COUNT = 3; const MIN_SIZE = 100; @@ -1377,6 +1377,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, function resolveDeviceStatus(device) { const fsRaw = device?.color; + return fsRaw === 'red' ? 'offline' : fsRaw === 'green' ? 'working' : fsRaw === 'blue' ? 'idle' : 'idle'; ////if (device?.onlineStatus == 0) return 'offline'; //if (stRaw !== undefined && stRaw !== null && stRaw !== '') { @@ -1466,6 +1467,42 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, offline: { text: t('devices.offline'), color: DEVICE_STATUS_COLORS.offline } }; const status = statusMap[stateKey] || statusMap.idle; + // 控制模式 / 系统模式 / 定位状态 文案映射(与任务规划页保持一致) + const controlModeMap = { + '0': t('devices.controlOff'), + '1': t('devices.localCpntrol'), + '2': t('devices.autoTask'), + '3': t('devices.remoteControl') + }; + const systemModeMap = { + '2': t('devices.autoTask'), + '3': t('devices.remoteControl') + }; + const fixStatusMap = { + no_fix: t('devices.noFix'), + single: t('devices.single'), + dgnss: t('devices.dgnss'), + ins: t('devices.ins'), + rtk_fixed: t('devices.rtkFixed'), + rtk_float: t('devices.rtkFloat'), + single_no_heading: t('devices.singleNoHeading'), + dgnss_no_heading: t('devices.dgnssNoHeading'), + rtk_fixed_no_heading: t('devices.rtkFixedNoHeading'), + rtk_float_no_heading: t('devices.rtkFloatNoHeading') + }; + // 以下状态行仅在设备携带对应字段时展示,普通标记点的悬浮提示不受影响 + const hasWorkStatus = robot.color !== undefined || robot.status !== undefined || robot.feStatus !== undefined; + const controlModeText = robot.controlMode !== undefined && robot.controlMode !== null && robot.controlMode !== '' + ? (controlModeMap[String(robot.controlMode)] || '-') + : ''; + const systemModeText = robot.sm !== undefined && robot.sm !== null && robot.sm !== '' + ? (systemModeMap[String(robot.sm)] || '-') + : ''; + const fixStatusText = robot.fix_status ? (fixStatusMap[robot.fix_status] || String(robot.fix_status)) : ''; + const batteryRaw = robot.battery !== undefined && robot.battery !== null + ? robot.battery + : (robot.batteryLevel !== undefined ? robot.batteryLevel : undefined); + const batteryText = batteryRaw !== undefined && batteryRaw !== null && batteryRaw !== '' ? Number(batteryRaw) + '%' : ''; let deviceValuesHTML = ''; if (robot.devicevalue && robot.devicevalue.length > 0) { deviceValuesHTML = robot.devicevalue.map((device) => ` @@ -1489,13 +1526,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, ` : ''} ${deviceValuesHTML ? `
${t('devices.deviceData')}:${deviceValuesHTML}
` : ''} + ${hasWorkStatus ? `
${t('systemSetting.status')}:${status.text}
` : ''} + ${controlModeText ? `
${t('devices.controlMode')}${controlModeText}
` : ''} + ${systemModeText ? `
${t('devices.systemMode')}:${systemModeText}
` : ''} + ${batteryText ? `
${t('devices.rtBattery')}:${batteryText}
` : ''}
${t('systemSetting.longitude')}:${lonStr}
${t('systemSetting.latitude')}:${latStr}
`; - //
${t('systemSetting.status')}: - // - // ${status.text} - //
} else { tooltip.innerHTML = `
📍 ${t('systemSetting.longitude')}:${lonStr}
@@ -3187,6 +3224,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, const haloId = `${id}_halo`; const haloColor = getDeviceHaloColor(device); + if (isRealtimeMode) { // 一机一光圈:实时模式下移除设备光圈,避免原位置残留 viewer.entities.removeById(haloId); @@ -3532,6 +3570,18 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, realtimePosition.lat && !isNaN(Number(realtimePosition.lon)) && !isNaN(Number(realtimePosition.lat)); + const rtHaloColor = realtimePosition?.status == "online" ? Cesium.Color.fromCssColorString('#19cd08') : Cesium.Color.fromCssColorString('#ef340b'); + + // ============================= + // 判断是否需要飞行 + // ============================= + + const needFlight = hasRealtime && !hasFlownRef.current && !realtimeHiddenRef.current; + + // ============================= + // 判断是否需要隐藏 + // ============================= + // ==================================== // 情况1:没有实时数据 -> 清理所有 realtime @@ -3669,7 +3719,6 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, const position = Cesium.Cartesian3.fromDegrees(lon, lat, 1); // 实时光圈颜色:优先取设备状态色,缺省蓝色(工作) - const rtHaloColor = Cesium.Color.fromCssColorString('#19cd08'); // ==================================== // 无人机模式:保持原来的逻辑 @@ -3940,7 +3989,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, realtimeCarEntityRef.current.billboard.rotation = rotation; // 实时光圈跟随机器移动,原光随动不残留 - ensureRealtimeHalo(viewer, position, rtHaloColor, 38); + //ensureRealtimeHalo(viewer, position, rtHaloColor, 38); } // 机器人模式只在导航模式下显示额外的实时轨迹线 @@ -4149,112 +4198,110 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, )} {/* 图例:返航点 / 分区 */} - {(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0 || stationOverlay.tempObstaclePoints.length > 0) && ( -
+
{t('devices.mapEditor.legend')}
+
+ + {t('devices.mapEditor.returnPoint')} +
+
+ + {t('devices.mapEditor.restArea')} +
+ +
+ + {t('devices.mapEditor.obstacle')} +
+ -
- )} + ⌖ + {t('devices.mapEditor.location')} + + ); diff --git a/src/components/devices/DPadControl.tsx b/src/components/devices/DPadControl.tsx index a4c6621..017250c 100644 --- a/src/components/devices/DPadControl.tsx +++ b/src/components/devices/DPadControl.tsx @@ -1,6 +1,7 @@ import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; +import { subscribeEmergencyStop } from './emergencyStopControl'; import { ChevronUp, ChevronDown, @@ -60,6 +61,10 @@ const DPadControl: React.FC = ({ const [pressed, setPressed] = useState>({}); const [speed, setSpeed] = useState(0.5); + // 急停锁存状态:与其他入口(手柄 / 功能按钮)共享同一份状态 + const [eStopActive, setEStopActive] = useState(false); + + useEffect(() => subscribeEmergencyStop(setEStopActive), []); // 每个物理输入单独记录,避免同方向不同按键互相干扰 // 例如 ArrowUp 和 W 可以同时按下 @@ -69,7 +74,6 @@ const DPadControl: React.FC = ({ const speedRef = useRef(0.5); const pressTimer = useRef(null); const disabledRef = useRef(disabled); - const emergencyTimer = useRef(null); const onGamepadUpdateRef = useRef(onGamepadUpdate); const onSpeedChangeRef = useRef(onSpeedChange); @@ -204,29 +208,11 @@ const DPadControl: React.FC = ({ stopTimer(); emit(); }, [stopTimer, emit]); - const startEmergency = useCallback(() => { + // 急停:切换锁存状态(第一次按下→发送 eStop=1,第二次按下→发送 eStop=0) + // 视觉由订阅到的共享锁存状态驱动,与手柄 / 其他入口保持一致 + const toggleEmergency = useCallback(() => { if (disabledRef.current) return; - - pressedRef.current = { - ...pressedRef.current, - center: true, - }; - setPressed({ ...pressedRef.current }); - onEmergencyStopRef.current?.(); - - if (emergencyTimer.current !== null) { - window.clearTimeout(emergencyTimer.current); - } - - emergencyTimer.current = window.setTimeout(() => { - pressedRef.current = { - ...pressedRef.current, - center: false, - }; - setPressed({ ...pressedRef.current }); - emergencyTimer.current = null; - }, 350); }, []); // 键盘控制:支持方向键 + WASD 组合 @@ -247,7 +233,7 @@ const DPadControl: React.FC = ({ // 防止长按空格时重复触发急停 if (!e.repeat) { - startEmergency(); + toggleEmergency(); } return; @@ -287,7 +273,7 @@ const DPadControl: React.FC = ({ window.removeEventListener('keyup', handleKeyUp); window.removeEventListener('blur', handleBlur); }; - }, [startPress, endPress, releaseAll, startEmergency]); + }, [startPress, endPress, releaseAll, toggleEmergency]); // 禁用时立即停止;卸载时清理定时器 useEffect(() => { @@ -317,17 +303,17 @@ const DPadControl: React.FC = ({ }; }, [disabled, stopTimer]); - // 紧急停止按钮的短暂按压动画 + // 急停锁存相关清理 - useEffect(() => { - return () => { - if (emergencyTimer.current !== null) { - window.clearTimeout(emergencyTimer.current); - } - stopTimer(); - }; - }, [stopTimer]); + //useEffect(() => { + // return () => { + // if (emergencyTimer.current !== null) { + // window.clearTimeout(emergencyTimer.current); + // } + // stopTimer(); + // }; + //}, [stopTimer]); const btnBase = 'flex items-center justify-center w-8 h-8 rounded-xl border transition-all duration-150 select-none active:scale-95 touch-none'; @@ -390,14 +376,14 @@ const DPadControl: React.FC = ({ type="button" aria-label={t('devices.emergencyStop')} disabled={disabled} - className={`${btnBase} relative ${pressed.center + className={`${btnBase} relative ${eStopActive ? 'border-red-500 bg-red-500/40 text-white shadow-[0_0_16px_rgba(239,68,68,0.6)]' : 'border-red-500/70 bg-red-500/10 text-red-400 hover:bg-red-500/20' } ${disabled ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer' }`} - onClick={startEmergency} + onClick={toggleEmergency} > diff --git a/src/components/devices/DeviceOverviewPage.tsx b/src/components/devices/DeviceOverviewPage.tsx index f80db7a..716d779 100644 --- a/src/components/devices/DeviceOverviewPage.tsx +++ b/src/components/devices/DeviceOverviewPage.tsx @@ -40,7 +40,7 @@ import envConfig from '../../../env'; import utils from '@/lib/utils.ts'; import { useUnitFormatter } from '@/lib/units'; import { useTranslation } from 'react-i18next'; -import { sendEmergencyStop } from './emergencyStopControl'; +import { sendEmergencyStop, subscribeEmergencyStop, syncEmergencyStop } from './emergencyStopControl'; import AlarmLevelTag from '../AlarmLevelTag.tsx'; import { getDeviceTastPool } from '@/api/device.ts'; import { backToRestPointCommand } from '@/api/mapEdit'; @@ -69,6 +69,10 @@ export default function DeviceOverviewPage() { const [deviceStatistics, setDeviceStatistics] = useState(null); const [currentSelectedRobot, setCurrentSelectedRobot] = useState(null); const [realtimeMap, setRealtimeMap] = useState({}); + // 急停锁存状态:与 DPadControl / XboxController 共享同一份状态 + const [eStopActive, setEStopActive] = useState(false); + + useEffect(() => subscribeEmergencyStop(setEStopActive), []); const controllerRef = useRef(null); const [messageApi, contextHolder] = message.useMessage(); const [taskList, setTaskList] = useState([]); @@ -429,11 +433,16 @@ export default function DeviceOverviewPage() { ...persistentDroneData, ...wsData, // 统一字段名 - capacity_percent: wsData.battery_level || persistentDroneData?.capacity_percent || selectedDevice.capacity_percent || 100 + capacity_percent: wsData.battery_level ?? wsData.battery ?? wsData.capacity_percent ?? persistentDroneData?.capacity_percent ?? selectedDevice.capacity_percent ?? 100 }; }, [selectedDevice, uavState, persistentHostData, persistentDroneData, realtimeMap]); + // 实时数据里的急停状态同步到共享锁存状态:true=已急停,false=未急停 + useEffect(() => { + syncEmergencyStop(realtimeDevice?.emergency_stop); + }, [realtimeDevice?.emergency_stop]); + // MQTT消息处理 const handleMqttMessage = useCallback((topic, message) => { @@ -701,6 +710,9 @@ export default function DeviceOverviewPage() { const sn = d.serialNumber || d.device_sn; const rt = realtimeMap[sn] || {}; const online = rt.status !== undefined ? (rt.status !== 'OFFLINE' ? 1 : 0) : d.onlineStatus; + // 状态 / 电量优先取实时消息 + const rtFeStatus = rt?.status; + const rtBattery = rt.battery ?? rt.battery_level ?? rt.capacity_percent ?? undefined; return { ...d, @@ -710,7 +722,12 @@ export default function DeviceOverviewPage() { status: online === 1 ? t('devices.online') : t('devices.offline'), onlineStatus: online, mode: rt.status === 'EXECUTING' ? '作业中' : rt.status === 'IDLE' ? t('devices.idle') : (d.feStatus == 1 ? '作业中' : d.feStatus == 2 ? t('devices.idle') : '离线'), - capacity_percent: rt.battery || d.capacity_percent || 100, + feStatus: rtFeStatus, + capacity_percent: rtBattery ?? d.capacity_percent ?? 100, + lastRunningStatus: { + ...(d.lastRunningStatus || {}), + battery: rtBattery ?? d.lastRunningStatus?.battery ?? d?.vehicleMessage?.battery + }, position: rt.position || d.position || '站内', task: rt.currentTaskName || d.task || (d.status === 4 ? '待命' : '作业中'), comm: rt.rssi ? `${rt.rssi}dBm` : (d.rssi ? `${d.rssi}dBm` : '良好'), @@ -724,9 +741,10 @@ export default function DeviceOverviewPage() { const handleReturn = () => message.info(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2')); const handleRecharge = () => message.info(t('devices.commandIssuedFixed2')); // 急停:点击时直接下发 button7(绕过控制权限校验),并提示已触发 - const handleEmergencyStop = () => { - sendEmergencyStop(selectedDevice?.serialNumber || ""); - message.error(t('devices.s73')); + const handleEmergencyStop = async () => { + const next = await sendEmergencyStop(selectedDevice?.serialNumber || ""); + if (next) message.error(t('devices.estopTriggered')); + else message.success(t('devices.estopNormal')); }; const fix2 = (val) => { @@ -871,17 +889,18 @@ export default function DeviceOverviewPage() { dataIndex: 'lastRunningStatus', width: 70, render: (lastRunningStatus) => { - const v = lastRunningStatus?.battery || 100; + const v = lastRunningStatus?.battery ?? "--"; return ; } - }, { title: t('aiAnalysis.location'), dataIndex: 'position', width: 90 }, + }, + // { title: t('aiAnalysis.location'), dataIndex: 'position', width: 90 }, //{ title: '累计作业面积', dataIndex: 'work_area', width: 110, render: v => `${Number(v || 0).toFixed(2)} ㎡` }, //{ title: t('devices.fixed2CurrentFixed2TaskSuspended2Fixed2'), dataIndex: 'task', width: 100 }, - { title: t('devices.statusFixed2'), dataIndex: 'comm', width: 100, render: v => }, + //{ title: t('devices.statusFixed2'), dataIndex: 'comm', width: 100, render: v => }, { title: t('roles.actions'), key: 'action', @@ -967,6 +986,13 @@ export default function DeviceOverviewPage() { } } }, + { + title: t('devices.executionCycle'), + width: 320, + render: (_, record) => { + return `${record.startTime || ''} - ${record.finishTime || ''}`; + } + }, { title: t('roles.status'), dataIndex: 'taskStaus', @@ -1018,7 +1044,7 @@ export default function DeviceOverviewPage() { dataSource={alarmList} scroll={{ x: 'max-content' }} columns={[ - { title: t('common.time'), dataIndex: 'alertTime', width: 90, render: (v) => {v} }, + { title: t('common.time'), dataIndex: 'alarmTime', width: 90, render: (v) => {v} }, { title: t('devices.device'), dataIndex: 'deviceName', width: 100, render: (v) => {v} }, { title: t('alerts.alarmTitle'), @@ -1076,8 +1102,8 @@ export default function DeviceOverviewPage() { )} {selectedDevice.deviceAlias || selectedDevice.drone_callsign || selectedDevice.callsign || selectedDevice.deviceName} - - {selectedDevice.onlineStatus == 1 ? t('devices.online') : t('devices.offline')} + + {realtimeDevice.status == 1 || realtimeDevice.status == 2 ? t('devices.online') : t('devices.offline')} */} {/**/} - + diff --git a/src/components/devices/DeviceStatusPage.tsx b/src/components/devices/DeviceStatusPage.tsx index 862654b..78a447d 100644 --- a/src/components/devices/DeviceStatusPage.tsx +++ b/src/components/devices/DeviceStatusPage.tsx @@ -77,8 +77,9 @@ import { useTranslation } from 'react-i18next'; import { backToRestPointCommand } from '@/api/mapEdit'; import CarReverseGuideLine from './CarReverseGuideLine'; import mowerImg from '../../assets/images/mower.png'; -import { sendEmergencyStop } from './emergencyStopControl'; +import { sendEmergencyStop, syncEmergencyStop } from './emergencyStopControl'; const { RangePicker } = DatePicker; + const { Text } = Typography; const ConsoleBadge = ({ online, text, color }: any) => ( @@ -461,6 +462,11 @@ export default function DeviceStatusPage() { ...locationInfo }; }, [device, wsDeviceInfo, isUAV, locationInfo]); + + // 实时下发的急停状态同步到共享锁存状态:true=已急停,false=未急停 + useEffect(() => { + syncEmergencyStop(runningStatus?.emergency_stop); + }, [runningStatus?.emergency_stop]); // 统一在线状态判断:优先实时数据,兜底接口数据 const isDeviceOnline = useMemo(() => { // 1. 优先检查实时数据源(WebSocket 推送的 wsDeviceInfo / locationInfo) @@ -546,6 +552,7 @@ export default function DeviceStatusPage() { lon: robotLon, lat: robotLat, heading: runningStatus?.yaw || wsDeviceInfo?.yaw || locationInfo?.yaw || device?.lastRunningStatus?.heading || 0, + status: Object.keys(wsDeviceInfo || {}).length > 0 ? 'online' : 'offline', }; } return null; @@ -665,6 +672,12 @@ export default function DeviceStatusPage() { }, [isUAV, device]); const mapDevices = useMemo(() => { if (!device) return null; + // 光圈颜色:无实时数据 → 红色;有实时数据 → feStatus 优先(1 工作中=green / 2 空闲=blue),status 兜底 + const hasRealtime = (wsDeviceInfo && Object.keys(wsDeviceInfo).length > 0) || (locationInfo && Object.keys(locationInfo).length > 0); + const rtStatus = String(runningStatus?.feStatus ?? runningStatus?.status ?? ''); + const deviceColor = hasRealtime + ? (rtStatus === '1' ? 'green' : 'blue') + : 'red'; // 优先使用持久化MQTT数据,其次使用uavState const lng = currentDroneData?.longitude ?? uavState?.longitude ?? runningStatus?.longitude ?? device.longitude; const lat = currentDroneData?.latitude ?? uavState?.latitude ?? runningStatus?.latitude ?? device.latitude; @@ -678,14 +691,14 @@ export default function DeviceStatusPage() { longitude: lng, latitude: lat, name: device?.deviceAlias || device?.callsign || device?.deviceName || t('devices.device'), - color: "red", + color: deviceColor, type: isUAV ? 'drone' : device?.productName?.includes(t('constants.mower')) ? 'mower' : 'robot', }; - }, [device, isUAV, runningStatus, uavState, currentDroneData]); + }, [device, isUAV, runningStatus, uavState, currentDroneData, wsDeviceInfo, locationInfo]); const handleControlMode = (controlMode: number) => { if (!selectedSn) { messageApi.error(t('devices.selectDevice')); @@ -700,7 +713,7 @@ export default function DeviceStatusPage() { deviceId: selectedSn } modeChage(data).then(res => { - if (res.code == 200) { + if (res.code == 200 && res?.data) { messageApi.success(t('devices.controlModeSuccess')); } else { messageApi.error(res.msg || t('devices.controlModeFail')); @@ -771,6 +784,63 @@ export default function DeviceStatusPage() { sendSteerFrame(index, true); window.setTimeout(() => sendSteerFrame(index, false), 300); }, [sendSteerFrame]); + // 方向盘功能按钮:三组互斥锁存(割刀启动/停止、底盘升/降、点火/熄火) + type SteerGroup = 'blade' | 'chassis' | 'power'; + const EMPTY_STEER_STATE: Record = { blade: null, chassis: null, power: null }; + const [steerState, setSteerState] = useState>(EMPTY_STEER_STATE); + const steerStateRef = useRef(steerState); + steerStateRef.current = steerState; + + // 按锁存状态组装遥控帧:割刀统一走 button2(启动=true,停止/未点击=false) + const buildSteerButtons = useCallback((s: Record) => { + const buttons = new Array(17).fill(false); + buttons[2] = s.blade === 'start'; // 割刀:button2 + buttons[0] = s.chassis === 'up'; // 底盘升起 + buttons[1] = s.chassis === 'down'; // 底盘下降 + buttons[4] = s.power === 'ignition'; // 点火 + buttons[5] = s.power === 'shutdown'; // 熄火 + return buttons; + }, []); + + const sendSteerState = useCallback((next: Record) => { + steerStateRef.current = next; + setSteerState(next); + handleGamepadUpdate({ + buttons: buildSteerButtons(next), + axes: [0, 0, 0, 0], + connected: true, + ts: Date.now(), + }); + }, [buildSteerButtons, handleGamepadUpdate]); + + // 点击:未激活→激活;再次点击→取消;切换同组另一个按钮时自动互斥 + const toggleSteerGroup = useCallback((group: SteerGroup, value: string) => { + if (blockIfGamepadConnected()) return; + const prev = steerStateRef.current; + sendSteerState({ ...prev, [group]: prev[group] === value ? null : value } as Record); + }, [blockIfGamepadConnected, sendSteerState]); + + // 锁存期间每 100ms 持续发送,保持"按住"语义 + useEffect(() => { + if (steerState.blade === null && steerState.chassis === null && steerState.power === null) return; + const id = window.setInterval(() => { + const cur = steerStateRef.current; + if (cur.blade === null && cur.chassis === null && cur.power === null) return; + handleGamepadUpdate({ + buttons: buildSteerButtons(cur), + axes: [0, 0, 0, 0], + connected: true, + ts: Date.now(), + }); + }, 200); + return () => window.clearInterval(id); + }, [steerState, buildSteerButtons, handleGamepadUpdate]); + + // 切换设备时清空锁存,避免残留 + useEffect(() => { + steerStateRef.current = EMPTY_STEER_STATE; + setSteerState(EMPTY_STEER_STATE); + }, [selectedSn]); const handleControlModal = useCallback(() => { console.log('请求控制权限'); controllerRef.current?.requestControl(); @@ -1270,9 +1340,9 @@ export default function DeviceStatusPage() { } label={t('devices.rtLeftTemp')} value={(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp), 1).label : '-'} /> } label={t('devices.rtRightTemp')} value={(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp), 1).label : '-'} /> } label={t('devices.rtMainTemp')} value={(runningStatus?.main_temperature ?? runningStatus?.chipTemp) !== undefined ? formatTemperature(Number(runningStatus?.main_temperature ?? runningStatus?.chipTemp), 1).label : '-'} /> - } label={t('devices.motionStatus')} value={runningStatus?.motion === 'moving' ? t('devices.motionMoving') : runningStatus?.motion === 'stopped' ? t('devices.motionStopped') : runningStatus?.motion === 'blocked' ? t('devices.motionBlocked') : '-'} /> + {/*} label={t('devices.motionStatus')} value={runningStatus?.motion === 'moving' ? t('devices.motionMoving') : runningStatus?.motion === 'stopped' ? t('devices.motionStopped') : runningStatus?.motion === 'blocked' ? t('devices.motionBlocked') : '-'} />*/} } label={t('devices.cutterSpedd')} value={runningStatus?.cutter_speed ?? "-"} /> - } label={t('devices.rtEmergency')} value={runningStatus?.emergency_stop === true ? t('devices.estopTriggered') : runningStatus?.emergency_stop === false ? t('devices.estopNormal') : '-'} /> + } label={t('devices.rtEmergency')} value={runningStatus?.emergency_stop == "true" ? t('devices.estopTriggered') : runningStatus?.emergency_stop == "false" ? t('devices.estopNormal') : '-'} /> {/*} label={t('devices.rtLeftMeasureRpm')} value={(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed) !== undefined ? Number(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/} {/*} label={t('devices.rtRightMeasureRpm')} value={(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed) !== undefined ? Number(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/} } label={t('devices.rtLeftMotorRpm')} value={runningStatus?.left_motor_rpm !== undefined ? Number(runningStatus?.left_motor_rpm).toFixed(1) + 'rpm' : '-'} /> @@ -1453,16 +1523,16 @@ export default function DeviceStatusPage() {
- } label={t('devices.steer.ignition')} color="#22c55e" onPressStart={() => sendSteerFrame(4, true)} onPressEnd={() => sendSteerFrame(4, false)} /> - } label={t('devices.steer.shutdown')} color="#ef4444" onPressStart={() => sendSteerFrame(5, true)} onPressEnd={() => sendSteerFrame(5, false)} /> + } label={t('devices.steer.ignition')} color="#22c55e" active={steerState.power === 'ignition'} onToggle={() => toggleSteerGroup('power', 'ignition')} /> + } label={t('devices.steer.shutdown')} color="#ef4444" active={steerState.power === 'shutdown'} onToggle={() => toggleSteerGroup('power', 'shutdown')} />
- } label={t('devices.steer.chassisUp')} color="#3b82f6" onPressStart={() => sendSteerFrame(0, true)} onPressEnd={() => sendSteerFrame(0, false)} /> - } label={t('devices.steer.chassisDown')} color="#3b82f6" onPressStart={() => sendSteerFrame(1, true)} onPressEnd={() => sendSteerFrame(1, false)} /> + } label={t('devices.steer.chassisUp')} color="#3b82f6" active={steerState.chassis === 'up'} onToggle={() => toggleSteerGroup('chassis', 'up')} /> + } label={t('devices.steer.chassisDown')} color="#3b82f6" active={steerState.chassis === 'down'} onToggle={() => toggleSteerGroup('chassis', 'down')} />
- } label={t('devices.steer.cutterAccel')} color="#f59e0b" onPressStart={() => sendSteerFrame(2, true)} onPressEnd={() => sendSteerFrame(2, false)} /> - } label={t('devices.steer.cutterDecel')} color="#f59e0b" onPressStart={() => sendSteerFrame(3, true)} onPressEnd={() => sendSteerFrame(3, false)} /> + } label={t('devices.steer.cutterAccel')} color="#f59e0b" active={steerState.blade === 'start'} onToggle={() => toggleSteerGroup('blade', 'start')} /> + } label={t('devices.steer.cutterDecel')} color="#f59e0b" active={steerState.blade === 'stop'} onToggle={() => toggleSteerGroup('blade', 'stop')} />
diff --git a/src/components/devices/MapEditorView.tsx b/src/components/devices/MapEditorView.tsx index b1d7f94..2ea2a1f 100644 --- a/src/components/devices/MapEditorView.tsx +++ b/src/components/devices/MapEditorView.tsx @@ -181,11 +181,13 @@ export const MapEditorView = React.forwardRef(function MapEditorView( }, [presetRoutes, presetModeFilter]); const selectRobot = useMemo(() => { if (!Array.isArray(robots)) return []; + // 任务规划页面:机器没有实时消息(无实时位置)时,不在地图上显示 + if (extraMapProps && !extraMapProps.realtimePosition) return []; return robots .filter(robot => robot.serialNumber == selectedRobotId) .map(robot => (extraMapProps?.deviceColor ? { ...robot, color: extraMapProps.deviceColor } : robot)); - }, [selectedRobotId, robots, extraMapProps?.deviceColor]); + }, [selectedRobotId, robots, extraMapProps?.deviceColor, extraMapProps?.realtimePosition]); useEffect(() => { if (extraMapProps.polyPoints?.length > 0) { setPolyPoints(extraMapProps.polyPoints); diff --git a/src/components/devices/Steerbutton.tsx b/src/components/devices/Steerbutton.tsx index 019309c..069f9ad 100644 --- a/src/components/devices/Steerbutton.tsx +++ b/src/components/devices/Steerbutton.tsx @@ -1,122 +1,33 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; - interface SteerButtonProps { icon: React.ReactNode; label: string; color: string; - onPressStart?: () => void; - onPressEnd?: () => void; - interval?: number; + // 受控高亮:由父组件统一管理,保证同组按钮互斥(不会同时显示为按下) + active?: boolean; + disabled?: boolean; + onToggle?: () => void; } +/** + * 锁存按钮(受控): + * 高亮状态完全由 active 决定,点击只触发 onToggle。 + * 持续发送 / 互斥逻辑由父组件统一管理。 + */ const SteerButton = ({ icon, label, color, - onPressStart, - onPressEnd, - interval = 100, + active = false, + disabled = false, + onToggle, }: SteerButtonProps) => { - const [pressed, setPressed] = useState(false); - - // 是否处于按下状态 - const holdingRef = useRef(false); - - // 定时发送句柄 - const timerRef = useRef | null>(null); - - // 保存最新的回调,避免定时器使用过期闭包 - const onPressStartRef = useRef(onPressStart); - const onPressEndRef = useRef(onPressEnd); - - useEffect(() => { - onPressStartRef.current = onPressStart; - }, [onPressStart]); - - useEffect(() => { - onPressEndRef.current = onPressEnd; - }, [onPressEnd]); - - // 停止长按 - const stopHold = useCallback(() => { - if (!holdingRef.current) return; - - holdingRef.current = false; - - if (timerRef.current !== null) { - clearTimeout(timerRef.current); - timerRef.current = null; - } - - setPressed(false); - - // 只在有效按压结束时发送一次释放数据 - onPressEndRef.current?.(); - }, []); - - // 开始长按 - const startHold = useCallback(() => { - // 防止重复触发 - if (holdingRef.current) return; - - holdingRef.current = true; - setPressed(true); - - // 立即发送第一帧 - onPressStartRef.current?.(); - - // 持续发送 - const scheduleNext = () => { - if (!holdingRef.current) return; - - timerRef.current = setTimeout(() => { - if (!holdingRef.current) return; - - onPressStartRef.current?.(); - - scheduleNext(); - }, interval); - }; - - scheduleNext(); - }, [interval]); - - // 组件卸载时清理定时器 - useEffect(() => { - return () => { - holdingRef.current = false; - - if (timerRef.current !== null) { - clearTimeout(timerRef.current); - timerRef.current = null; - } - }; - }, []); - return (