根据不同账号 显示的首页优化 规划界面 悬浮显示 状态信息 全局急停状态统一 割刀 根据新方案对接 两个状态 任务路线 显示为 抽拉式一行一个 xbox组件优化数据发送,重构数据

This commit is contained in:
mmc
2026-11-14 18:23:27 +08:00
parent f057e0b72c
commit 831e1086d3
12 changed files with 566 additions and 382 deletions

View File

@@ -172,6 +172,31 @@ export default function AppLayout() {
return () => clearInterval(timer); return () => clearInterval(timer);
}, [userInfo, timezone, dateFormat]); }, [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(() => { useEffect(() => {
setTime(nowInTz(timezone, dateFormat)); setTime(nowInTz(timezone, dateFormat));
}, [timezone, dateFormat]); }, [timezone, dateFormat]);

View File

@@ -425,14 +425,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
if (!viewer || !Cesium) return; if (!viewer || !Cesium) return;
console.log(message, "障碍物信息")
const payload = message; const payload = message;
const objects = Array.isArray(payload) const objects = Array.isArray(payload)
? payload ? payload
: Array.isArray(payload?.objects) : Array.isArray(payload?.objects)
? payload.objects ? payload.objects
: []; : [];
console.log(objects, "障碍物信息2222") console.log(objects, "障碍物信息")
// 全量替换:先把地图上所有 live-obstacle 实体按 id 前缀全部移除 // 全量替换:先把地图上所有 live-obstacle 实体按 id 前缀全部移除
// 不依赖 liveObstacleEntities Map(避免历史孤儿实体残留) // 不依赖 liveObstacleEntities Map(避免历史孤儿实体残留)
const toRemove = []; const toRemove = [];
@@ -825,6 +824,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// 特点:多层扩散动画光圈,独立一套 id // 特点:多层扩散动画光圈,独立一套 id
// ============================================================ // ============================================================
function ensureRealtimeHalo(viewer, position, color, size = 100, haloId = 'realtime_car_halo') { function ensureRealtimeHalo(viewer, position, color, size = 100, haloId = 'realtime_car_halo') {
return;
const haloBaseId = haloId; const haloBaseId = haloId;
const RING_COUNT = 3; const RING_COUNT = 3;
const MIN_SIZE = 100; const MIN_SIZE = 100;
@@ -1377,6 +1377,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
function resolveDeviceStatus(device) { function resolveDeviceStatus(device) {
const fsRaw = device?.color; const fsRaw = device?.color;
return fsRaw === 'red' ? 'offline' : fsRaw === 'green' ? 'working' : fsRaw === 'blue' ? 'idle' : 'idle'; return fsRaw === 'red' ? 'offline' : fsRaw === 'green' ? 'working' : fsRaw === 'blue' ? 'idle' : 'idle';
////if (device?.onlineStatus == 0) return 'offline'; ////if (device?.onlineStatus == 0) return 'offline';
//if (stRaw !== undefined && stRaw !== null && stRaw !== '') { //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 } offline: { text: t('devices.offline'), color: DEVICE_STATUS_COLORS.offline }
}; };
const status = statusMap[stateKey] || statusMap.idle; 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 = ''; let deviceValuesHTML = '';
if (robot.devicevalue && robot.devicevalue.length > 0) { if (robot.devicevalue && robot.devicevalue.length > 0) {
deviceValuesHTML = robot.devicevalue.map((device) => ` deviceValuesHTML = robot.devicevalue.map((device) => `
@@ -1489,13 +1526,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
</span> </span>
` : ''}</div > ` : ''}</div >
${deviceValuesHTML ? `<div style="margin-top:8px;"><strong>${t('devices.deviceData')}:</strong>${deviceValuesHTML}</div>` : ''} ${deviceValuesHTML ? `<div style="margin-top:8px;"><strong>${t('devices.deviceData')}:</strong>${deviceValuesHTML}</div>` : ''}
${hasWorkStatus ? `<div>${t('systemSetting.status')}:<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${status.color};margin-right:4px;"></span><span style="color:${status.color};font-weight:bold">${status.text}</span></div>` : ''}
${controlModeText ? `<div>${t('devices.controlMode')}${controlModeText}</div>` : ''}
${systemModeText ? `<div>${t('devices.systemMode')}:${systemModeText}</div>` : ''}
${batteryText ? `<div>${t('devices.rtBattery')}:${batteryText}</div>` : ''}
<div>${t('systemSetting.longitude')}:${lonStr}</div> <div>${t('systemSetting.longitude')}:${lonStr}</div>
<div>${t('systemSetting.latitude')}:${latStr}</div> <div>${t('systemSetting.latitude')}:${latStr}</div>
`; `;
//<div>${t('systemSetting.status')}:
// <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${status.color};margin-right:4px;"></span>
// <span style="color:${status.color};font-weight:bold">${status.text}</span>
//</div>
} else { } else {
tooltip.innerHTML = ` tooltip.innerHTML = `
<div style = "font-weight:600;margin-bottom:4px;" >📍 ${t('systemSetting.longitude')}:${lonStr}</div > <div style = "font-weight:600;margin-bottom:4px;" >📍 ${t('systemSetting.longitude')}:${lonStr}</div >
@@ -3187,6 +3224,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const haloId = `${id}_halo`; const haloId = `${id}_halo`;
const haloColor = getDeviceHaloColor(device); const haloColor = getDeviceHaloColor(device);
if (isRealtimeMode) { if (isRealtimeMode) {
// 一机一光圈:实时模式下移除设备光圈,避免原位置残留 // 一机一光圈:实时模式下移除设备光圈,避免原位置残留
viewer.entities.removeById(haloId); viewer.entities.removeById(haloId);
@@ -3532,6 +3570,18 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
realtimePosition.lat && realtimePosition.lat &&
!isNaN(Number(realtimePosition.lon)) && !isNaN(Number(realtimePosition.lon)) &&
!isNaN(Number(realtimePosition.lat)); !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 // 情况1:没有实时数据 -> 清理所有 realtime
@@ -3669,7 +3719,6 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 1); 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; 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,
</div> </div>
)} )}
{/* 图例:返航点 / 分区 */} {/* 图例:返航点 / 分区 */}
{(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0 || stationOverlay.tempObstaclePoints.length > 0) && ( <div
<div style={{
position: "absolute",
right: 12,
top: 12,
zIndex: 20,
background: "rgba(255,255,255,0.92)",
borderRadius: 6,
padding: "8px 10px",
fontSize: 12,
color: "#333",
lineHeight: "18px",
boxShadow: "0 2px 8px rgba(0,0,0,0.12)",
}}
>
<div style={{ fontWeight: 600, marginBottom: 6 }}>{t('devices.mapEditor.legend')}</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "returnPoint" ? 600 : 400,
color: legendHighlight === "returnPoint" ? "#165DFF" : "#333",
background: legendHighlight === "returnPoint" ? "#e8f3ff" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 10,
height: 10,
background: "#165DFF",
borderRadius: "50% 50% 50% 0",
transform: "rotate(-45deg)",
}} />
<span>{t('devices.mapEditor.returnPoint')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "region" ? 600 : 400,
color: legendHighlight === "region" ? "#13C2C2" : "#333",
background: legendHighlight === "region" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 12,
height: 10,
border: "1px solid #13C2C2",
background: "rgba(19,194,194,0.18)",
}} />
<span>{t('devices.mapEditor.restArea')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "obstaclePoint" ? 600 : 400,
color: legendHighlight === "obstaclePoint" ? "#13C2C2" : "#333",
background: legendHighlight === "obstaclePoint" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span
style={{
display: 'inline-block',
width: 12,
height: 12,
border: '2px solid #F5222D',
borderRadius: '50%',
background: 'rgba(245,34,45,0.18)',
boxSizing: 'border-box',
}}
/>
<span>{t('devices.mapEditor.obstacle')}</span>
</div>
<button
onClick={handleFlyToDevice}
style={{ style={{
position: "absolute", display: 'inline-flex',
right: 12, alignItems: 'center',
top: 12, justifyContent: 'center',
zIndex: 20, gap: '8px',
background: "rgba(255,255,255,0.92)", padding: '4px 8px',
borderRadius: 6, color: '#fff',
padding: "8px 10px", fontSize: '14px',
fontSize: 12, fontWeight: 500,
color: "#333", background: 'linear-gradient(135deg, #409eff 0%, #1677ff 100%)',
lineHeight: "18px", border: 'none',
boxShadow: "0 2px 8px rgba(0,0,0,0.12)", borderRadius: '8px',
boxShadow: '0 3px 10px rgba(22, 119, 255, 0.25)',
cursor: 'pointer',
transition: 'all 0.2s ease',
}} }}
> >
<div style={{ fontWeight: 600, marginBottom: 6 }}>{t('devices.mapEditor.legend')}</div> <span style={{ fontSize: '18px', lineHeight: 1 }}>⌖</span>
<div style={{ <span>{t('devices.mapEditor.location')}</span>
display: "flex", </button>
alignItems: "center", </div>
gap: 6,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "returnPoint" ? 600 : 400,
color: legendHighlight === "returnPoint" ? "#165DFF" : "#333",
background: legendHighlight === "returnPoint" ? "#e8f3ff" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 10,
height: 10,
background: "#165DFF",
borderRadius: "50% 50% 50% 0",
transform: "rotate(-45deg)",
}} />
<span>{t('devices.mapEditor.returnPoint')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "region" ? 600 : 400,
color: legendHighlight === "region" ? "#13C2C2" : "#333",
background: legendHighlight === "region" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 12,
height: 10,
border: "1px solid #13C2C2",
background: "rgba(19,194,194,0.18)",
}} />
<span>{t('devices.mapEditor.restArea')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "obstaclePoint" ? 600 : 400,
color: legendHighlight === "obstaclePoint" ? "#13C2C2" : "#333",
background: legendHighlight === "obstaclePoint" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span
style={{
display: 'inline-block',
width: 12,
height: 12,
border: '2px solid #F5222D',
borderRadius: '50%',
background: 'rgba(245,34,45,0.18)',
boxSizing: 'border-box',
}}
/>
<span>{t('devices.mapEditor.obstacle')}</span>
</div>
<button
onClick={handleFlyToDevice}
style={{
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
padding: '4px 8px',
color: '#fff',
fontSize: '14px',
fontWeight: 500,
background: 'linear-gradient(135deg, #409eff 0%, #1677ff 100%)',
border: 'none',
borderRadius: '8px',
boxShadow: '0 3px 10px rgba(22, 119, 255, 0.25)',
cursor: 'pointer',
transition: 'all 0.2s ease',
}}
>
<span style={{ fontSize: '18px', lineHeight: 1 }}>⌖</span>
<span>{t('devices.mapEditor.location')}</span>
</button>
</div>
)}
</div> </div>
); );

