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')}
}
@@ -1089,7 +1115,7 @@ export default function DeviceOverviewPage() {
- {t('devices.batteryLevel')}: {fix2(realtimeDevice?.capacity_percent || realtimeDevice?.lastRunningStatus?.battery || 100)}%
+ {t('devices.batteryLevel')}: {fix2(realtimeDevice?.battery)}%
{realtimeDevice?.environment_temperature && (
@@ -1159,7 +1185,7 @@ export default function DeviceOverviewPage() {
{/*{t('video.pause')}*/}
{t('devices.returnHome')}
{/*{t('devices.s24')}*/}
- {t('devices.s29')}
+ {eStopActive ? t('devices.estopTriggered') : t('devices.s29')}
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 (
{
- e.preventDefault();
- e.stopPropagation();
-
- // 仅响应鼠标左键,触摸和笔不受影响
- if (e.pointerType === 'mouse' && e.button !== 0) return;
-
- // 捕获指针,确保在按钮外松开也能收到事件
- e.currentTarget.setPointerCapture(e.pointerId);
-
- startHold();
- }}
- onPointerUp={(e) => {
- e.preventDefault();
- e.stopPropagation();
- stopHold();
- }}
- onPointerCancel={stopHold}
- onLostPointerCapture={stopHold}
+ aria-pressed={active}
+ disabled={disabled}
+ onClick={onToggle}
onContextMenu={(e) => e.preventDefault()}
style={{
flex: '1 1 0',
@@ -128,15 +39,18 @@ const SteerButton = ({
minHeight: 46,
padding: '6px 4px',
borderRadius: 8,
- border: `1px solid ${pressed ? color : `${color}55`}`,
+ border: `1px solid ${active ? color : `${color}55`}`,
+ background: active ? `${color}22` : 'transparent',
color,
- cursor: 'pointer',
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.4 : 1,
userSelect: 'none',
touchAction: 'none',
- transform: pressed ? 'scale(0.94)' : 'scale(1)',
- boxShadow: pressed ? `0 0 14px ${color}66` : 'none',
+ transform: active ? 'scale(0.97)' : 'scale(1)',
+ boxShadow: active ? `0 0 14px ${color}66, inset 0 0 8px ${color}22` : 'none',
+ fontWeight: active ? 700 : 500,
transition:
- 'transform .08s, background .12s, border-color .12s, box-shadow .12s',
+ 'transform .08s, background .12s, border-color .12s, box-shadow .12s, font-weight .12s, opacity .12s',
}}
>
diff --git a/src/components/devices/TaskPlanningView.tsx b/src/components/devices/TaskPlanningView.tsx
index 86008af..f450cd0 100644
--- a/src/components/devices/TaskPlanningView.tsx
+++ b/src/components/devices/TaskPlanningView.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef, useMemo } from 'react';
-import { Row, Col, Card, Button, Space, Table, Tag, Typography, Badge, Tabs, Input, Switch, Tooltip, Timeline, Select, message, DatePicker, TimePicker, Popconfirm, App, Radio, Empty } from 'antd';
+import { Row, Col, Card, Button, Space, Table, Tag, Typography, Badge, Tabs, Input, Switch, Tooltip, Timeline, Select, message, DatePicker, TimePicker, Popconfirm, App, Radio, Empty, Collapse } from 'antd';
import { PlusOutlined, ImportOutlined, NodeIndexOutlined, SaveOutlined, DeleteOutlined, CloseOutlined, ReloadOutlined, ExclamationCircleOutlined, EnvironmentOutlined, EnvironmentFilled } from '@ant-design/icons';
import { Car, Navigation, MapPinned, Route, Satellite, LayoutGrid, CheckCircle2, AlertCircle, TrendingUp, Maximize2 } from 'lucide-react';
import TaskTypeRadio from '../taskRadio/taskRadio';
@@ -80,6 +80,8 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const [routeSearch, setRouteSearch] = useState('');
const [routeList, setRouteList] = useState([]);
+ // 任务下发:按模式分组的路线(折叠面板使用)
+ const dispatchRouteGroups = useMemo(() => groupRoutesByMode(routeList, t), [routeList, t]);
const [consecutiveLoading, setConsecutiveLoading] = useState(false);
// 执行任务弹窗
@@ -212,18 +214,6 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const controllerRef = useRef(null);
const isFirstConnect = useRef(true);
const mapRef = useRef(null);
- const fixStatusMap: Record = {
- '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 handleFinish = (data) => {
@@ -1739,8 +1729,8 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
points,
polyPoints,
routeMode,
- realtimePosition,
- realtimeDevice: targetRobot ? { ...targetRobot, color: robotMapColor } : targetRobot,
+ realtimePosition: robotRealtimePosition ? realtimePosition : null,
+ realtimeDevice: targetRobot ? { ...targetRobot, ...(robotRealtimePosition || {}), color: robotMapColor } : targetRobot,
deviceColor: robotMapColor,
realtimeType: 'robot',
ifClearNavLine: clearNavLine,
@@ -1754,7 +1744,7 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
onSave={() => fetchRouteList()}
/>
- {/* 机器人状态悬浮面板 - 绝对定位左上角 */}
+ {/* 机器人操作面板(状态信息改为鼠标悬浮机器时在地图上显示) */}
{execute && executingRobot && (
-
+ {/*
{t('devices.systemMode')}
{(() => {
const mode = robotRealtimePosition?.sm || robotRealtimePosition?.sm;
@@ -1850,16 +1840,13 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
);
})()}
-
+ */}
+
-
- {t('devices.location')}
- {robotRealtimePosition?.fix_status ? fixStatusMap[robotRealtimePosition?.fix_status] : t('constants.locationUnknown')}
-
{/* 视频开关 */}
@@ -2301,61 +2288,61 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
{(!routeList || routeList.length === 0) ? (
) : (
-
- {groupRoutesByMode(routeList, t).map(group => (
-
-
+
g.key)}
+ style={{ maxHeight: 280, overflowY: 'auto' }}
+ items={dispatchRouteGroups.map(group => ({
+ key: group.key,
+ label: (
+
{group.label}
({group.items.length})
-
+ ),
+ children: (
+
{group.items.map(route => {
const checked = dispatchRouteIds.includes(route.id);
-
return (
- {
- // 按路线下发:单选
- setDispatchRouteIds(nextChecked ? [route.id] : []);
-
- if (nextChecked) {
- // 选择下发路径时,取消上方任务规划的选中
+ onClick={() => {
+ // 按路线下发:单选,一行一个;再次点击可取消
+ setDispatchRouteIds(checked ? [] : [route.id]);
+ if (!checked) {
setEditorType(null);
flyToRoute(route.id);
}
}}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+ width: '100%',
+ boxSizing: 'border-box',
+ padding: '6px 10px',
+ borderRadius: 6,
+ cursor: 'pointer',
+ border: `1px solid ${checked ? '#1677ff' : '#e5e6eb'}`,
+ background: checked ? '#f0f7ff' : '#fff',
+ fontSize: 12,
+ color: '#344054',
+ transition: 'all .15s',
+ }}
>
-
- {route.workName || route.name}
-
-
+
+ {route.workName || route.name}
+ {checked && ✓}
+
);
})}
-
- ))}
-
+ )
+ }))}
+ />
)}
)}
diff --git a/src/components/devices/XboxController.tsx b/src/components/devices/XboxController.tsx
index bd900bb..fe7da47 100644
--- a/src/components/devices/XboxController.tsx
+++ b/src/components/devices/XboxController.tsx
@@ -1,6 +1,7 @@
import React, { useEffect, useState, useRef } from 'react';
+import { sendEmergencyStop, subscribeEmergencyStop } from './emergencyStopControl';
import { useTranslation } from 'react-i18next';
-const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
+const XboxController = ({ onGamepadUpdate, onConnectionChange, deviceId }: { onGamepadUpdate?: any; onConnectionChange?: any; deviceId?: string }) => {
const { t } = useTranslation();
const [gamepadState, setGamepadState] = useState<{
buttons: boolean[];
@@ -23,19 +24,94 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
const lastSendRef = useRef(0);
const SEND_INTERVAL = 1000 / 10; // 20Hz
const lastPayloadRef = useRef('');
+ // 物理按键上一帧状态(上升沿检测)
+ const lastButtonsRef = useRef(new Array(17).fill(false));
+ const [eStopActive, setEStopActive] = useState(false);
+ const eStopActiveRef = useRef(false);
+ eStopActiveRef.current = eStopActive;
+ // 锁存状态:底盘升降 / 点火熄火,同组互斥(不会同时显示为按下)
+ // 割刀不锁存:按下 X → button2=true,按下 Y → button2=false,都没按 → button2=null
+ const [latchState, setLatchState] = useState<{
+ chassisUp: boolean;
+ chassisDown: boolean;
+ ignition: boolean;
+ shutdown: boolean;
+ }>({
+ chassisUp: false,
+ chassisDown: false,
+ ignition: false,
+ shutdown: false,
+ });
+ const latchRef = useRef(latchState);
+ latchRef.current = latchState;
+ // 订阅急停锁存状态变化:任何入口触发急停都能同步到按钮视觉
+ useEffect(() => {
+ const unsub = subscribeEmergencyStop((val) => setEStopActive(val));
+ return unsub;
+ }, []);
const updateGamepad = () => {
const gp = navigator.getGamepads()[0];
if (gp) {
+ const physical = gp.buttons.map(b => b.pressed);
+ const prev = lastButtonsRef.current;
+ const axes = gp.axes.map(normalizeAxis);
+ // 上升沿:底盘(A 升 / B 降)、点火熄火(LB / RB),同组按键互斥
+ const next = { ...latchRef.current };
+ if (physical[0] && !prev[0]) {
+ next.chassisUp = !next.chassisUp;
+ if (next.chassisUp) next.chassisDown = false;
+ }
+ if (physical[1] && !prev[1]) {
+ next.chassisDown = !next.chassisDown;
+ if (next.chassisDown) next.chassisUp = false;
+ }
+ if (physical[4] && !prev[4]) {
+ next.ignition = !next.ignition;
+ if (next.ignition) next.shutdown = false;
+ }
+ if (physical[5] && !prev[5]) {
+ next.shutdown = !next.shutdown;
+ if (next.shutdown) next.ignition = false;
+ }
+ // button8 (急停) 上升沿 → 调接口,不走 WebSocket
+ if (physical[8] && !prev[8] && deviceId) {
+ sendEmergencyStop(deviceId);
+ }
+ lastButtonsRef.current = physical;
+ const latchChanged =
+ next.chassisUp !== latchRef.current.chassisUp ||
+ next.chassisDown !== latchRef.current.chassisDown ||
+ next.ignition !== latchRef.current.ignition ||
+ next.shutdown !== latchRef.current.shutdown;
+ if (latchChanged) {
+ latchRef.current = next;
+ setLatchState(next);
+ }
+ const latch = latchChanged ? next : latchRef.current;
+ // 割刀:按下 X → button2=true,按下 Y → button2=false,两个都没按 → button2=null
+ const bladeValue = physical[2] ? true : physical[3] ? false : null;
+ // 锁存状态写入发送帧
+ const wsButtons: any[] = physical.slice();
+ wsButtons[0] = latch.chassisUp;
+ wsButtons[1] = latch.chassisDown;
+ wsButtons[2] = bladeValue;
+ wsButtons[3] = false; // Y 仅作为"割刀停止"指令,不再透传为按键
+ wsButtons[4] = latch.ignition;
+ wsButtons[5] = latch.shutdown;
+ wsButtons[8] = false;
+ // 手柄图形显示:割刀启动/停止同一时刻只点亮一个
+ const displayButtons = wsButtons.slice();
+ displayButtons[3] = !physical[2] && physical[3];
const state = {
- buttons: gp.buttons.map(b => b.pressed),
- axes: gp.axes.map(normalizeAxis),
+ buttons: displayButtons,
+ axes,
connected: true,
ts: Date.now(),
};
setGamepadState(state);
const payload = JSON.stringify({
- buttons: state.buttons,
- axes: state.axes,
+ buttons: wsButtons,
+ axes,
});
const now = performance.now();
if (
@@ -81,6 +157,10 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
console.log('❌ Gamepad disconnected');
//handleControlModal({ control: false });
setGamepadState(prev => ({ ...prev, connected: false }));
+ // 断开连接时清空锁存,避免按钮残留为按下状态
+ const reset = { chassisUp: false, chassisDown: false, ignition: false, shutdown: false };
+ latchRef.current = reset;
+ setLatchState(reset);
};
window.addEventListener('gamepadconnected', handleConnect);
window.addEventListener('gamepaddisconnected', handleDisconnect);
@@ -177,15 +257,17 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
{/* X */}
X
- {/* Y */}
+ Y
Y
{/* Menu Buttons + Text Label button8=急停, button9=Menu */}
-
- 急停
+ {/* Emergency Stop button 急停 */}
+
+ STOP
+ {/*急停*/}
- Menu
+
);
diff --git a/src/components/devices/emergencyStopControl.ts b/src/components/devices/emergencyStopControl.ts
index db1a002..3eb1af3 100644
--- a/src/components/devices/emergencyStopControl.ts
+++ b/src/components/devices/emergencyStopControl.ts
@@ -1,28 +1,76 @@
-import { wsManager } from '../WebSocketManager';
+import { eStopChange } from '../../api/device';
-// 急停对应手柄 button7(buttons 数组下标 7)
-const EMERGENCY_STOP_BUTTON_INDEX = 7;
+// 本地锁存状态
+let active = false;
+const listeners = new Set<(val: boolean) => void>();
-// 构建单帧遥控数据:仅急停位按下/松开,其余按键与摇杆轴保持空闲
-const buildFrame = (pressed: boolean) => {
- const buttons = new Array(17).fill(false);
- buttons[EMERGENCY_STOP_BUTTON_INDEX] = pressed;
- return { buttons, axes: [0, 0, 0, 0], connected: true, ts: Date.now() };
+const emit = () => {
+ for (const fn of listeners) {
+ try { fn(active); } catch { }
+ }
};
-/**
- * 单击急停:绕过控制权限校验,直接经 WebSocket 下发 button7;
- * 约 300ms 后自动补发一帧复位数据,模拟按下再松开。
- */
-export const sendEmergencyStop = (userInfo?: any) => {
- const send = (pressed: boolean) =>
- wsManager.send({
- type: 'remoteControl',
- remoteData: buildFrame(pressed),
- token: userInfo?.token,
- userName: userInfo?.username,
+/** 订阅急停锁存状态变化,返回 unsubscribe */
+export const subscribeEmergencyStop = (fn: (val: boolean) => void) => {
+ listeners.add(fn);
+ fn(active); // 立即回调一次当前值
+ return () => listeners.delete(fn);
+};
+
+/** 由实时数据(runningStatus.emergency_stop)同步急停状态,只更新本地显示,不发请求 */
+export const syncEmergencyStop = (val: any) => {
+ // 兼容后端可能下发的 boolean / 1 / 0 / "true" / "false"
+ if (val === undefined || val === null || val === '') return;
+ const next = val === true || val === 1 || val === '1' || val === 'true';
+ if (active === next) return;
+ active = next;
+ emit();
+};
+
+/** 切换急停状态(toggle) */
+export const sendEmergencyStop = async (deviceId: string) => {
+ if (!deviceId) return active;
+
+ const newActive = !active;
+
+ console.log('[EmergencyStop] eStop=' + (newActive ? 1 : 0) + ' sending');
+
+ try {
+ const res = await eStopChange({
+ deviceId,
+ eStop: newActive ? 1 : 0
});
+ if (res?.code == 200) {
+ active = newActive;
+ emit();
- send(true);
- setTimeout(() => send(false), 300);
+ console.log('[EmergencyStop] eStop=' + (active ? 1 : 0) + ' success');
+ } else {
+ console.warn('[EmergencyStop] eStop failed:', res);
+ }
+
+ } catch (err) {
+ console.error('[EmergencyStop] eStop request error:', err);
+ }
+
+ return active;
};
+
+export const toggleEmergencyStop = sendEmergencyStop;
+export const startEmergencyStop = async (deviceId: string) => {
+ if (!deviceId || active) return;
+ await sendEmergencyStop(deviceId);
+};
+export const stopEmergencyStop = async (deviceId: string) => {
+ if (!deviceId || !active) return;
+ await sendEmergencyStop(deviceId);
+};
+
+export const isEmergencyStopActive = () => active;
+
+if (typeof window !== 'undefined') {
+ window.addEventListener('beforeunload', () => {
+ active = false;
+ emit();
+ });
+}
diff --git a/src/locales/zh/index.ts b/src/locales/zh/index.ts
index 5e543fd..22ae8c6 100644
--- a/src/locales/zh/index.ts
+++ b/src/locales/zh/index.ts
@@ -707,9 +707,9 @@ const zh = {
bKey: 'B 键',
bKeyDesc: '降底盘',
xKey: 'X 键',
- xKeyDesc: '割刀加速',
+ xKeyDesc: '割刀启动',
yKey: 'Y 键',
- yKeyDesc: '割刀减速',
+ yKeyDesc: '割刀停止',
lbKey: 'LB 键',
lbDesc: '点火',
rbKey: 'RB 键',
@@ -726,8 +726,8 @@ const zh = {
chassisDown: '底盘下降',
chassisDownHint: '底盘下降',
cutterControl: '割刀控制',
- cutterAccel: '割刀加速',
- cutterDecel: '割刀减速',
+ cutterAccel: '割刀启动',
+ cutterDecel: '割刀停止',
},
features: {
title: '功能控制',
diff --git a/src/router/routes.tsx b/src/router/routes.tsx
index aefa2c9..5e87fd7 100644
--- a/src/router/routes.tsx
+++ b/src/router/routes.tsx
@@ -1,4 +1,4 @@
-import React, { lazy, Suspense } from 'react';
+import React, { lazy, Suspense } from 'react';
import type { RouteObject } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -150,10 +150,7 @@ export const routes: RouteObject[] = [
path: 'agri',
element: withSuspense(Agri)
},
- {
- path: 'alerts/all',
- element: withSuspense(Alerts)
- },
+
{
path: 'reportCenter/overview',
element: withSuspense(ReportCenterOverview)