Files
web-Iot/src/components/devices/DeviceStatusPage.tsx

1658 lines
67 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, {
useState,
useEffect,
useMemo,
useRef,
useCallback,
} from 'react';
import {
Row,
Col,
Card,
Tag,
Typography,
Space,
Empty,
Descriptions,
Badge,
Progress,
Button,
Select,
message,
Modal,
Switch,
} from 'antd';
import {
DashboardOutlined,
GlobalOutlined,
VideoCameraOutlined,
ControlOutlined,
CameraOutlined,
ThunderboltOutlined,
EnvironmentOutlined,
DeleteOutlined,
SafetyOutlined,
LockOutlined,
UnlockOutlined,
LoadingOutlined,
PoweroffOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
PlusOutlined,
MinusOutlined,
} from '@ant-design/icons';
import {
getsinglePlan,
getsinglePlanTrack,
getFlightTaskDetail,
getUAVState,
getSiteDevice,
getSiteUAVList,
addRoute,
modeChage,
} from '../../api/device.ts';
import { useLocation } from 'react-router-dom';
import XboxController from './XboxController';
import RobotFeatureButtons from './RobotFeatureButtons';
import DPadControl from './DPadControl';
import ReverseCameraOverlay from './ReverseCameraOverlay';
import DroneVideoPlayer from './DroneVideoPlayer';
import CesiumMap from '../Map.jsx';
import { useSelector } from 'react-redux';
import { RootState } from '@/src/store/index.ts';
import { useWebRTCPlayer } from '../useWebRTCStream.tsx';
import VideoPlayer from '../VideoPlayer.tsx';
import SteerButton from './SteerButton';
import AgrtcRoomRobot from '../AgrtcRoomRobot';
import DeviceController from './DeviceController';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import { MowerAllView } from './MowerAllView';
import { useMqtt } from '@/hooks/useMqtt';
import envConfig from '../../../env';
import { dataUrlToFile } from '@/lib/utils.ts';
import { useUnitFormatter } from '@/lib/units';
import { PauseOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { backToRestPointCommand } from '@/api/mapEdit';
import CarReverseGuideLine from './CarReverseGuideLine';
import mowerImg from '../../assets/images/mower.png';
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' }}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: color || (online ? '#52c41a' : '#8c8c8c') }} />
{text}
</span>
);
const ConsoleRow = ({ icon, label, value }: any) => (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#8c8c8c', whiteSpace: 'nowrap' }}>
{icon}
{label}
</span>
<span style={{ fontSize: 12, color: '#262626', textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{value}</span>
</div>
);
// 暗色控制台面板(参考图样式:细边框、小圆角、蓝色竖条标题、右侧状态 badge)
const ConsolePanel = ({ title, extra, badge, children, style, bodyStyle }: any) => (
<div style={{ display: 'flex', flexDirection: 'column', background: '#fff', borderRadius: 10, overflow: 'hidden', ...style }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, padding: '8px 10px', borderBottom: '1px solid #f0f0f0', flexShrink: 0 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
<span style={{ width: 3, height: 14, borderRadius: 2, background: '#1890ff', flexShrink: 0 }} />
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, fontWeight: 600, color: '#262626', whiteSpace: 'nowrap' }}>{title}</span>
</span>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>{extra}{badge}</span>
</div>
<div style={{ flex: 1, minHeight: 0, padding: 10, ...bodyStyle }}>{children}</div>
</div>
);
// 方向盘功能按钮(暗色小方块,样式参考参考图)
// SteerButton:支持长按持续发送(与 DPadControl 方向键行为一致)
//const SteerButton = ({ icon, label, color, onPressStart, onPressEnd }: any) => {
// const [pressed, setPressed] = useState(false);
// const holdingRef = useRef(false);
// const intervalRef = useRef<number | null>(null);
// const emitEndedRef = useRef(false);
// const stopHold = useCallback(() => {
// if (intervalRef.current !== null) { window.clearInterval(intervalRef.current); intervalRef.current = null; }
// if (!holdingRef.current) return;
// holdingRef.current = false;
// emitEndedRef.current = false;
// setPressed(false);
// onPressEnd?.();
// }, [onPressEnd]);
// const startHold = useCallback(() => {
// if (holdingRef.current) return;
// holdingRef.current = true;
// emitEndedRef.current = false;
// setPressed(true);
// if (intervalRef.current !== null) window.clearInterval(intervalRef.current);
// // 立即首帧 + 每 100ms 持续(DPadControl 也是 100ms)
// onPressStart?.();
// intervalRef.current = window.setInterval(() => {
// if (!holdingRef.current) return;
// onPressStart?.();
// }, 100);
// }, [onPressStart]);
// useEffect(() => () => {
// if (intervalRef.current !== null) window.clearInterval(intervalRef.current);
// if (holdingRef.current) stopHold();
// }, [stopHold]);
// return (
// <button
// type="button"
// aria-label={label}
// onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); startHold(); }}
// onMouseUp={(e) => { e.preventDefault(); e.stopPropagation(); stopHold(); }}
// onMouseLeave={() => { if (holdingRef.current) stopHold(); }}
// onTouchStart={(e) => { e.preventDefault(); startHold(); }}
// onTouchEnd={(e) => { e.preventDefault(); stopHold(); }}
// onTouchCancel={() => { if (holdingRef.current) stopHold(); }}
// onContextMenu={(e) => e.preventDefault()}
// onClick={(e) => e.preventDefault()}
// style={{
// flex: '1 1 0',
// display: 'flex',
// flexDirection: 'column',
// alignItems: 'center',
// justifyContent: 'center',
// gap: 4,
// minHeight: 46,
// padding: '6px 4px',
// borderRadius: 8,
// background: pressed ? color + '30' : '#1e293b',
// border: '1px solid ' + (pressed ? color : color + '55'),
// color: color,
// cursor: 'pointer',
// userSelect: 'none',
// touchAction: 'none',
// transform: pressed ? 'scale(0.94)' : 'scale(1)',
// boxShadow: pressed ? '0 0 14px ' + color + '66' : 'none',
// transition: 'transform .08s, background .12s, border-color .12s, box-shadow .12s',
// }}
// >
// <span style={{ display: 'inline-flex', fontSize: 16, lineHeight: 1 }}>{icon}</span>
// <span style={{ fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap' }}>{label}</span>
// </button>
// );
//};
export default function DeviceStatusPage() {
const { t } = useTranslation();
const { userInfo } = useSelector((state: RootState) => state.user);
const { stationId, currentStation } = useSelector((state: RootState) => state.station);
const { formatTemperature } = useUnitFormatter();
const [persistentDroneData, setPersistentDroneData] = useState(null); // 持久化无人机数据
const [persistentHostData, setPersistentHostData] = useState(null); // 持久化机场数据
const [devices, setDevices] = useState([]);
const [planedevices, setPlaneDevices] = useState([]);
const [devicesAll, setDevicesAll] = useState([]);
const [arrivedPoint, setArrivedPoint] = useState(null);//完成点
const [isLoopMode, setIsLoopMode] = useState(true);
const controllerRef = useRef<DeviceController | null>(null);
const isFirstConnect = useRef(true);
const [detectReportInfo, setDeportInfo] = useState<any>(null);
// 标记本次会话是否已经发起过控制权限申请,避免手柄/方向盘高频更新时重复申请
const hasRequestedControlRef = useRef(false);
const [messageApi, contextHolder] = message.useMessage();
// 视频播放开关
const [isVideoPlaying, setIsVideoPlaying] = useState(false);
const toggleVideoPlay = useCallback(() => {
setIsVideoPlaying(prev => !prev);
}, []);
const [isControlled, setIsControlled] = useState(false);
const [hasControlRight, setHasControlRight] = useState(false);
const [connecting, setConnecting] = useState(false);
const [wsStatus, setWsStatus] = useState('disconnected');
const [wsDeviceInfo, setWsDeviceInfo] = useState({});
const [locationInfo, setLocationInfo] = useState({});
// 👇 加上这两个
const [queryTimeRange, setQueryTimeRange] = useState([]); // 时间范围
const [startTimestamp, setStartTimestamp] = useState(''); // 开始时间戳
const [endTimestamp, setEndTimestamp] = useState(''); // 结束时间戳
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalContent, setModalContent] = useState({
title: '',
content: '',
});
const [mowerView, setMowerView] = useState('front');
const [steerXY, setSteerXY] = useState({ x: 0, y: 0 });
const [isGamepadConnected, setIsGamepadConnected] = useState(false);
const [uavState, setUavState] = useState<any>(null);
const [points, setPoints] = useState([]);
const [clearNavLine, setClearNavLine] = useState(0);
const [clearPlanLine, setClearPlanLine] = useState(0);
const timerRef = useRef<any>(null);
// 打点相关状态
const [markedPoints, setMarkedPoints] = useState([]); // 标记的点
const [completeFlag, setCompleteFlag] = useState(false); // 是否完成路径规划
const [savePath, setSavePath] = useState(null); // 保存的路径数据
const [isSaveModalVisible, setIsSaveModalVisible] = useState(false); // 保存模态框可见性
const [plotName, setPlotName] = useState(''); // 地块名称
const [isSaving, setIsSaving] = useState(false); // 是否正在保存
const mapRef = useRef(null);
const clearDrawRef = useRef<(() => void) | null>(null); // 地图 ref
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const urlSn = queryParams.get('sn'); // 拿到路由上的sn
// 获取数据
const fetchAllData = async () => {
if (!stationId) return;
try {
// 1. 同时发请求
const [deviceRes, planeRes] = await Promise.all([
getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1, orgId: currentStation?.orgId }),
getSiteUAVList(stationId),
]);
// 2. 处理普通设备
const devData = deviceRes?.code === 200 ? (deviceRes.rows || []) : [];
// 3. 处理无人机 + 自动补全地图需要的字段(关键改动)
let planeData = planeRes?.code === 200 ? (planeRes?.rows || []) : [];
planeData = planeData.map(item => ({
...item,
type: 'plane',
lastRunningStatus: {
longitude: item.longitude || 0,
latitude: item.latitude || 0,
},
deviceAlias: item.drone_callsign || item.device_sn
|| t('constants.uav'),
}));
setDevices(devData);
setPlaneDevices(planeData);
// 合并所有设备
const all = [...devData, ...planeData];
setDevicesAll(all);
} catch (err) {
console.error('数据请求失败', err);
}
};
const handleFinishEdPoint = (point) => {
setArrivedPoint(point);
}
useEffect(() => {
fetchAllData();
}, [userInfo, stationId]);
// 当前选中的设备SN
const [selectedSn, setSelectedSn] = useState('');
// 当设备列表加载后,如果没有选中的设备,默认选中第一个
useEffect(() => {
if (devicesAll?.length > 0) {
// 优先从url参数匹配设备
if (urlSn) {
const target = devicesAll.find(d =>
(d.device_sn || d.serialNumber) === urlSn
);
if (target) {
setSelectedSn(urlSn);
setIsVideoPlaying(false);
return;
}
}
// url无sn / 没匹配到对应设备:默认选中第一个
const firstDevice = devicesAll[0];
setSelectedSn(firstDevice.device_sn || firstDevice.serialNumber);
setIsVideoPlaying(false);
}
}, [devicesAll, urlSn]);
// 获取当前选中的无人机设备
const device = useMemo(() => {
const sn = selectedSn;
if (!sn) return null;
return devicesAll?.find(
(d) => (d.device_sn || d.serialNumber) == sn,
);
}, [devicesAll, selectedSn]);
const isUAV = useMemo(() => {
// 设备有 drone_callsign 或 gateway_sn 则是无人机
return !!(device?.drone_callsign || device?.gateway_sn);
}, [device]);
// 设备选择变化时,调用回调并更新内部状态
const handleDeviceSelectChange = (val) => {
setSelectedSn(val);
// 切换设备时清空之前的标记点等
setMarkedPoints([]);
setCompleteFlag(false);
setSavePath(null);
};
// 当MQTT数据更新时,更新持久化数据(只在有新数据时更新)
const handleMqttMessage = useCallback((topic, message) => {
try {
const parsedMessage = JSON.parse(message);
if (parsedMessage.data && parsedMessage.data.host) {
const { host } = parsedMessage.data;
// 判断是无人机数据还是机场数据:无人机数据有 battery 字段
const isDroneData = host.battery !== undefined;
if (isDroneData) {
// 处理无人机数据
setPersistentDroneData(prevData => {
const newData = { ...prevData };
// 无人机特有字段
if (host.battery?.capacity_percent !== undefined) {
newData.capacity_percent = host.battery.capacity_percent;
}
if (host.attitude_head !== undefined) {
newData.heading = host.attitude_head;
}
if (host.horizontal_speed !== undefined) {
newData.horizontal_speed = host.horizontal_speed;
}
if (host.vertical_speed !== undefined) {
newData.vertical_speed = host.vertical_speed;
}
if (host.total_flight_time !== undefined) {
newData.total_flight_time = host.total_flight_time;
}
if (host.total_flight_sorties !== undefined) {
newData.total_flight_sorties = host.total_flight_sorties;
}
if (host.mode_code !== undefined) {
newData.mode_code = host.mode_code;
}
// 通用字段
if (host.height !== undefined) {
newData.height = host.height;
}
if (host.wind_speed !== undefined) {
newData.wind_speed = host.wind_speed;
}
if (host.position_state !== undefined) {
newData.position_state = host.position_state;
}
if (host.longitude !== undefined) {
newData.longitude = host.longitude;
}
if (host.latitude !== undefined) {
newData.latitude = host.latitude;
}
return newData;
});
} else {
// 处理机场数据
setPersistentHostData(prevData => {
const newData = { ...prevData };
// 机场特有字段
if (host.drone_charge_state?.capacity_percent !== undefined) {
newData.capacity_percent = host.drone_charge_state.capacity_percent;
}
if (host.air_conditioner?.air_conditioner_state !== undefined) {
newData.air_conditioner_state = host.air_conditioner.air_conditioner_state;
}
if (host.air_conditioner_state !== undefined) {
newData.air_conditioner_state = host.air_conditioner_state;
}
// 通用字段
if (host.environment_temperature !== undefined) {
newData.environment_temperature = host.environment_temperature;
}
if (host.wind_speed !== undefined) {
newData.wind_speed = host.wind_speed;
}
if (host.rainfall !== undefined) {
newData.rainfall = host.rainfall === 0 ? 'no_rain' : 'rain';
}
if (host.humidity !== undefined) {
newData.humidity = host.humidity;
}
if (host.drone_in_dock !== undefined) {
newData.drone_in_dock = host.drone_in_dock;
}
if (host.cover_state !== undefined) {
newData.cover_state = host.cover_state;
}
if (host.temperature !== undefined) {
newData.temperature = host.temperature;
}
if (host.home_distance !== undefined) {
newData.home_distance = host.home_distance;
}
return newData;
});
}
}
} catch (err) {
console.error('DeviceStatusPage MQTT 消息解析失败:', err);
}
}, []);
// 根据选中设备动态构建MQTT主题
const mqttTopics = useMemo(() => {
if (!isUAV || !device) {
return [];
}
const topics = [];
if (device.device_sn) {
topics.push(`thing/product/${device.device_sn}/osd`);
}
if (device.gateway_sn && device.gateway_sn !== device.device_sn) {
topics.push(`thing/product/${device.gateway_sn}/osd`);
}
return topics;
}, [isUAV, device]);
// 订阅MQTT消息
useMqtt({
url: envConfig.mqtt_url,
topic: mqttTopics,
onMessage: handleMqttMessage,
enabled: mqttTopics.length > 0,
});
// 合并无人机和机场数据
const currentDroneData = React.useMemo(() => {
return { ...persistentHostData, ...persistentDroneData };
}, [persistentDroneData, persistentHostData]);
// 实时位置数据(用于地图)
const runningStatus = useMemo(() => {
// 判断对象是否为空
if ((!wsDeviceInfo || Object.keys(wsDeviceInfo).length === 0) && (!locationInfo || Object.keys(locationInfo).length === 0) && !isUAV) {
return {};
}
if (isUAV) {
return {
...wsDeviceInfo,
};
}
const base = device?.lastRunningStatus || {};
return isUAV
? base
: {
...base,
...device?.locationMessage,
...wsDeviceInfo,
...locationInfo
};
}, [device, wsDeviceInfo, isUAV, locationInfo]);
// 实时下发的急停状态同步到共享锁存状态:true=已急停,false=未急停
useEffect(() => {
syncEmergencyStop(runningStatus?.emergency_stop);
}, [runningStatus?.emergency_stop]);
// 统一在线状态判断:优先实时数据,兜底接口数据
const isDeviceOnline = useMemo(() => {
// 1. 优先检查实时数据源(WebSocket 推送的 wsDeviceInfo / locationInfo)
const hasWsData = wsDeviceInfo && Object.keys(wsDeviceInfo).length > 0;
const hasLocData = locationInfo && Object.keys(locationInfo).length > 0;
if (hasWsData || hasLocData) {
return true;
}
return false;
//// 2. 检查 runningStatus 里是否有有效经纬度或实时状态字段
//const runningLon = runningStatus?.longitude;
//const runningLat = runningStatus?.latitude;
//const hasValidCoords = runningLon !== undefined && runningLon !== null && runningLon !== 0
// && runningLat !== undefined && runningLat !== null && runningLat !== 0;
//const hasFeStatus = runningStatus?.feStatus !== 3;
//const hasStatusField = runningStatus?.status !== 0;
//if (hasValidCoords || hasFeStatus || hasStatusField) {
// return true;
//}
// 3. 兜底用接口返回的 onlineStatus
return device?.onlineStatus == 1;
}, [device, wsDeviceInfo, locationInfo,]);
const { video: robotVideo, error, ready } = useWebRTCPlayer(
(!isUAV && isVideoPlaying && !device?.hasHost) ? (device?.serialNumber || '') : '',
(!isUAV && isVideoPlaying)
? `webrtc://1.95.137.212/live/livestream/${device?.serialNumber}`
: ''
);
//const { video: robotVideo, error, ready } = useWebRTCPlayer(
// !isUAV ? device?.serialNumber : '',
// `webrtc://1.95.137.212/live/livestream/${device?.serialNumber}`,
//);
const getVal = (val) => val === "no_rain" ? t('devices.rainNo') : (val || '-');
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 realtimePosition = React.useMemo(() => {
// 1. 无人机:优先用 MQTT 实时数据
if (isUAV) {
if (currentDroneData?.longitude && currentDroneData?.latitude) {
return {
lon: currentDroneData.longitude,
lat: currentDroneData.latitude,
heading: currentDroneData.heading || 0,
};
}
// 无人机没有实时数据时,用 lastRunningStatus 兜底
const baseLon = device?.lastRunningStatus?.longitude || device?.longitude;
const baseLat = device?.lastRunningStatus?.latitude || device?.latitude;
if (baseLon && baseLat) {
return {
lon: Number(baseLon),
lat: Number(baseLat),
heading: device?.lastRunningStatus?.heading || 0,
};
}
return null;
}
// 2. 机器人:优先从 wsDeviceInfo / runningStatus / locationInfo 取实时经纬度
let robotLon = runningStatus?.longitude || wsDeviceInfo?.longitude || locationInfo?.longitude;
let robotLat = runningStatus?.latitude || wsDeviceInfo?.latitude || locationInfo?.latitude;
// 3. 没有实时经纬度时,从 lastRunningStatus 兜底
if ((!robotLon || !robotLat) && (device?.lastRunningStatus || device?.locationMessage)) {
robotLon = robotLon || device?.lastRunningStatus?.longitude || device?.locationMessage?.longitude;
robotLat = robotLat || device?.lastRunningStatus?.latitude || device?.locationMessage?.latitude;
}
// 4. 最终兜底:设备静态经纬度
if ((!robotLon || !robotLat) && device) {
robotLon = robotLon || device.longitude;
robotLat = robotLat || device.latitude;
}
if (robotLon && robotLat) {
return {
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;
}, [isUAV, currentDroneData, runningStatus, wsDeviceInfo, locationInfo, device]);
// 寻车:地图定位到当前设备位置
const handleFindCar = () => {
if (!realtimePosition) {
messageApi.warning(t('devices.locationUnknown'));
return;
}
mapRef.current?.flyToPosition?.(realtimePosition, { height: 300 });
};
const handleDetectionReport = (res) => {
console.log("获取障碍物信息", res)
setDeportInfo(res);
}
useEffect(() => {
const controller = new DeviceController(userInfo, messageApi);
controller.onDeviceInfoUpdate = setWsDeviceInfo;
controller.onLocationInfoUpdate = setLocationInfo;
controller.onControlStatusChange = setIsControlled;
controller.onHasControlRightChange = setHasControlRight;
controller.onRequestControlStatusChange = setConnecting;
controller.onWsStatusChange = setWsStatus;
controller.handleArrivedPoint = handleFinishEdPoint;
controller.onDetectionReport = handleDetectionReport;
controller.onPermissionRequest = (content) => {
setModalContent(content);
setIsModalOpen(true);
};
controller.init();
controllerRef.current = controller;
return () => {
controller?.destroy();
controllerRef.current?.destroy();
controllerRef.current = null;
};
}, []);
useEffect(() => {
if (!device || !controllerRef.current || !device?.serialNumber || isUAV) {
return;
}
setWsDeviceInfo({});
setLocationInfo({});
if (isFirstConnect.current) {
isFirstConnect.current = false;
controllerRef.current.connectDevice(device);
} else {
controllerRef.current.switchDevice(device);
}
}, [device?.serialNumber]);
// 定时获取无人机状态
useEffect(() => {
const fetchUavState = async () => {
if (isUAV && device?.gateway_sn && device?.device_sn) {
try {
const res = await getUAVState({
sn: device.gateway_sn,
droneSn: device.device_sn
});
if (res.code === 200) {
setUavState(res.data);
}
} catch (err) {
console.error('获取无人机状态失败', err);
}
} else {
setUavState(null);
}
};
fetchUavState();
}, [isUAV, device]);
// 获取执行中任务的轨迹
useEffect(() => {
const fetchExecutingTaskTrack = async () => {
if (isUAV && device?.gateway_sn) {
try {
const todayStart = dayjs().startOf('day').unix();
const todayEnd = dayjs().endOf('day').unix();
const sns = [device.gateway_sn];
const res = await getsinglePlan({ sns, beginAt: todayStart, endAt: todayEnd });
if (res?.code === 200 && res.data) {
let combinedList = [];
Object.values(res.data).forEach((item: any) => {
if (item.list) combinedList = combinedList.concat(item.list);
});
// 筛选出执行中的任务
const executingTask = combinedList.find(t =>
['executing', 'running', 'restored'].includes(t.status)
);
if (executingTask) {
const trackRes = await getsinglePlanTrack(executingTask);
if (trackRes.code === 0 && trackRes.data.track?.points?.length) {
const trackPoints = trackRes.data.track.points.map(item => ({
lon: item.longitude || item.lon,
lat: item.latitude || item.lat
}));
setPoints(trackPoints);
} else {
setPoints([]);
}
} else {
setPoints([]);
}
} else {
setPoints([]);
}
} catch (err) {
console.error('获取执行中任务轨迹失败', err);
setPoints([]);
}
} else {
setPoints([]);
}
};
fetchExecutingTaskTrack();
}, [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;
return {
...device,
lastRunningStatus: {
...device.lastRunningStatus,
longitude: lng,
latitude: lat,
},
longitude: lng,
latitude: lat,
name: device?.deviceAlias || device?.callsign || device?.deviceName || t('devices.device'),
color: deviceColor,
type: isUAV
? 'drone'
: device?.productName?.includes(t('constants.mower'))
? 'mower'
: 'robot',
};
}, [device, isUAV, runningStatus, uavState, currentDroneData, wsDeviceInfo, locationInfo]);
const handleControlMode = (controlMode: number) => {
if (!selectedSn) {
messageApi.error(t('devices.selectDevice'));
return;
}
//console.log(runningStatus,controlMode, "现在的控制controlmode")
if ((controlMode == 3 && runningStatus?.control_mode == 3) || runningStatus?.systemMode == 3) {
messageApi.warning(t('devices.onRemoteControl'));
return;
}
const data = {
controlMode: controlMode,
deviceId: selectedSn
}
modeChage(data).then(res => {
if (res.code == 200 && res?.data) {
messageApi.success(t('devices.controlModeSuccess'));
} else {
messageApi.error(t('devices.controlModeFail'));
}
}).catch(err => {
messageApi.success(t('devices.controlModeFail'));
}
)
}
const realtimeDevice = useMemo(() => {
if (!device) return null;
return {
...device,
...uavState,
...currentDroneData, // 持久化数据最后覆盖,确保优先显示
};
}, [device, uavState, currentDroneData]);
// 模式/权限提示节流:仅在用户真实操作(有按键或摇杆输入)时提示,2 秒内只提示一次
// 避免点击页面其他区域、手柄轮询中性帧、失焦复位等无输入帧误触发提示
const controlWarnRef = useRef(0);
const handleGamepadUpdate = useCallback((state) => {
const hasInput =
//(Array.isArray(state?.buttons) && state.buttons.some((v: any) => v == true || v == 1)) ||
(Array.isArray(state?.axes) && state.axes.some((v: any) => Math.abs(Number(v) || 0) > 0.05));
// 只有真实操作才做模式与权限校验,中性帧(无按键、轴为 0)不提示
if (hasInput) {
const now = Date.now();
if (now - controlWarnRef.current > 2000) {
let warned = false;
// 无控制权限时:提示(避免手柄/方向盘高频更新刷屏)
if (!isControlled) {
messageApi.warning("请获取控制权限");
warned = true;
}
console.log(runningStatus, "realtimePosition1111")
if (!(runningStatus?.control_mode == 3 || runningStatus?.systemMode == 3)) {
messageApi.warning(t('devices.switchControl'));
warned = true;
} else if (
runningStatus?.controlMode != 3 &&
runningStatus?.controlMode != 0 &&
runningStatus?.controlMode != null
) {
messageApi.warning(t('devices.noRemoteControl'));
warned = true;
}
if (warned) controlWarnRef.current = now;
}
}
console.log('Gamepad state updated:', state);
// 记录方向盘 xy 坐标,用于倒车影像叠加层
if (state?.axes) {
setSteerXY({ x: state.axes[2] || 0, y: state.axes[1] || 0 });
}
// 无论是否有输入(含 false/中性帧)都必须下发,保证设备侧能收到释放/停止状态
controllerRef.current?.sendGamepad(state);
}, [isControlled, connecting]);
// 手柄已连接时拦截面板操作并提示(2 秒内只提示一次,避免高频刷屏)
const gamepadWarnRef = useRef(0);
const blockIfGamepadConnected = useCallback(() => {
// 没连接手柄 或 还没获取控制权限 → 不拦截(没控制权限本来就发不出消息)
if (!isGamepadConnected) return false;
if (!isControlled) {
messageApi.warning("请获取控制权限");
return false;
}
const now = Date.now();
if (now - gamepadWarnRef.current > 2000) {
gamepadWarnRef.current = now;
messageApi.warning(t('devices.disconnectGamepadFirst'));
}
return true;
}, [isGamepadConnected, isControlled, t, messageApi]);
// 方向盘功能按钮:复用与手柄一致的遥控帧(指定位按下后短暂释放)
// 方向盘按键按下/释放帧(长按模式:onDown 每 100ms 调用一次;短按模式:sendSteerButton 一次性发送后 300ms 自动释放)
const sendSteerFrame = useCallback(
(index: number, pressed: boolean) => {
if (blockIfGamepadConnected()) return;
const buttons = new Array(17).fill(false);
buttons[index] = pressed;
handleGamepadUpdate({
buttons,
axes: [0, 0, 0, 0],
connected: true,
ts: Date.now(),
});
},
[handleGamepadUpdate, blockIfGamepadConnected],
);
const sendSteerButton = useCallback((index: number) => {
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();
}, []);
// 获得控制权限后,重置"已申请"标记,以便后续失去权限时可再次提示
useEffect(() => {
if (isControlled) {
hasRequestedControlRef.current = false;
}
}, [isControlled]);
const handleOk = () => {
controllerRef.current?.sendPermissionRequest(
true,
'switchResult',
);
setIsControlled(false);
setIsModalOpen(false);
};
const handleCancel = () => {
controllerRef.current?.sendPermissionRequest(
false,
'switchResult',
);
setIsControlled(true);
setIsModalOpen(false);
};
const fix2 = (val) => {
if (val === null || val === undefined || isNaN(val)) {
return '-';
}
return Number(val).toFixed(2);
};
const handleAutoBack = () => {
const payload = {
deviceId: selectedSn,
orgId: currentStation?.orgId,
siteId: stationId,
}
backToRestPointCommand(payload).then(res => { }).catch(err => {
console.error('返回休息点失败', err);
})
}
// 打点功能
const handleMarkPoint = () => {
if (!realtimePosition) {
message.warning(t('devices.locationFail'));
return;
}
const newPoint = {
lon: Number(realtimePosition.lon),
lat: Number(realtimePosition.lat),
};
setMarkedPoints([...markedPoints, newPoint]);
messageApi.success(t('devices.pointMarked', { count: markedPoints.length + 1 }));
};
// Map click to add marked point
const handleMapMarkPoint = (point) => {
setMarkedPoints([...markedPoints, { lon: Number(point.lon), lat: Number(point.lat) }]);
messageApi.success(t('devices.pointMarked', { count: markedPoints.length + 1 }));
};
// 撤回上一个打点
const handleUndoMark = () => {
if (markedPoints.length === 0) {
message.info(t('devices.noPointsToUndo'));
return;
}
const newPoints = markedPoints.slice(0, -1);
setMarkedPoints(newPoints);
messageApi.success(t('devices.pointUndone', { count: newPoints.length }));
};
// 清空标记点
const handleClearPoints = () => {
setMarkedPoints([]);
setCompleteFlag(false);
setSavePath(null);
clearDrawRef.current?.();
};
const getPathPoints = (coords) => {
console.log("getPathPoints", coords)
//setPathPoints(coords);
if (!coords || coords.length === 0) return;
const newWps = coords.map((p, i) => ({
id: i + 1,
lon: p.lon.toFixed(6),
lat: p.lat.toFixed(6),
}));
console.log("newWps", newWps)
//setWaypoints(newWps);
};
// 完成功能 - 调用路径规划接口
const handleSave = async () => {
if (!plotName.trim()) {
messageApi.warning(t('devices.inputPlotName'));
return;
}
setIsSaving(true);
try {
// ✅重点:接收handleComplete返回的path数据,不再读组件savePath state
const pathResult = await handleComplete();
if (!pathResult) {
messageApi.warning(t('devices.saveFail'));
// 路径规划失败/校验不通过直接终止
return;
}
// 1. 获取地图截图
let screenshotDataUrl = null;
if (mapRef.current) {
screenshotDataUrl = await mapRef.current.captureScreenshot();
}
// 2. 创建 FormData
const formData = new FormData();
// 3. 添加文件
if (screenshotDataUrl) {
// 将 dataUrl 转换为 Blob
const file = dataUrlToFile(screenshotDataUrl, "screenshot.jpg");
console.log("blob", file)
if (file instanceof File) {
formData.append('file', file);
}
}
// 4. 添加 workRecord,直接使用函数返回的 pathResult,不读取state savePath
const workRecord = {
workName: plotName,
siteId: stationId,
orgId: currentStation?.orgId,
jsonData: pathResult, // 直接用返回值,彻底规避state异步延迟
mode: isLoopMode ? "coverage" : "single_point",//"区域还是单点"
};
console.log("workRecord", workRecord)
formData.append(
"workRecord",
new Blob([JSON.stringify(workRecord)], {
type: "application/json"
})
);
// 5. 调用保存接口
const res = await addRoute(formData);
if (res.code === 200) {
messageApi.success(t('common.saveSuccess'));
setIsSaveModalVisible(false);
// 重置状态
setMarkedPoints([]);
setCompleteFlag(false);
setSavePath(null);
} else {
messageApi.error(res.msg || t('common.saveFail'));
}
} catch (error) {
console.error('保存失败:', error);
messageApi.error(t('common.saveFail'));
} finally {
setIsSaving(false);
}
};
/**
* 修改handleComplete:计算完成后 return路径对象;失败返回null
*/
const handleComplete = async () => {
//如果是闭环模式
if (isLoopMode) {
if (markedPoints.length < 3) {
messageApi.warning(t('devices.minThreePoints'));
return null; //校验失败返回null
}
try {
// 准备路径规划请求参数
let positionPoints = [...markedPoints];
// =========新增:保证闭环,第一个点和最后一个点一致=========
const firstPt = positionPoints[0];
const lastPt = positionPoints[positionPoints.length - 1];
// 判断经纬度是否相等,不相等就把首点追加到末尾
if (!(firstPt.lat === lastPt.lat && firstPt.lon === lastPt.lon)) {
positionPoints.push({ ...firstPt });
}
const requestParams = {
outer: {
position: positionPoints.map(point => ({
lat: point.lat,
lng: point.lon,
})),
},
};
const path = requestParams?.outer?.position
setPoints(path);
const resultObj = {
path: path,
outer: requestParams?.outer?.position?.map(p => {
return {
lng: p.lon,
lat: p.lat
}
}),
};
setSavePath(resultObj);
setCompleteFlag(true);
messageApi.success(t('devices.pathPlanDone'));
return resultObj; // ✅返回计算好的数据给上层调用
} catch (error) {
console.error('路径规划失败:', error);
messageApi.error(t('devices.pathPlanFailRetry'));
return null;
}
} else {
// 单点模式
const positionPoints = [...markedPoints].map(item => {
return {
lng: item.lon,
lat: item.lat
}
});
setPoints(positionPoints);
const resultObj = {
path: positionPoints,
outer: [],
};
setSavePath(resultObj);
setCompleteFlag(true);
return resultObj; // ✅返回
}
};
const getDeviceType = (device) => {
if (!device) return '';
if (device?.deviceType === 'I') {
return t("devices.paramEnum.deviceTypeI");
} else if (device?.deviceType === 'M') {
return t("devices.paramEnum.deviceTypeM");
} else if (device?.deviceType === 'U') {
return t("devices.paramEnum.deviceTypeU");
} return t("devices.robot");
}
// 打开保存模态框
const handleOpenSaveModal = () => {
//if (!completeFlag) {
// messageApi.warning(t('devices.completePathFirst'));
// return;
//}
setPlotName('');
setIsSaveModalVisible(true);
};
const realtimeType = useMemo(() => {
return isUAV ? 'plane' : 'car';
}, [isUAV]);
if (!device) {
return (
<Empty
description={t('video.selectDevice')}
style={{ marginTop: 100 }}
/>
);
}
return (
<div style={{ background: 'linear-gradient(180deg, #f0f4f8 0%, #e8eef5 100%)', minHeight: '100%', padding: 0 }}>
<style>{`
.ds-card { box-shadow: 0 2px 12px rgba(0,0,0,0.06) !important; border: 1px solid #e8edf3 !important; }
.ds-card:hover { box-shadow: 0 4px 20px rgba(0,0,0,0.1) !important; transition: box-shadow 0.3s ease; }
`}</style>
<div style={{ padding: '4px 0px 8px' }}>
<Typography.Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.2vw, 18px)', color: '#262626' }}>机器人控制</Typography.Title>
</div>
<div style={{ padding: 0 }}>
{contextHolder}
<div
style={{
marginBottom: 8,
display: 'flex',
alignItems: 'center',
gap: 12,
flexWrap: 'wrap',
}}
>
<Text strong>{t('devices.selectDevice')}:</Text>
<Select
style={{ width: 380, minWidth: 280 }}
value={selectedSn}
onChange={handleDeviceSelectChange}
showSearch
optionFilterProp="label"
placeholder={t('video.selectDevice')}
allowClear={false}
loading={devicesAll?.length === 0}
options={[
{
label: t('devices.robot'),
title: 'robot',
options: devicesAll?.filter(item => !item.gateway_sn && !item.drone_callsign && item.serialNumber).map(item => ({
value: item.device_sn || item.serialNumber,
label: `${item.deviceAlias || item.deviceName || t('devices.unknownDevice')} `,
})),
},
{
label: t('constants.uav'),
title: 'uav',
options: devicesAll?.filter(item => item?.gateway_sn || item?.drone_callsign).map(item => ({
value: item?.device_sn,
label: `${item?.drone_callsign || item?.callsign || t('devices.unknownDrone')}`,
})),
},
].filter(group => group?.options?.length > 0)}
/>
<Tag color={isUAV ? 'cyan' : 'blue'}>
{isUAV ? t('constants.uav') : getDeviceType(device)}
</Tag>
<Tag color={isDeviceOnline ? 'green' : 'default'}>
{isDeviceOnline ? t('devices.online') : t('devices.offline')}
</Tag>
</div>
{/* 无人机专用布局 */}
{isUAV ? (
<Row gutter={[16, 16]} align="stretch">
{/* 左侧:机场视频 + 地图 */}
<Col xs={24} lg={8}>
{/* 无人机场视频 + 机场状态 */}
<Card className="ds-card"
title={
<>
<VideoCameraOutlined />
{t('devices.stationVideo')}
</>
}
variant="borderless"
style={{ borderRadius: 12, marginBottom: 8 }}
styles={{ body: { padding: 12 } }}
>
<div style={{ borderRadius: 8, overflow: 'hidden', height: 300 }}>
<DroneVideoPlayer
device={realtimeDevice}
height={300}
dualVideo={false}
showSourceSelect={false}
videoSource="station"
statusData={{ ...persistentHostData, ...uavState }}
displayType="station"
/>
</div>
</Card>
{/* 地图 */}
<Card className="ds-card"
title={
<>
<GlobalOutlined />
{t('devices.situationMap')}
</>
}
extra={
<Space size={4}>
<Button
size="small"
type="primary"
icon={<DeleteOutlined />}
onClick={() => setClearNavLine((v) => v + 1)}
>
{t('devices.clearRealtimeTrack')}
</Button>
<Button
size="small"
danger
icon={<DeleteOutlined />}
onClick={() => {
setPoints([]);
setClearPlanLine((v) => v + 1);
}}
>
{t('devices.clearPlanRoute')}
</Button>
</Space>
}
variant="borderless"
style={{ borderRadius: 12 }}
styles={{ body: { padding: 12, height: 400 } }}
>
<CesiumMap
ref={mapRef}
devices={[mapDevices]}
points={points}
markedPoints={markedPoints}
realtimePosition={realtimePosition}
realtimeType={realtimeType}
onPathChange={getPathPoints}
drawRealTime={true}
finishPoint={arrivedPoint}
ifClearNavLine={clearNavLine}
ifClearPlanLine={clearPlanLine}
detectReportInfo={detectReportInfo}
from="deviceStatus" onMarkPoint={handleMapMarkPoint} onClearDraw={(fn) => { clearDrawRef.current = fn; }}
/>
</Card>
</Col>
{/* 右侧:无人机视频 + 无人机状态 */}
<Col xs={24} lg={16}>
{/* 无人机视频 + 无人机状态 */}
<Card className="ds-card"
title={
<>
<VideoCameraOutlined />
{t('devices.droneVideo')}
</>
}
variant="borderless"
style={{ borderRadius: 12, marginBottom: 8 }}
styles={{ body: { padding: 12 } }}
>
<div style={{ borderRadius: 8, overflow: 'hidden', height: "100%" }}>
<DroneVideoPlayer
device={realtimeDevice}
height={760}
dualVideo={false}
showSourceSelect={false}
videoSource="drone"
statusData={{ ...persistentDroneData, ...uavState }}
displayType="drone"
/>
</div>
</Card>
</Col>
</Row>
) : (
// 机器人布局:暗色控制台风格(按参考图重排),所有原有交互与数据绑定保持不变
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<Row gutter={[10, 10]} align="stretch">
{/* ===== 设备状态 ===== */}
<Col xs={24} lg={7} style={{ display: 'flex' }}>
<ConsolePanel
style={{ flex: 1, height: 600 }}
title={<><DashboardOutlined /> {t('devices.deviceStatus')}</>}
badge={<ConsoleBadge online={isDeviceOnline} text={isDeviceOnline ? t('devices.online') : t('devices.offline')} />}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
<img src={mowerImg} alt="" style={{ width: 60, height: 60, objectFit: 'contain', flexShrink: 0 }} />
<div style={{ minWidth: 0 }}>
<div style={{ color: '#262626', fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{device?.deviceAlias || device?.deviceName || t('devices.unknownDevice')}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, fontSize: 12, color: isDeviceOnline ? '#52c41a' : '#8c8c8c' }}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: isDeviceOnline ? '#52c41a' : '#8c8c8c' }} />
{isDeviceOnline ? t('devices.online') : t('devices.offline')}
</div>
</div>
</div>
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 12, paddingRight: 4 }}>
<ConsoleRow icon={<ThunderboltOutlined />} label={t('devices.rtBattery')} value={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><span style={{ width: 86, height: 8, borderRadius: 4, background: '#f0f0f0', display: 'inline-block', overflow: 'hidden' }}><span style={{ display: 'block', height: '100%', background: '#52c41a', width: (Math.min(100, Math.max(0, Number(runningStatus?.battery_percentage ?? runningStatus?.battery ?? 0))) + '%') }} /></span>{(runningStatus?.battery_percentage ?? runningStatus?.battery) !== undefined ? (runningStatus?.battery_percentage ?? runningStatus?.battery) + '%' : '-'}</span>} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtVoltage')} value={(runningStatus?.battery_voltage ?? runningStatus?.voltage) !== undefined ? Number(runningStatus?.battery_voltage ?? runningStatus?.voltage).toFixed(2) + 'V' : '-'} />
<ConsoleRow
icon={<ControlOutlined />}
label={t('devices.rtMode')}
value={
(runningStatus?.control_mode ?? runningStatus?.controlMode) !== undefined
? (() => {
const mode =
runningStatus?.control_mode ?? runningStatus?.controlMode;
switch (mode) {
case '0':
case 0:
return t('devices.controlOff');
case '1':
case 1:
return t('devices.localCpntrol');
case '2':
case 2:
return t('devices.autoTask');
case '3':
case 3:
return t('devices.remoteControl');
default:
return "-";
}
})()
: '-'
}
/>
<ConsoleRow
icon={<DashboardOutlined />}
label={t('devices.systemMode')}
value={(() => {
const mode =
runningStatus?.system_mode ??
runningStatus?.systemMode ??
runningStatus?.control_mode ??
runningStatus?.controlMode;
switch (mode) {
case '2':
case 2:
return t('devices.autoTask');
case '3':
case 3:
return t('devices.remoteControl');
case '0':
case 0:
return t('devices.controlOff');
case '1':
case 1:
return t('devices.localCpntrol');
default:
return '-';
}
})()}
/>
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.forwardSpeed')} value={(runningStatus?.linear_speed ?? runningStatus?.linearSpeed) !== undefined ? Number(runningStatus?.linear_speed ?? runningStatus?.linearSpeed).toFixed(2) + ' m/s' : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.turnSpeed')} value={(runningStatus?.angular_speed ?? runningStatus?.angularSpeed) !== undefined ? Number(runningStatus?.angular_speed ?? runningStatus?.angularSpeed).toFixed(2) + ' rad/s' : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftMotor')} value={(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent) !== undefined ? Number(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent).toFixed(2) + 'A' : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightMotor')} value={(runningStatus?.right_motor_current ?? runningStatus?.rightCurrent) !== undefined ? Number(runningStatus?.right_motor_current ?? runningStatus?.rightCurrent).toFixed(2) + 'A' : '-'} />
<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.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={<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' : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightMotorRpm')} value={runningStatus?.right_motor_rpm !== undefined ? Number(runningStatus?.right_motor_rpm).toFixed(1) + 'rpm' : '-'} />
{/*<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkArea')} value={runningStatus?.total_work_area !== undefined ? Number(runningStatus?.total_work_area).toFixed(2) : '-'} />
<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkDuration')} value={runningStatus?.total_work_duration !== undefined ? Number(runningStatus?.total_work_duration).toFixed(0) : '-'} />
<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkDistance')} value={runningStatus?.total_work_distance !== undefined ? Number(runningStatus?.total_work_distance).toFixed(2) : '-'} />*/}
</div>
</div>
</ConsolePanel>
</Col>
{/* ===== 四路视频 ===== */}
<Col xs={24} lg={10} style={{ display: 'flex' }}>
<ConsolePanel
style={{ flex: 1, height: 600 }}
title={<><VideoCameraOutlined /> {t('devices.realtimeVideoMonitor')}</>}
badge={isVideoPlaying ? <ConsoleBadge online text={t('devices.liveBadge')} /> : null}
extra={
<Button
size="small"
type="text"
style={{ color: '#1890ff' }}
icon={isVideoPlaying ? <PauseOutlined /> : <PlayCircleOutlined />}
onClick={toggleVideoPlay}
>
{isVideoPlaying ? t('video.stop') : t('video.play')}
</Button>
}
bodyStyle={{ padding: 8, display: 'flex', flexDirection: 'column', gap: 8 }}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0, overflowX: 'auto' }}>
{[{ key: 'front', label: t('devices.frontView') }, { key: 'left', label: t('devices.leftView') }, { key: 'right', label: t('devices.rightView') }, { key: 'back', label: t('devices.backView') }, { key: 'all', label: t('devices.panorama') }].map((v) => (
<Button key={v.key} type={mowerView === v.key ? 'primary' : 'default'} size="small" onClick={() => setMowerView(v.key)}>
{v.label}
</Button>
))}
</div>
<div style={{ position: 'relative', flex: 1, minHeight: 0, borderRadius: 8, overflow: 'hidden', }}>
{isVideoPlaying && (
mowerView === 'all' ? (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<MowerAllView serialNumber={device?.serialNumber} robotVideo={robotVideo} error={error} ready={ready} />
</div>
) : mowerView === 'front' ? (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<AgrtcRoomRobot CHANNEL={"cam2-17"} />
<CarReverseGuideLine
direction="forward"
steer={steerXY.x * 45}
linearSpeed={Number(runningStatus?.linear_speed ?? runningStatus?.linearSpeed)}
angularSpeed={Number(runningStatus?.angular_speed ?? runningStatus?.angularSpeed)}
visible={isVideoPlaying}
/>
</div>
) : (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<VideoPlayer
deviceId={device?.serialNumber}
idx={mowerView === 'back' ? 2 : mowerView === 'left' ? 3 : 4}
className="w-full h-full object-contain"
video={robotVideo}
error={error}
ready={ready}
/>
{mowerView === 'back' && (
<CarReverseGuideLine
direction="reverse"
steer={steerXY.x * 45}
linearSpeed={Number(runningStatus?.linear_speed ?? runningStatus?.linearSpeed)}
angularSpeed={Number(runningStatus?.angular_speed ?? runningStatus?.angularSpeed)}
visible={isVideoPlaying}
/>
)}
</div>
)
)}
{!isVideoPlaying && (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 12, color: 'rgba(14, 78, 198, 0.55)' }}>
<VideoCameraOutlined style={{ fontSize: 56, opacity: 0.6 }} />
<div style={{ fontSize: 15 }}>{t('devices.videoStopped')}</div>
<div style={{ fontSize: 12, opacity: 0.7 }}>{t('devices.clickPlayHint')}</div>
</div>
)}
</div>
</ConsolePanel>
</Col>
{/* ===== 实时地图 ===== */}
<Col xs={24} lg={7} style={{ display: 'flex' }}>
<ConsolePanel
style={{ flex: 1, height: 600 }}
title={<><GlobalOutlined /> {t('devices.situationMap')}</>}
extra={
<Space size={4}>
<Button size="small" type="primary" icon={<DeleteOutlined />} onClick={() => setClearNavLine((v) => v + 1)}>{t('devices.clearRealtimeTrack')}</Button>
<Button size="small" danger icon={<DeleteOutlined />} onClick={() => { setPoints([]); setClearPlanLine((v) => v + 1); }}>{t('devices.clearPlanRoute')}</Button>
</Space>
}
bodyStyle={{ padding: 8, display: 'flex' }}
>
<div style={{ flex: 1, minHeight: 0, borderRadius: 8, overflow: 'hidden', position: 'relative' }}>
<CesiumMap
ref={mapRef}
devices={[mapDevices]}
points={points}
markedPoints={markedPoints}
realtimePosition={realtimePosition}
realtimeType={realtimeType}
drawRealTime={true}
finishPoint={arrivedPoint}
ifClearNavLine={clearNavLine}
ifClearPlanLine={clearPlanLine}
detectReportInfo={detectReportInfo}
from="deviceStatus"
onMarkPoint={handleMapMarkPoint}
onClearDraw={(fn) => { clearDrawRef.current = fn; }}
/>
<div style={{ position: 'absolute', top: 8, left: 8, zIndex: 10, background: 'rgba(0,0,0,0.55)', color: '#fff', padding: '8px 12px', borderRadius: 8, fontSize: 12, backdropFilter: 'blur(4px)', boxShadow: '0 2px 8px rgba(0,0,0,0.3)', display: 'flex', flexDirection: 'column', gap: 4 }}>
{/*<div style={{ fontWeight: 600, color: '#91caff' }}>{t('devices.rtPositioning')}:{runningStatus?.qual == 0 ? t('constants.locationInvalid') : runningStatus?.qual == 1 ? t('devices.gpsSingle') : runningStatus?.qual == 2 ? t('devices.dgpsDiff') : runningStatus?.qual == 4 ? t('devices.rtkFixed2') : runningStatus?.qual == 5 ? t('devices.rtkFloat') : t('constants.locationUnknown')}</div>*/}
{/*<div>{t('devices.rtSatellites')}:{t('devices.satelliteCount', { count: runningStatus?.satelliteCnt || 0 })}</div>*/}
<div>{t('devices.rtHeadingAngle')}:{runningStatus?.yaw !== undefined ? Number(runningStatus?.yaw).toFixed(1) + '°' : '-'}</div>
{/*<div>{t('devices.rtRollAngle')}:{runningStatus?.roll !== undefined ? Number(runningStatus?.roll).toFixed(1) + '°' : '-'}</div>
<div>{t('devices.rtPitchAngle')}:{runningStatus?.pitch !== undefined ? Number(runningStatus?.pitch).toFixed(1) + '°' : '-'}</div>*/}
</div>
</div>
</ConsolePanel>
</Col>
</Row>
{/* ===== 下行:手柄控制 / 方向盘控制 / 功能控制 ===== */}
<Row gutter={[10, 10]} align="stretch">
<Col xs={24} lg={10} style={{ display: 'flex' }}>
<ConsolePanel
style={{ flex: 1, minHeight: 300 }}
title={<><ControlOutlined /> {t('devices.gamepadControl')}</>}
badge={<ConsoleBadge online={isGamepadConnected} text={isGamepadConnected ? t('devices.controllerConnected') : t('devices.controllerNotConnected')} />}
extra={
<Space size={8}>
<Tag
icon={connecting ? <LoadingOutlined /> : (isControlled ? <UnlockOutlined /> : <LockOutlined />)}
color={connecting ? 'gold' : (isControlled ? 'green' : 'red')}
style={{ margin: 0, fontSize: 12 }}
>
{connecting ? t('devices.controlRequesting') : isControlled ? t('devices.controlGranted') : t('devices.noControlRight')}
</Tag>
{isControlled ? (
<Button size="small" danger icon={<LockOutlined />} onClick={() => { controllerRef.current?.release?.(); setIsControlled(false); }}>{t('devices.releaseControl')}</Button>
) : (
<Button size="small" type="primary" icon={<UnlockOutlined />} loading={connecting} onClick={handleControlModal}>{t('devices.requestControl')}</Button>
)}
</Space>
}
bodyStyle={{ padding: 10, display: 'flex', alignItems: 'center', gap: 10, overflow: 'hidden' }}
>
<div style={{ width: 300, flexShrink: 0, transform: 'scale(0.82)', transformOrigin: 'left center' }}>
<XboxController onGamepadUpdate={handleGamepadUpdate} onConnectionChange={setIsGamepadConnected} deviceId={selectedSn} />
</div>
<div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6, overflow: 'auto' }}>
{[{ k: t('devices.gamepad.leftStick'), v: t('devices.gamepad.leftStickDesc') }, { k: t('devices.gamepad.rightStick'), v: t('devices.gamepad.rightStickDesc') }, { k: t('devices.gamepad.aKey'), v: t('devices.gamepad.aKeyDesc') }, { k: t('devices.gamepad.bKey'), v: t('devices.gamepad.bKeyDesc') }, { k: t('devices.gamepad.xKey'), v: t('devices.gamepad.xKeyDesc') }, { k: t('devices.gamepad.yKey'), v: t('devices.gamepad.yKeyDesc') }, { k: "LB", v: t("devices.gamepad.lbDesc") }, { k: "RB", v: t("devices.gamepad.rbDesc") }, { k: "Stop", v: t("devices.gamepad.Stop") }].map((item) => (
<div key={item.k} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
<span style={{ minWidth: 52, color: '#8c8c8c', whiteSpace: 'nowrap' }}>{item.k}</span>
<span style={{ color: '#262626' }}>{item.v}</span>
</div>
))}
</div>
</ConsolePanel>
</Col>
<Col xs={24} lg={7} style={{ display: 'flex' }}>
<ConsolePanel
style={{ flex: 1, minHeight: 300 }}
title={<><ControlOutlined /> {t('devices.steeringControl')}</>}
bodyStyle={{ padding: 10, display: 'flex', alignItems: 'center', gap: 12, overflow: 'auto' }}
>
<div style={{ width: '100%', maxWidth: 200 }}>
<DPadControl
onGamepadUpdate={(state) => { if (blockIfGamepadConnected()) return; handleGamepadUpdate(state); }}
onSpeedChange={() => { }}
onEmergencyStop={() => sendEmergencyStop(selectedSn)}
/>
</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" 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" 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" 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>
</Col>
<Col xs={24} lg={7} style={{ display: 'flex' }}>
<ConsolePanel
style={{ minHeight: 300, flex: 'none', width: '100%' }}
title={<><SafetyOutlined style={{ color: '#fa541c' }} /> {t('devices.features.title')}</>}
bodyStyle={{ padding: 10, display: 'flex', flex: "auto" }}
>
<RobotFeatureButtons
showEmergencyStop
deviceId={selectedSn}
activeFeatures={['response', 'obstacleAvoidance', 'lowBatteryReturn', 'tiltProtection', "findCar"]}
onToggle={(feature, enabled) => { console.log('[DeviceStatusPage] Feature toggled: ' + feature + ' = ' + enabled); }}
sendFindCar={() => handleFindCar()}
sendAutoBack={() => handleAutoBack()}
sendControlMode={(data) => handleControlMode(data)}
controlMode={runningStatus?.controlMode}
/>
</ConsolePanel>
</Col>
</Row>
</div >
)
}
<Modal
open={isModalOpen}
onOk={handleOk}
onCancel={handleCancel}
title={modalContent?.title}
okText={t('common.ok')}
cancelText={t('common.cancel')}
>
<p>{modalContent?.content}</p>
</Modal>
{/* 保存路径模态框 */}
<Modal
open={isSaveModalVisible}
title={t('devices.savePathTitle')}
onOk={handleSave}
onCancel={() => setIsSaveModalVisible(false)}
okText={t('common.save')}
cancelText={t('common.cancel')}
confirmLoading={isSaving}
>
<div style={{ marginBottom: 16 }}>
<label style={{ display: 'block', marginBottom: 8 }}>{t('devices.plotNameLabel')}</label>
<input
type="text"
value={plotName}
onChange={(e) => setPlotName(e.target.value)}
placeholder={t('devices.inputPlotName')}
style={{
width: '100%',
padding: '8px 12px',
border: '1px solid #d9d9d9',
borderRadius: 4,
fontSize: 14,
}}
/>
</div>
{isSaving && (
<div style={{ textAlign: 'center', padding: '16px 0' }}>
<div style={{
display: 'inline-block',
width: 30,
height: 30,
border: '3px solid #1890ff',
borderTopColor: 'transparent',
borderRadius: '50%',
animation: 'spin 0.8s linear infinite',
}} />
<div style={{ marginTop: 8, color: '#666' }}>{t('devices.saving')}</div>
</div>
)}
<style>
{`
@keyframes spin {
to {
transform: rotate(360deg);
}
}
`}
</style>
</Modal>
</div >
</div >
);
}