View File

@@ -1,6 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { subscribeEmergencyStop } from './emergencyStopControl';
import { import {
ChevronUp, ChevronUp,
ChevronDown, ChevronDown,
@@ -60,6 +61,10 @@ const DPadControl: React.FC<DPadControlProps> = ({
const [pressed, setPressed] = useState<Record<string, boolean>>({}); const [pressed, setPressed] = useState<Record<string, boolean>>({});
const [speed, setSpeed] = useState(0.5); const [speed, setSpeed] = useState(0.5);
// 急停锁存状态:与其他入口(手柄 / 功能按钮)共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
// 每个物理输入单独记录,避免同方向不同按键互相干扰 // 每个物理输入单独记录,避免同方向不同按键互相干扰
// 例如 ArrowUp 和 W 可以同时按下 // 例如 ArrowUp 和 W 可以同时按下
@@ -69,7 +74,6 @@ const DPadControl: React.FC<DPadControlProps> = ({
const speedRef = useRef(0.5); const speedRef = useRef(0.5);
const pressTimer = useRef<number | null>(null); const pressTimer = useRef<number | null>(null);
const disabledRef = useRef(disabled); const disabledRef = useRef(disabled);
const emergencyTimer = useRef<number | null>(null);
const onGamepadUpdateRef = useRef(onGamepadUpdate); const onGamepadUpdateRef = useRef(onGamepadUpdate);
const onSpeedChangeRef = useRef(onSpeedChange); const onSpeedChangeRef = useRef(onSpeedChange);
@@ -204,29 +208,11 @@ const DPadControl: React.FC<DPadControlProps> = ({
stopTimer(); stopTimer();
emit(); emit();
}, [stopTimer, emit]); }, [stopTimer, emit]);
const startEmergency = useCallback(() => { // 急停:切换锁存状态(第一次按下→发送 eStop=1,第二次按下→发送 eStop=0)
// 视觉由订阅到的共享锁存状态驱动,与手柄 / 其他入口保持一致
const toggleEmergency = useCallback(() => {
if (disabledRef.current) return; if (disabledRef.current) return;
pressedRef.current = {
...pressedRef.current,
center: true,
};
setPressed({ ...pressedRef.current });
onEmergencyStopRef.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 组合 // 键盘控制:支持方向键 + WASD 组合
@@ -247,7 +233,7 @@ const DPadControl: React.FC<DPadControlProps> = ({
// 防止长按空格时重复触发急停 // 防止长按空格时重复触发急停
if (!e.repeat) { if (!e.repeat) {
startEmergency(); toggleEmergency();
} }
return; return;
@@ -287,7 +273,7 @@ const DPadControl: React.FC<DPadControlProps> = ({
window.removeEventListener('keyup', handleKeyUp); window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur); window.removeEventListener('blur', handleBlur);
}; };
}, [startPress, endPress, releaseAll, startEmergency]); }, [startPress, endPress, releaseAll, toggleEmergency]);
// 禁用时立即停止;卸载时清理定时器 // 禁用时立即停止;卸载时清理定时器
useEffect(() => { useEffect(() => {
@@ -317,17 +303,17 @@ const DPadControl: React.FC<DPadControlProps> = ({
}; };
}, [disabled, stopTimer]); }, [disabled, stopTimer]);
// 紧急停止按钮的短暂按压动画 // 急停锁存相关清理
useEffect(() => { //useEffect(() => {
return () => { // return () => {
if (emergencyTimer.current !== null) { // if (emergencyTimer.current !== null) {
window.clearTimeout(emergencyTimer.current); // window.clearTimeout(emergencyTimer.current);
} // }
stopTimer(); // stopTimer();
}; // };
}, [stopTimer]); //}, [stopTimer]);
const btnBase = 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'; '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<DPadControlProps> = ({
type="button" type="button"
aria-label={t('devices.emergencyStop')} aria-label={t('devices.emergencyStop')}
disabled={disabled} 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 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' : 'border-red-500/70 bg-red-500/10 text-red-400 hover:bg-red-500/20'
} ${disabled } ${disabled
? 'opacity-40 cursor-not-allowed' ? 'opacity-40 cursor-not-allowed'
: 'cursor-pointer' : 'cursor-pointer'
}`} }`}
onClick={startEmergency} onClick={toggleEmergency}
> >
<ShieldAlert className="w-5 h-5" /> <ShieldAlert className="w-5 h-5" />
<span className="absolute -top-1 -right-1 px-1 bg-slate-900/80 text-[8px] text-red-400/80 rounded border border-red-500/30 pointer-events-none"> <span className="absolute -top-1 -right-1 px-1 bg-slate-900/80 text-[8px] text-red-400/80 rounded border border-red-500/30 pointer-events-none">

View File

@@ -40,7 +40,7 @@ import envConfig from '../../../env';
import utils from '@/lib/utils.ts'; import utils from '@/lib/utils.ts';
import { useUnitFormatter } from '@/lib/units'; import { useUnitFormatter } from '@/lib/units';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { sendEmergencyStop } from './emergencyStopControl'; import { sendEmergencyStop, subscribeEmergencyStop, syncEmergencyStop } from './emergencyStopControl';
import AlarmLevelTag from '../AlarmLevelTag.tsx'; import AlarmLevelTag from '../AlarmLevelTag.tsx';
import { getDeviceTastPool } from '@/api/device.ts'; import { getDeviceTastPool } from '@/api/device.ts';
import { backToRestPointCommand } from '@/api/mapEdit'; import { backToRestPointCommand } from '@/api/mapEdit';
@@ -69,6 +69,10 @@ export default function DeviceOverviewPage() {
const [deviceStatistics, setDeviceStatistics] = useState(null); const [deviceStatistics, setDeviceStatistics] = useState(null);
const [currentSelectedRobot, setCurrentSelectedRobot] = useState(null); const [currentSelectedRobot, setCurrentSelectedRobot] = useState(null);
const [realtimeMap, setRealtimeMap] = useState<any>({}); const [realtimeMap, setRealtimeMap] = useState<any>({});
// 急停锁存状态:与 DPadControl / XboxController 共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
const controllerRef = useRef<DeviceController | null>(null); const controllerRef = useRef<DeviceController | null>(null);
const [messageApi, contextHolder] = message.useMessage(); const [messageApi, contextHolder] = message.useMessage();
const [taskList, setTaskList] = useState<any[]>([]); const [taskList, setTaskList] = useState<any[]>([]);
@@ -429,11 +433,16 @@ export default function DeviceOverviewPage() {
...persistentDroneData, ...persistentDroneData,
...wsData, ...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]); }, [selectedDevice, uavState, persistentHostData, persistentDroneData, realtimeMap]);
// 实时数据里的急停状态同步到共享锁存状态:true=已急停,false=未急停
useEffect(() => {
syncEmergencyStop(realtimeDevice?.emergency_stop);
}, [realtimeDevice?.emergency_stop]);
// MQTT消息处理 // MQTT消息处理
const handleMqttMessage = useCallback((topic, message) => { const handleMqttMessage = useCallback((topic, message) => {
@@ -701,6 +710,9 @@ export default function DeviceOverviewPage() {
const sn = d.serialNumber || d.device_sn; const sn = d.serialNumber || d.device_sn;
const rt = realtimeMap[sn] || {}; const rt = realtimeMap[sn] || {};
const online = rt.status !== undefined ? (rt.status !== 'OFFLINE' ? 1 : 0) : d.onlineStatus; 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 { return {
...d, ...d,
@@ -710,7 +722,12 @@ export default function DeviceOverviewPage() {
status: online === 1 ? t('devices.online') : t('devices.offline'), status: online === 1 ? t('devices.online') : t('devices.offline'),
onlineStatus: online, onlineStatus: online,
mode: rt.status === 'EXECUTING' ? '作业中' : rt.status === 'IDLE' ? t('devices.idle') : (d.feStatus == 1 ? '作业中' : d.feStatus == 2 ? t('devices.idle') : '离线'), 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 || '站内', position: rt.position || d.position || '站内',
task: rt.currentTaskName || d.task || (d.status === 4 ? '待命' : '作业中'), task: rt.currentTaskName || d.task || (d.status === 4 ? '待命' : '作业中'),
comm: rt.rssi ? `${rt.rssi}dBm` : (d.rssi ? `${d.rssi}dBm` : '良好'), 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 handleReturn = () => message.info(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2'));
const handleRecharge = () => message.info(t('devices.commandIssuedFixed2')); const handleRecharge = () => message.info(t('devices.commandIssuedFixed2'));
// 急停:点击时直接下发 button7(绕过控制权限校验),并提示已触发 // 急停:点击时直接下发 button7(绕过控制权限校验),并提示已触发
const handleEmergencyStop = () => { const handleEmergencyStop = async () => {
sendEmergencyStop(selectedDevice?.serialNumber || ""); const next = await sendEmergencyStop(selectedDevice?.serialNumber || "");
message.error(t('devices.s73')); if (next) message.error(t('devices.estopTriggered'));
else message.success(t('devices.estopNormal'));
}; };
const fix2 = (val) => { const fix2 = (val) => {
@@ -871,17 +889,18 @@ export default function DeviceOverviewPage() {
dataIndex: 'lastRunningStatus', dataIndex: 'lastRunningStatus',
width: 70, width: 70,
render: (lastRunningStatus) => { render: (lastRunningStatus) => {
const v = lastRunningStatus?.battery || 100; const v = lastRunningStatus?.battery ?? "--";
return <Progress return <Progress
percent={v} percent={v}
size="small" size="small"
status={v < 40 ? 'exception' : 'active'} status={v < 40 ? 'exception' : 'active'}
/>; />;
} }
}, { 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: '累计作业面积', dataIndex: 'work_area', width: 110, render: v => `${Number(v || 0).toFixed(2)} ㎡` },
//{ title: t('devices.fixed2CurrentFixed2TaskSuspended2Fixed2'), dataIndex: 'task', width: 100 }, //{ title: t('devices.fixed2CurrentFixed2TaskSuspended2Fixed2'), dataIndex: 'task', width: 100 },
{ title: t('devices.statusFixed2'), dataIndex: 'comm', width: 100, render: v => <Badge status={v && v.includes('-') ? 'warning' : 'success'} text={v} /> }, //{ title: t('devices.statusFixed2'), dataIndex: 'comm', width: 100, render: v => <Badge status={v && v.includes('-') ? 'warning' : 'success'} text={v} /> },
{ {
title: t('roles.actions'), title: t('roles.actions'),
key: 'action', 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'), title: t('roles.status'),
dataIndex: 'taskStaus', dataIndex: 'taskStaus',
@@ -1018,7 +1044,7 @@ export default function DeviceOverviewPage() {
dataSource={alarmList} dataSource={alarmList}
scroll={{ x: 'max-content' }} scroll={{ x: 'max-content' }}
columns={[ columns={[
{ title: t('common.time'), dataIndex: 'alertTime', width: 90, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> }, { title: t('common.time'), dataIndex: 'alarmTime', width: 90, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> },
{ title: t('devices.device'), dataIndex: 'deviceName', width: 100, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> }, { title: t('devices.device'), dataIndex: 'deviceName', width: 100, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> },
{ {
title: t('alerts.alarmTitle'), title: t('alerts.alarmTitle'),
@@ -1076,8 +1102,8 @@ export default function DeviceOverviewPage() {
<span style={{ fontSize: 20, color: '#1890ff' }}><CarOutlined /></span> <span style={{ fontSize: 20, color: '#1890ff' }}><CarOutlined /></span>
)} )}
<span style={{ fontSize: 14, fontWeight: 600 }}>{selectedDevice.deviceAlias || selectedDevice.drone_callsign || selectedDevice.callsign || selectedDevice.deviceName}</span> <span style={{ fontSize: 14, fontWeight: 600 }}>{selectedDevice.deviceAlias || selectedDevice.drone_callsign || selectedDevice.callsign || selectedDevice.deviceName}</span>
<Tag color={selectedDevice.onlineStatus === 1 ? "success" : "default"} size="small" style={{ margin: 0 }}> <Tag color={realtimeDevice.status == 1 || realtimeDevice.status == 2 ? "success" : "default"} size="small" style={{ margin: 0 }}>
{selectedDevice.onlineStatus == 1 ? t('devices.online') : t('devices.offline')} {realtimeDevice.status == 1 || realtimeDevice.status == 2 ? t('devices.online') : t('devices.offline')}
</Tag> </Tag>
<Button <Button
type="primary" size="small" ghost icon={<InfoCircleOutlined />} type="primary" size="small" ghost icon={<InfoCircleOutlined />}
@@ -1089,7 +1115,7 @@ export default function DeviceOverviewPage() {
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}> <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<span style={{ color: '#52c41a' }}><ThunderboltOutlined /></span> <span style={{ color: '#52c41a' }}><ThunderboltOutlined /></span>
<span style={{ fontSize: 12 }}>{t('devices.batteryLevel')}: {fix2(realtimeDevice?.capacity_percent || realtimeDevice?.lastRunningStatus?.battery || 100)}%</span> <span style={{ fontSize: 12 }}>{t('devices.batteryLevel')}: {fix2(realtimeDevice?.battery)}%</span>
</div> </div>
{realtimeDevice?.environment_temperature && ( {realtimeDevice?.environment_temperature && (
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
@@ -1159,7 +1185,7 @@ export default function DeviceOverviewPage() {
{/*<Button style={{ borderRadius: 8, flex: 1 }} onClick={handlePause}>{t('video.pause')}</Button>*/} {/*<Button style={{ borderRadius: 8, flex: 1 }} onClick={handlePause}>{t('video.pause')}</Button>*/}
<Button type="primary" style={{ borderRadius: 8, flex: 1 }} onClick={handleAutoBack}>{t('devices.returnHome')}</Button> <Button type="primary" style={{ borderRadius: 8, flex: 1 }} onClick={handleAutoBack}>{t('devices.returnHome')}</Button>
{/*<Button style={{ flex: 1, background: '#52c41a', borderColor: '#52c41a', color: "#fff", borderRadius: 8, }} onClick={handleRecharge}>{t('devices.s24')}</Button>*/} {/*<Button style={{ flex: 1, background: '#52c41a', borderColor: '#52c41a', color: "#fff", borderRadius: 8, }} onClick={handleRecharge}>{t('devices.s24')}</Button>*/}
<Button danger style={{ flex: 1, borderRadius: 8 }} onClick={handleEmergencyStop}>{t('devices.s29')}</Button> <Button danger={!eStopActive} type={eStopActive ? 'primary' : 'default'} style={{ flex: 1, borderRadius: 8, background: eStopActive ? '#cf1322' : undefined, borderColor: eStopActive ? '#cf1322' : undefined, color: eStopActive ? '#fff' : undefined }} onClick={handleEmergencyStop}>{eStopActive ? t('devices.estopTriggered') : t('devices.s29')}</Button>
</div> </div>
</div> </div>

View File

@@ -77,8 +77,9 @@ import { useTranslation } from 'react-i18next';
import { backToRestPointCommand } from '@/api/mapEdit'; import { backToRestPointCommand } from '@/api/mapEdit';
import CarReverseGuideLine from './CarReverseGuideLine'; import CarReverseGuideLine from './CarReverseGuideLine';
import mowerImg from '../../assets/images/mower.png'; import mowerImg from '../../assets/images/mower.png';
import { sendEmergencyStop } from './emergencyStopControl'; import { sendEmergencyStop, syncEmergencyStop } from './emergencyStopControl';
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
const { Text } = Typography; const { Text } = Typography;
const ConsoleBadge = ({ online, text, color }: any) => ( const ConsoleBadge = ({ online, text, color }: any) => (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, color: color || (online ? '#52c41a' : '#8c8c8c'), whiteSpace: 'nowrap' }}> <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, color: color || (online ? '#52c41a' : '#8c8c8c'), whiteSpace: 'nowrap' }}>
@@ -461,6 +462,11 @@ export default function DeviceStatusPage() {
...locationInfo ...locationInfo
}; };
}, [device, wsDeviceInfo, isUAV, locationInfo]); }, [device, wsDeviceInfo, isUAV, locationInfo]);
// 实时下发的急停状态同步到共享锁存状态:true=已急停,false=未急停
useEffect(() => {
syncEmergencyStop(runningStatus?.emergency_stop);
}, [runningStatus?.emergency_stop]);
// 统一在线状态判断:优先实时数据,兜底接口数据 // 统一在线状态判断:优先实时数据,兜底接口数据
const isDeviceOnline = useMemo(() => { const isDeviceOnline = useMemo(() => {
// 1. 优先检查实时数据源(WebSocket 推送的 wsDeviceInfo / locationInfo) // 1. 优先检查实时数据源(WebSocket 推送的 wsDeviceInfo / locationInfo)
@@ -546,6 +552,7 @@ export default function DeviceStatusPage() {
lon: robotLon, lon: robotLon,
lat: robotLat, lat: robotLat,
heading: runningStatus?.yaw || wsDeviceInfo?.yaw || locationInfo?.yaw || device?.lastRunningStatus?.heading || 0, heading: runningStatus?.yaw || wsDeviceInfo?.yaw || locationInfo?.yaw || device?.lastRunningStatus?.heading || 0,
status: Object.keys(wsDeviceInfo || {}).length > 0 ? 'online' : 'offline',
}; };
} }
return null; return null;
@@ -665,6 +672,12 @@ export default function DeviceStatusPage() {
}, [isUAV, device]); }, [isUAV, device]);
const mapDevices = useMemo(() => { const mapDevices = useMemo(() => {
if (!device) return null; 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 // 优先使用持久化MQTT数据,其次使用uavState
const lng = currentDroneData?.longitude ?? uavState?.longitude ?? runningStatus?.longitude ?? device.longitude; const lng = currentDroneData?.longitude ?? uavState?.longitude ?? runningStatus?.longitude ?? device.longitude;
const lat = currentDroneData?.latitude ?? uavState?.latitude ?? runningStatus?.latitude ?? device.latitude; const lat = currentDroneData?.latitude ?? uavState?.latitude ?? runningStatus?.latitude ?? device.latitude;
@@ -678,14 +691,14 @@ export default function DeviceStatusPage() {
longitude: lng, longitude: lng,
latitude: lat, latitude: lat,
name: device?.deviceAlias || device?.callsign || device?.deviceName || t('devices.device'), name: device?.deviceAlias || device?.callsign || device?.deviceName || t('devices.device'),
color: "red", color: deviceColor,
type: isUAV type: isUAV
? 'drone' ? 'drone'
: device?.productName?.includes(t('constants.mower')) : device?.productName?.includes(t('constants.mower'))
? 'mower' ? 'mower'
: 'robot', : 'robot',
}; };
}, [device, isUAV, runningStatus, uavState, currentDroneData]); }, [device, isUAV, runningStatus, uavState, currentDroneData, wsDeviceInfo, locationInfo]);
const handleControlMode = (controlMode: number) => { const handleControlMode = (controlMode: number) => {
if (!selectedSn) { if (!selectedSn) {
messageApi.error(t('devices.selectDevice')); messageApi.error(t('devices.selectDevice'));
@@ -700,7 +713,7 @@ export default function DeviceStatusPage() {
deviceId: selectedSn deviceId: selectedSn
} }
modeChage(data).then(res => { modeChage(data).then(res => {
if (res.code == 200) { if (res.code == 200 && res?.data) {
messageApi.success(t('devices.controlModeSuccess')); messageApi.success(t('devices.controlModeSuccess'));
} else { } else {
messageApi.error(res.msg || t('devices.controlModeFail')); messageApi.error(res.msg || t('devices.controlModeFail'));
@@ -771,6 +784,63 @@ export default function DeviceStatusPage() {
sendSteerFrame(index, true); sendSteerFrame(index, true);
window.setTimeout(() => sendSteerFrame(index, false), 300); window.setTimeout(() => sendSteerFrame(index, false), 300);
}, [sendSteerFrame]); }, [sendSteerFrame]);
// 方向盘功能按钮:三组互斥锁存(割刀启动/停止、底盘升/降、点火/熄火)
type SteerGroup = 'blade' | 'chassis' | 'power';
const EMPTY_STEER_STATE: Record<SteerGroup, string | null> = { blade: null, chassis: null, power: null };
const [steerState, setSteerState] = useState<Record<SteerGroup, string | null>>(EMPTY_STEER_STATE);
const steerStateRef = useRef(steerState);
steerStateRef.current = steerState;
// 按锁存状态组装遥控帧:割刀统一走 button2(启动=true,停止/未点击=false)
const buildSteerButtons = useCallback((s: Record<SteerGroup, string | null>) => {
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<SteerGroup, string | null>) => {
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<SteerGroup, string | null>);
}, [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(() => { const handleControlModal = useCallback(() => {
console.log('请求控制权限'); console.log('请求控制权限');
controllerRef.current?.requestControl(); controllerRef.current?.requestControl();
@@ -1270,9 +1340,9 @@ export default function DeviceStatusPage() {
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftTemp')} value={(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp), 1).label : '-'} /> <ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftTemp')} value={(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp), 1).label : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightTemp')} value={(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp), 1).label : '-'} /> <ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightTemp')} value={(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp), 1).label : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtMainTemp')} value={(runningStatus?.main_temperature ?? runningStatus?.chipTemp) !== undefined ? formatTemperature(Number(runningStatus?.main_temperature ?? runningStatus?.chipTemp), 1).label : '-'} /> <ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtMainTemp')} value={(runningStatus?.main_temperature ?? runningStatus?.chipTemp) !== undefined ? formatTemperature(Number(runningStatus?.main_temperature ?? runningStatus?.chipTemp), 1).label : '-'} />
<ConsoleRow icon={<EnvironmentOutlined />} label={t('devices.motionStatus')} value={runningStatus?.motion === 'moving' ? t('devices.motionMoving') : runningStatus?.motion === 'stopped' ? t('devices.motionStopped') : runningStatus?.motion === 'blocked' ? t('devices.motionBlocked') : '-'} /> {/*<ConsoleRow icon={<EnvironmentOutlined />} label={t('devices.motionStatus')} value={runningStatus?.motion === 'moving' ? t('devices.motionMoving') : runningStatus?.motion === 'stopped' ? t('devices.motionStopped') : runningStatus?.motion === 'blocked' ? t('devices.motionBlocked') : '-'} />*/}
<ConsoleRow icon={<EnvironmentOutlined />} label={t('devices.cutterSpedd')} value={runningStatus?.cutter_speed ?? "-"} /> <ConsoleRow icon={<EnvironmentOutlined />} label={t('devices.cutterSpedd')} value={runningStatus?.cutter_speed ?? "-"} />
<ConsoleRow icon={<SafetyOutlined />} label={t('devices.rtEmergency')} value={runningStatus?.emergency_stop === true ? t('devices.estopTriggered') : runningStatus?.emergency_stop === false ? t('devices.estopNormal') : '-'} /> <ConsoleRow icon={<SafetyOutlined />} label={t('devices.rtEmergency')} value={runningStatus?.emergency_stop == "true" ? t('devices.estopTriggered') : runningStatus?.emergency_stop == "false" ? t('devices.estopNormal') : '-'} />
{/*<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftMeasureRpm')} value={(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed) !== undefined ? Number(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/} {/*<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftMeasureRpm')} value={(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed) !== undefined ? Number(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/}
{/*<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightMeasureRpm')} value={(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed) !== undefined ? Number(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/} {/*<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightMeasureRpm')} value={(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed) !== undefined ? Number(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/}
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftMotorRpm')} value={runningStatus?.left_motor_rpm !== undefined ? Number(runningStatus?.left_motor_rpm).toFixed(1) + 'rpm' : '-'} /> <ConsoleRow icon={<DashboardOutlined />} 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() {
</div> </div>
<div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 8 }}>
<div style={{ display: 'flex', gap: 8 }}> <div style={{ display: 'flex', gap: 8 }}>
<SteerButton icon={<PlayCircleOutlined />} label={t('devices.steer.ignition')} color="#22c55e" onPressStart={() => sendSteerFrame(4, true)} onPressEnd={() => sendSteerFrame(4, false)} /> <SteerButton icon={<PlayCircleOutlined />} label={t('devices.steer.ignition')} color="#22c55e" active={steerState.power === 'ignition'} onToggle={() => toggleSteerGroup('power', 'ignition')} />
<SteerButton icon={<PoweroffOutlined />} label={t('devices.steer.shutdown')} color="#ef4444" onPressStart={() => sendSteerFrame(5, true)} onPressEnd={() => sendSteerFrame(5, false)} /> <SteerButton icon={<PoweroffOutlined />} label={t('devices.steer.shutdown')} color="#ef4444" active={steerState.power === 'shutdown'} onToggle={() => toggleSteerGroup('power', 'shutdown')} />
</div> </div>
<div style={{ display: 'flex', gap: 8 }}> <div style={{ display: 'flex', gap: 8 }}>
<SteerButton icon={<ArrowUpOutlined />} label={t('devices.steer.chassisUp')} color="#3b82f6" onPressStart={() => sendSteerFrame(0, true)} onPressEnd={() => sendSteerFrame(0, false)} /> <SteerButton icon={<ArrowUpOutlined />} label={t('devices.steer.chassisUp')} color="#3b82f6" active={steerState.chassis === 'up'} onToggle={() => toggleSteerGroup('chassis', 'up')} />
<SteerButton icon={<ArrowDownOutlined />} label={t('devices.steer.chassisDown')} color="#3b82f6" onPressStart={() => sendSteerFrame(1, true)} onPressEnd={() => sendSteerFrame(1, false)} /> <SteerButton icon={<ArrowDownOutlined />} label={t('devices.steer.chassisDown')} color="#3b82f6" active={steerState.chassis === 'down'} onToggle={() => toggleSteerGroup('chassis', 'down')} />
</div> </div>
<div style={{ display: 'flex', gap: 8 }}> <div style={{ display: 'flex', gap: 8 }}>
<SteerButton icon={<PlusOutlined />} label={t('devices.steer.cutterAccel')} color="#f59e0b" onPressStart={() => sendSteerFrame(2, true)} onPressEnd={() => sendSteerFrame(2, false)} /> <SteerButton icon={<PlusOutlined />} label={t('devices.steer.cutterAccel')} color="#f59e0b" active={steerState.blade === 'start'} onToggle={() => toggleSteerGroup('blade', 'start')} />
<SteerButton icon={<MinusOutlined />} label={t('devices.steer.cutterDecel')} color="#f59e0b" onPressStart={() => sendSteerFrame(3, true)} onPressEnd={() => sendSteerFrame(3, false)} /> <SteerButton icon={<MinusOutlined />} label={t('devices.steer.cutterDecel')} color="#f59e0b" active={steerState.blade === 'stop'} onToggle={() => toggleSteerGroup('blade', 'stop')} />
</div> </div>
</div> </div>
</ConsolePanel> </ConsolePanel>

View File

@@ -181,11 +181,13 @@ export const MapEditorView = React.forwardRef(function MapEditorView(
}, [presetRoutes, presetModeFilter]); }, [presetRoutes, presetModeFilter]);
const selectRobot = useMemo(() => { const selectRobot = useMemo(() => {
if (!Array.isArray(robots)) return []; if (!Array.isArray(robots)) return [];
// 任务规划页面:机器没有实时消息(无实时位置)时,不在地图上显示
if (extraMapProps && !extraMapProps.realtimePosition) return [];
return robots return robots
.filter(robot => robot.serialNumber == selectedRobotId) .filter(robot => robot.serialNumber == selectedRobotId)
.map(robot => (extraMapProps?.deviceColor ? { ...robot, color: extraMapProps.deviceColor } : robot)); .map(robot => (extraMapProps?.deviceColor ? { ...robot, color: extraMapProps.deviceColor } : robot));
}, [selectedRobotId, robots, extraMapProps?.deviceColor]); }, [selectedRobotId, robots, extraMapProps?.deviceColor, extraMapProps?.realtimePosition]);
useEffect(() => { useEffect(() => {
if (extraMapProps.polyPoints?.length > 0) { if (extraMapProps.polyPoints?.length > 0) {
setPolyPoints(extraMapProps.polyPoints); setPolyPoints(extraMapProps.polyPoints);

View File

@@ -1,122 +1,33 @@
import { useCallback, useEffect, useRef, useState } from 'react';
interface SteerButtonProps { interface SteerButtonProps {
icon: React.ReactNode; icon: React.ReactNode;
label: string; label: string;
color: string; color: string;
onPressStart?: () => void; // 受控高亮:由父组件统一管理,保证同组按钮互斥(不会同时显示为按下)
onPressEnd?: () => void; active?: boolean;
interval?: number; disabled?: boolean;
onToggle?: () => void;
} }
/**
* 锁存按钮(受控):
* 高亮状态完全由 active 决定,点击只触发 onToggle。
* 持续发送 / 互斥逻辑由父组件统一管理。
*/
const SteerButton = ({ const SteerButton = ({
icon, icon,
label, label,
color, color,
onPressStart, active = false,
onPressEnd, disabled = false,
interval = 100, onToggle,
}: SteerButtonProps) => { }: SteerButtonProps) => {
const [pressed, setPressed] = useState(false);
// 是否处于按下状态
const holdingRef = useRef(false);
// 定时发送句柄
const timerRef = useRef<ReturnType<typeof setTimeout> | 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 ( return (
<button <button
type="button" type="button"
aria-label={label} aria-label={label}
aria-pressed={pressed} aria-pressed={active}
onPointerDown={(e) => { disabled={disabled}
e.preventDefault(); onClick={onToggle}
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}
onContextMenu={(e) => e.preventDefault()} onContextMenu={(e) => e.preventDefault()}
style={{ style={{
flex: '1 1 0', flex: '1 1 0',
@@ -128,15 +39,18 @@ const SteerButton = ({
minHeight: 46, minHeight: 46,
padding: '6px 4px', padding: '6px 4px',
borderRadius: 8, borderRadius: 8,
border: `1px solid ${pressed ? color : `${color}55`}`, border: `1px solid ${active ? color : `${color}55`}`,
background: active ? `${color}22` : 'transparent',
color, color,
cursor: 'pointer', cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.4 : 1,
userSelect: 'none', userSelect: 'none',
touchAction: 'none', touchAction: 'none',
transform: pressed ? 'scale(0.94)' : 'scale(1)', transform: active ? 'scale(0.97)' : 'scale(1)',
boxShadow: pressed ? `0 0 14px ${color}66` : 'none', boxShadow: active ? `0 0 14px ${color}66, inset 0 0 8px ${color}22` : 'none',
fontWeight: active ? 700 : 500,
transition: 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',
}} }}
> >
<span style={{ display: 'inline-flex', fontSize: 16, lineHeight: 1 }}> <span style={{ display: 'inline-flex', fontSize: 16, lineHeight: 1 }}>

View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef, useMemo } from 'react'; 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 { 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 { Car, Navigation, MapPinned, Route, Satellite, LayoutGrid, CheckCircle2, AlertCircle, TrendingUp, Maximize2 } from 'lucide-react';
import TaskTypeRadio from '../taskRadio/taskRadio'; import TaskTypeRadio from '../taskRadio/taskRadio';
@@ -80,6 +80,8 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const [routeSearch, setRouteSearch] = useState(''); const [routeSearch, setRouteSearch] = useState('');
const [routeList, setRouteList] = useState([]); const [routeList, setRouteList] = useState([]);
// 任务下发:按模式分组的路线(折叠面板使用)
const dispatchRouteGroups = useMemo(() => groupRoutesByMode(routeList, t), [routeList, t]);
const [consecutiveLoading, setConsecutiveLoading] = useState(false); const [consecutiveLoading, setConsecutiveLoading] = useState(false);
// 执行任务弹窗 // 执行任务弹窗
@@ -212,18 +214,6 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const controllerRef = useRef<DeviceController | null>(null); const controllerRef = useRef<DeviceController | null>(null);
const isFirstConnect = useRef(true); const isFirstConnect = useRef(true);
const mapRef = useRef(null); const mapRef = useRef(null);
const fixStatusMap: Record<string, string> = {
'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) => { const handleFinish = (data) => {
@@ -1739,8 +1729,8 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
points, points,
polyPoints, polyPoints,
routeMode, routeMode,
realtimePosition, realtimePosition: robotRealtimePosition ? realtimePosition : null,
realtimeDevice: targetRobot ? { ...targetRobot, color: robotMapColor } : targetRobot, realtimeDevice: targetRobot ? { ...targetRobot, ...(robotRealtimePosition || {}), color: robotMapColor } : targetRobot,
deviceColor: robotMapColor, deviceColor: robotMapColor,
realtimeType: 'robot', realtimeType: 'robot',
ifClearNavLine: clearNavLine, ifClearNavLine: clearNavLine,
@@ -1754,7 +1744,7 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
onSave={() => fetchRouteList()} onSave={() => fetchRouteList()}
/> />
{/* 机器人状态悬浮面板 - 绝对定位左上角 */} {/* 机器人操作面板(状态信息改为鼠标悬浮机器时在地图上显示) */}
{execute && executingRobot && ( {execute && executingRobot && (
<div <div
style={{ style={{
@@ -1820,7 +1810,7 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
})()} })()}
</span> </span>
<span> {/*<span>
{t('devices.systemMode')} {t('devices.systemMode')}
{(() => { {(() => {
const mode = robotRealtimePosition?.sm || robotRealtimePosition?.sm; const mode = robotRealtimePosition?.sm || robotRealtimePosition?.sm;
@@ -1850,16 +1840,13 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
</span> </span>
); );
})()} })()}
</span> </span>*/}
<span>
{t('devices.location')}
{robotRealtimePosition?.fix_status ? fixStatusMap[robotRealtimePosition?.fix_status] : t('constants.locationUnknown')}
</span>
{/* 视频开关 */} {/* 视频开关 */}
<span style={{ display: 'flex', alignItems: 'center', gap: 6 }}> <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
@@ -2301,61 +2288,61 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
{(!routeList || routeList.length === 0) ? ( {(!routeList || routeList.length === 0) ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : ( ) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 280, overflowY: 'auto' }}> <Collapse
{groupRoutesByMode(routeList, t).map(group => ( size="small"
<div key={group.key}> ghost
<div style={{ fontSize: 12, fontWeight: 600, color: group.color, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}> defaultActiveKey={dispatchRouteGroups.map(g => g.key)}
style={{ maxHeight: 280, overflowY: 'auto' }}
items={dispatchRouteGroups.map(group => ({
key: group.key,
label: (
<div style={{ fontSize: 12, fontWeight: 600, color: group.color, display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: group.color }} /> <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: group.color }} />
{group.label} {group.label}
<span style={{ color: '#999', fontWeight: 400, fontSize: 11 }}>({group.items.length})</span> <span style={{ color: '#999', fontWeight: 400, fontSize: 11 }}>({group.items.length})</span>
</div> </div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}> ),
children: (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{group.items.map(route => { {group.items.map(route => {
const checked = dispatchRouteIds.includes(route.id); const checked = dispatchRouteIds.includes(route.id);
return ( return (
<Tag.CheckableTag <div
key={route.id} key={route.id}
checked={checked} onClick={() => {
style={{ // 按路线下发:单选,一行一个;再次点击可取消
display: 'inline-flex', setDispatchRouteIds(checked ? [] : [route.id]);
alignItems: 'center', if (!checked) {
border: `1px solid ${checked ? '#1677ff' : '#dce5f2'}`,
background: checked ? '#f0f7ff' : '#fff',
color: '#344054',
borderRadius: 4,
padding: '3px 12px',
margin: 0,
fontSize: 12,
lineHeight: '20px',
whiteSpace: 'nowrap',
}}
onChange={nextChecked => {
// 按路线下发:单选
setDispatchRouteIds(nextChecked ? [route.id] : []);
if (nextChecked) {
// 选择下发路径时,取消上方任务规划的选中
setEditorType(null); setEditorType(null);
flyToRoute(route.id); 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',
}}
> >
<span <span style={{ width: 6, height: 6, borderRadius: '50%', background: group.color, flex: '0 0 auto' }} />
style={{ <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{route.workName || route.name}</span>
color: '#344054', {checked && <span style={{ color: '#1677ff', fontWeight: 700 }}>✓</span>}
display: 'inline-block', </div>
}}
>
{route.workName || route.name}
</span>
</Tag.CheckableTag>
); );
})} })}
</div> </div>
</div> )
))} }))}
</div> />
)} )}
</div> </div>
)} )}

View File

@@ -1,6 +1,7 @@
import React, { useEffect, useState, useRef } from 'react'; import React, { useEffect, useState, useRef } from 'react';
import { sendEmergencyStop, subscribeEmergencyStop } from './emergencyStopControl';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const XboxController = ({ onGamepadUpdate, onConnectionChange }) => { const XboxController = ({ onGamepadUpdate, onConnectionChange, deviceId }: { onGamepadUpdate?: any; onConnectionChange?: any; deviceId?: string }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [gamepadState, setGamepadState] = useState<{ const [gamepadState, setGamepadState] = useState<{
buttons: boolean[]; buttons: boolean[];
@@ -23,19 +24,94 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
const lastSendRef = useRef(0); const lastSendRef = useRef(0);
const SEND_INTERVAL = 1000 / 10; // 20Hz const SEND_INTERVAL = 1000 / 10; // 20Hz
const lastPayloadRef = useRef(''); const lastPayloadRef = useRef('');
// 物理按键上一帧状态(上升沿检测)
const lastButtonsRef = useRef<boolean[]>(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 updateGamepad = () => {
const gp = navigator.getGamepads()[0]; const gp = navigator.getGamepads()[0];
if (gp) { 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 = { const state = {
buttons: gp.buttons.map(b => b.pressed), buttons: displayButtons,
axes: gp.axes.map(normalizeAxis), axes,
connected: true, connected: true,
ts: Date.now(), ts: Date.now(),
}; };
setGamepadState(state); setGamepadState(state);
const payload = JSON.stringify({ const payload = JSON.stringify({
buttons: state.buttons, buttons: wsButtons,
axes: state.axes, axes,
}); });
const now = performance.now(); const now = performance.now();
if ( if (
@@ -81,6 +157,10 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
console.log('❌ Gamepad disconnected'); console.log('❌ Gamepad disconnected');
//handleControlModal({ control: false }); //handleControlModal({ control: false });
setGamepadState(prev => ({ ...prev, connected: 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('gamepadconnected', handleConnect);
window.addEventListener('gamepaddisconnected', handleDisconnect); window.addEventListener('gamepaddisconnected', handleDisconnect);
@@ -177,15 +257,17 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
<circle cx="-20" cy="0" r="12" fill={buttons[2] ? "#3b82f6" : "#0f172a"} stroke="#3b82f6" strokeWidth="1" opacity={buttons[2] ? 1 : 0.6} /> {/* X */} <circle cx="-20" cy="0" r="12" fill={buttons[2] ? "#3b82f6" : "#0f172a"} stroke="#3b82f6" strokeWidth="1" opacity={buttons[2] ? 1 : 0.6} /> {/* X */}
<text x="-20" y="4" textAnchor="middle" fill={buttons[2] ? "#fff" : "#3b82f6"} fontSize="14" fontWeight="bold">X</text> <text x="-20" y="4" textAnchor="middle" fill={buttons[2] ? "#fff" : "#3b82f6"} fontSize="14" fontWeight="bold">X</text>
<circle cx="0" cy="-20" r="12" fill={buttons[3] ? "#eab308" : "#0f172a"} stroke="#eab308" strokeWidth="1" opacity={buttons[3] ? 1 : 0.6} /> {/* Y */} <circle cx="0" cy="-20" r="12" fill={buttons[3] ? "#eab308" : "#0f172a"} stroke="#eab308" strokeWidth="1" opacity={buttons[3] ? 1 : 0.6} /> Y
<text x="0" y="-16" textAnchor="middle" fill={buttons[3] ? "#fff" : "#eab308"} fontSize="14" fontWeight="bold">Y</text> <text x="0" y="-16" textAnchor="middle" fill={buttons[3] ? "#fff" : "#eab308"} fontSize="14" fontWeight="bold">Y</text>
</g> </g>
{/* Menu Buttons + Text Label button8=急停, button9=Menu */} {/* Menu Buttons + Text Label button8=急停, button9=Menu */}
<circle cx="180" cy="140" r="6" fill={buttons[8] ? "#22d3ee" : "#334155"} /> {/* Emergency Stop button 急停 */}
<text x="180" y="152" textAnchor="middle" fill={buttons[8] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold">急停</text> <circle cx="180" cy="140" r="14" fill={eStopActive || buttons[8] ? "#dc2626" : "#7f1d1d"} stroke={eStopActive || buttons[8] ? "#fca5a5" : "#991b1b"} strokeWidth="2" style={eStopActive || buttons[8] ? { filter: 'drop-shadow(0 0 8px #ef4444)' } : { filter: 'drop-shadow(0 0 2px #450a0a)' }} />
<text x="180" y="144" textAnchor="middle" fill={eStopActive || buttons[8] ? "#ffffff" : "#fca5a5"} fontSize="10" fontWeight="900">STOP</text>
{/*<text x="180" y="160" textAnchor="middle" fill={buttons[8] ? "#fecaca" : "#991b1b"} fontSize="7" fontWeight="bold">急停</text>*/}
<circle cx="220" cy="140" r="6" fill={buttons[9] ? "#22d3ee" : "#334155"} /> <circle cx="220" cy="140" r="6" fill={buttons[9] ? "#22d3ee" : "#334155"} />
<text x="220" y="152" textAnchor="middle" fill={buttons[9] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold">Menu</text> <text x="220" y="152" textAnchor="middle" fill={buttons[9] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold"></text>
</svg> </svg>
</div> </div>
); );

View File

@@ -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 emit = () => {
const buildFrame = (pressed: boolean) => { for (const fn of listeners) {
const buttons = new Array(17).fill(false); try { fn(active); } catch { }
buttons[EMERGENCY_STOP_BUTTON_INDEX] = pressed; }
return { buttons, axes: [0, 0, 0, 0], connected: true, ts: Date.now() };
}; };
/** /** 订阅急停锁存状态变化,返回 unsubscribe */
* 单击急停:绕过控制权限校验,直接经 WebSocket 下发 button7; export const subscribeEmergencyStop = (fn: (val: boolean) => void) => {
* 约 300ms 后自动补发一帧复位数据,模拟按下再松开。 listeners.add(fn);
*/ fn(active); // 立即回调一次当前值
export const sendEmergencyStop = (userInfo?: any) => { return () => listeners.delete(fn);
const send = (pressed: boolean) => };
wsManager.send({
type: 'remoteControl', /** 由实时数据(runningStatus.emergency_stop)同步急停状态,只更新本地显示,不发请求 */
remoteData: buildFrame(pressed), export const syncEmergencyStop = (val: any) => {
token: userInfo?.token, // 兼容后端可能下发的 boolean / 1 / 0 / "true" / "false"
userName: userInfo?.username, 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); console.log('[EmergencyStop] eStop=' + (active ? 1 : 0) + ' success');
setTimeout(() => send(false), 300); } 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();
});
}

View File

@@ -707,9 +707,9 @@ const zh = {
bKey: 'B 键', bKey: 'B 键',
bKeyDesc: '降底盘', bKeyDesc: '降底盘',
xKey: 'X 键', xKey: 'X 键',
xKeyDesc: '割刀加速', xKeyDesc: '割刀启动',
yKey: 'Y 键', yKey: 'Y 键',
yKeyDesc: '割刀减速', yKeyDesc: '割刀停止',
lbKey: 'LB 键', lbKey: 'LB 键',
lbDesc: '点火', lbDesc: '点火',
rbKey: 'RB 键', rbKey: 'RB 键',
@@ -726,8 +726,8 @@ const zh = {
chassisDown: '底盘下降', chassisDown: '底盘下降',
chassisDownHint: '底盘下降', chassisDownHint: '底盘下降',
cutterControl: '割刀控制', cutterControl: '割刀控制',
cutterAccel: '割刀加速', cutterAccel: '割刀启动',
cutterDecel: '割刀减速', cutterDecel: '割刀停止',
}, },
features: { features: {
title: '功能控制', title: '功能控制',

View File

@@ -1,4 +1,4 @@
import React, { lazy, Suspense } from 'react'; import React, { lazy, Suspense } from 'react';
import type { RouteObject } from 'react-router-dom'; import type { RouteObject } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -150,10 +150,7 @@ export const routes: RouteObject[] = [
path: 'agri', path: 'agri',
element: withSuspense(Agri) element: withSuspense(Agri)
}, },
{
path: 'alerts/all',
element: withSuspense(Alerts)
},
{ {
path: 'reportCenter/overview', path: 'reportCenter/overview',
element: withSuspense(ReportCenterOverview) element: withSuspense(ReportCenterOverview)