根据不同账号 显示的首页优化 规划界面 悬浮显示 状态信息 全局急停状态统一 割刀 根据新方案对接 两个状态 任务路线 显示为 抽拉式一行一个 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

@@ -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<DPadControlProps> = ({
const [pressed, setPressed] = useState<Record<string, boolean>>({});
const [speed, setSpeed] = useState(0.5);
// 急停锁存状态:与其他入口(手柄 / 功能按钮)共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
// 每个物理输入单独记录,避免同方向不同按键互相干扰
// 例如 ArrowUp 和 W 可以同时按下
@@ -69,7 +74,6 @@ const DPadControl: React.FC<DPadControlProps> = ({
const speedRef = useRef(0.5);
const pressTimer = useRef<number | null>(null);
const disabledRef = useRef(disabled);
const emergencyTimer = useRef<number | null>(null);
const onGamepadUpdateRef = useRef(onGamepadUpdate);
const onSpeedChangeRef = useRef(onSpeedChange);
@@ -204,29 +208,11 @@ const DPadControl: React.FC<DPadControlProps> = ({
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<DPadControlProps> = ({
// 防止长按空格时重复触发急停
if (!e.repeat) {
startEmergency();
toggleEmergency();
}
return;
@@ -287,7 +273,7 @@ const DPadControl: React.FC<DPadControlProps> = ({
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<DPadControlProps> = ({
};
}, [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<DPadControlProps> = ({
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}
>
<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">

View File

@@ -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<any>({});
// 急停锁存状态:与 DPadControl / XboxController 共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
const controllerRef = useRef<DeviceController | null>(null);
const [messageApi, contextHolder] = message.useMessage();
const [taskList, setTaskList] = useState<any[]>([]);
@@ -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 <Progress
percent={v}
size="small"
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: 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'),
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) => <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('alerts.alarmTitle'),
@@ -1076,8 +1102,8 @@ export default function DeviceOverviewPage() {
<span style={{ fontSize: 20, color: '#1890ff' }}><CarOutlined /></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 }}>
{selectedDevice.onlineStatus == 1 ? t('devices.online') : t('devices.offline')}
<Tag color={realtimeDevice.status == 1 || realtimeDevice.status == 2 ? "success" : "default"} size="small" style={{ margin: 0 }}>
{realtimeDevice.status == 1 || realtimeDevice.status == 2 ? t('devices.online') : t('devices.offline')}
</Tag>
<Button
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', alignItems: 'center', gap: 4 }}>
<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>
{realtimeDevice?.environment_temperature && (
<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 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 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>

View File

@@ -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) => (
<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
};
}, [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<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(() => {
console.log('请求控制权限');
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.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={<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={<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.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' : '-'} />
@@ -1453,16 +1523,16 @@ export default function DeviceStatusPage() {
</div>
<div style={{ width: '100%', display: 'flex', flexDirection: 'column', 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={<PoweroffOutlined />} label={t('devices.steer.shutdown')} color="#ef4444" onPressStart={() => sendSteerFrame(5, true)} onPressEnd={() => sendSteerFrame(5, 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" active={steerState.power === 'shutdown'} onToggle={() => toggleSteerGroup('power', 'shutdown')} />
</div>
<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={<ArrowDownOutlined />} label={t('devices.steer.chassisDown')} color="#3b82f6" onPressStart={() => sendSteerFrame(1, true)} onPressEnd={() => sendSteerFrame(1, 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" active={steerState.chassis === 'down'} onToggle={() => toggleSteerGroup('chassis', 'down')} />
</div>
<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={<MinusOutlined />} label={t('devices.steer.cutterDecel')} color="#f59e0b" onPressStart={() => sendSteerFrame(3, true)} onPressEnd={() => sendSteerFrame(3, 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" active={steerState.blade === 'stop'} onToggle={() => toggleSteerGroup('blade', 'stop')} />
</div>
</div>
</ConsolePanel>

View File

@@ -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);

View File

@@ -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<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 (
<button
type="button"
aria-label={label}
aria-pressed={pressed}
onPointerDown={(e) => {
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',
}}
>
<span style={{ display: 'inline-flex', fontSize: 16, lineHeight: 1 }}>

View File

@@ -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<DeviceController | null>(null);
const isFirstConnect = useRef(true);
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) => {
@@ -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 && (
<div
style={{
@@ -1820,7 +1810,7 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
})()}
</span>
<span>
{/*<span>
{t('devices.systemMode')}
{(() => {
const mode = robotRealtimePosition?.sm || robotRealtimePosition?.sm;
@@ -1850,16 +1840,13 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
</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 }}>
@@ -2301,61 +2288,61 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
{(!routeList || routeList.length === 0) ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 280, overflowY: 'auto' }}>
{groupRoutesByMode(routeList, t).map(group => (
<div key={group.key}>
<div style={{ fontSize: 12, fontWeight: 600, color: group.color, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
<Collapse
size="small"
ghost
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 }} />
{group.label}
<span style={{ color: '#999', fontWeight: 400, fontSize: 11 }}>({group.items.length})</span>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
),
children: (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{group.items.map(route => {
const checked = dispatchRouteIds.includes(route.id);
return (
<Tag.CheckableTag
<div
key={route.id}
checked={checked}
style={{
display: 'inline-flex',
alignItems: 'center',
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) {
// 选择下发路径时,取消上方任务规划的选中
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',
}}
>
<span
style={{
color: '#344054',
display: 'inline-block',
}}
>
{route.workName || route.name}
</span>
</Tag.CheckableTag>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: group.color, flex: '0 0 auto' }} />
<span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{route.workName || route.name}</span>
{checked && <span style={{ color: '#1677ff', fontWeight: 700 }}>✓</span>}
</div>
);
})}
</div>
</div>
))}
</div>
)
}))}
/>
)}
</div>
)}

View File

@@ -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<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 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 }) => {
<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>
<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>
</g>
{/* Menu Buttons + Text Label button8=急停, button9=Menu */}
<circle cx="180" cy="140" r="6" fill={buttons[8] ? "#22d3ee" : "#334155"} />
<text x="180" y="152" textAnchor="middle" fill={buttons[8] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold">急停</text>
{/* Emergency Stop button 急停 */}
<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"} />
<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>
</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 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();
});
}