diff --git a/src/components/devices/DPadControl.tsx b/src/components/devices/DPadControl.tsx index 833c55a..6ebb4db 100644 --- a/src/components/devices/DPadControl.tsx +++ b/src/components/devices/DPadControl.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { ChevronUp, ChevronDown, ChevronLeft, ChevronRight, Circle } from 'lucide-react'; +import { ChevronUp, ChevronDown, ChevronLeft, ChevronRight, Circle, ShieldAlert } from 'lucide-react'; export interface GamepadState { buttons: boolean[]; @@ -13,6 +13,7 @@ interface DPadControlProps { onGamepadUpdate?: (state: GamepadState) => void; onSpeedChange?: (speed: number) => void; disabled?: boolean; + onEmergencyStop?: () => void; } // 键盘按键映射 @@ -31,7 +32,7 @@ const KEY_MAP: Record = { D: 'right', }; -const DPadControl: React.FC = ({ onGamepadUpdate, onSpeedChange, disabled = false }) => { +const DPadControl: React.FC = ({ onGamepadUpdate, onSpeedChange, disabled = false, onEmergencyStop }) => { const { t } = useTranslation(); const [pressed, setPressed] = useState>({}); const [speed, setSpeed] = useState(0.5); @@ -181,6 +182,29 @@ const DPadControl: React.FC = ({ onGamepadUpdate, onSpeedChang ); + const startEmergency = () => { + if (disabled) return; + pressedRef.current = { ...pressedRef.current, center: true }; + setPressed(pressedRef.current); + onEmergencyStop?.(); + window.setTimeout(() => { + pressedRef.current = { ...pressedRef.current, center: false }; + setPressed(pressedRef.current); + }, 350); + }; + + const renderEmergency = () => ( + + ); + return (
{/* 十字方向键 */} @@ -189,7 +213,7 @@ const DPadControl: React.FC = ({ onGamepadUpdate, onSpeedChang {renderBtn('up', , t('devices.dpad.up'))}
{renderBtn('left', , t('devices.dpad.left'))} - {renderBtn('center', , t('devices.dpad.center'))} + {onEmergencyStop ? renderEmergency() : renderBtn('center', , t('devices.dpad.center'))} {renderBtn('right', , t('devices.dpad.right'))}
{renderBtn('down', , t('devices.dpad.down'))} diff --git a/src/components/devices/DeviceStatusPage.tsx b/src/components/devices/DeviceStatusPage.tsx index 0364cee..72243bc 100644 --- a/src/components/devices/DeviceStatusPage.tsx +++ b/src/components/devices/DeviceStatusPage.tsx @@ -1,1834 +1,3251 @@ 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, + } 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 CarReverseGuideLine from './CarReverseGuideLine'; + +import mowerImg from '../../assets/images/mower.png'; + +import { sendEmergencyStop } from './emergencyStopControl'; + const { RangePicker } = DatePicker; + + const { Text } = Typography; + +const ConsoleBadge = ({ online, text, color }: any) => ( + + + + + + {text} + + + +); + + + +const ConsoleRow = ({ icon, label, value }: any) => ( + +
+ + + + {icon} + + {label} + + + + {value} + +
+ +); + + + +// 暗色控制台面板(参考图样式:细边框、小圆角、蓝色竖条标题、右侧状态 badge) + +const ConsolePanel = ({ title, extra, badge, children, style, bodyStyle }: any) => ( + +
+ +
+ + + + + + {title} + + + + {extra}{badge} + +
+ +
{children}
+ +
+ +); + + + + + +// 方向盘功能按钮(暗色小方块,样式参考参考图) + +// SteerButton:支持长按持续发送(与 DPadControl 方向键行为一致) +//const SteerButton = ({ icon, label, color, onPressStart, onPressEnd }: any) => { +// const [pressed, setPressed] = useState(false); +// const holdingRef = useRef(false); +// const intervalRef = useRef(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 ( +// +// ); +//}; + + + + + 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(null); + const isFirstConnect = useRef(true); + // 标记本次会话是否已经发起过控制权限申请,避免手柄/方向盘高频更新时重复申请 + 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(null); + const [points, setPoints] = useState([]); + const [clearNavLine, setClearNavLine] = useState(0); + const [clearPlanLine, setClearPlanLine] = useState(0); + const timerRef = useRef(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 handleChange = (checked: boolean) => { + setIsLoopMode(checked); + if (checked) { + console.log('当前作业方式:回字'); + } else { + console.log('当前作业方式:单点'); + } + }; + + + // 获取数据 + 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; + } + 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]); + + 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 = { + '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, + }; + } + + return null; + }, [isUAV, currentDroneData, runningStatus, wsDeviceInfo, locationInfo, device]); + + // 寻车:地图定位到当前设备位置 + const handleFindCar = () => { + if (!realtimePosition) { + messageApi.warning(t('devices.locationUnknown')); + return; + } + mapRef.current?.flyToPosition?.(realtimePosition, { height: 300 }); + }; + + 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.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; + + // 优先使用持久化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'), + type: isUAV + ? 'drone' + : device?.productName?.includes(t('constants.mower')) + ? 'mower' + : 'robot', + }; + }, [device, isUAV, runningStatus, uavState, currentDroneData]); + const realtimeDevice = useMemo(() => { + if (!device) return null; + return { + ...device, + ...uavState, + ...currentDroneData, // 持久化数据最后覆盖,确保优先显示 + }; + }, [device, uavState, currentDroneData]); + + const handleGamepadUpdate = useCallback((state) => { - console.log('handleGamepadUpdate called with state:', isControlled); + // 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏) + //if (!isControlled) { + // //if (!hasRequestedControlRef.current && !connecting) { + // // hasRequestedControlRef.current = true; + // // handleControlModal(); + // //} + // return; + //} + console.log('Gamepad state updated:', state); + // 记录方向盘 xy 坐标,用于倒车影像叠加层 + if (state?.axes) { + setSteerXY({ x: state.axes[2] || 0, y: state.axes[1] || 0 }); + } + controllerRef.current?.sendGamepad(state); + }, [isControlled, connecting]); + + + // 手柄已连接时拦截面板操作并提示(2 秒内只提示一次,避免高频刷屏) + + const gamepadWarnRef = useRef(0); + + const blockIfGamepadConnected = useCallback(() => { + + if (!isGamepadConnected) return false; + + const now = Date.now(); + + if (now - gamepadWarnRef.current > 2000) { + + gamepadWarnRef.current = now; + + messageApi.warning(t('devices.disconnectGamepadFirst')); + + } + + return true; + + }, [isGamepadConnected, 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]); + + + 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 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 handleOpenSaveModal = () => { + //if (!completeFlag) { + // messageApi.warning(t('devices.completePathFirst')); + // return; + //} + setPlotName(''); + setIsSaveModalVisible(true); + }; + + + + const realtimeType = useMemo(() => { + return isUAV ? 'plane' : 'car'; + }, [isUAV]); + + + if (!device) { + return ( + + ); + } + + + + + return ( +
+ +
- {t('devices.deviceStatus')} + + 机器人控制 +
+ + +
+ {contextHolder} + + {/* 页面顶部按钮区域 */} + {!isUAV && ( +
+
+ {t('devices.pathPlanning')}: - {t('devices.markedPointsCount', { count: markedPoints?.length })} + + {t('devices.markedPointsCount', { count: markedPoints?.length })} +
+ + + {t('devices.workMode')} + + {isLoopMode ? t('devices.bowMode') : t('devices.abMode')} + + + + + {/**/} + + +
+ )} + +
+ {t('devices.selectDevice')}: + + setPlotName(e.target.value)} + placeholder={t('devices.inputPlotName')} + style={{ + width: '100%', + padding: '8px 12px', + border: '1px solid #d9d9d9', + borderRadius: 4, + fontSize: 14, + }} + /> +
+ {isSaving && ( +
+
+
{t('devices.saving')}
+
+ )} + + +
+
+ ); + } + diff --git a/src/components/devices/RobotFeatureButtons.tsx b/src/components/devices/RobotFeatureButtons.tsx index 5688f8a..77c6607 100644 --- a/src/components/devices/RobotFeatureButtons.tsx +++ b/src/components/devices/RobotFeatureButtons.tsx @@ -20,7 +20,6 @@ export type RobotFeature = | 'findCar' | 'autoback'; - export interface FeatureConfig { key: RobotFeature; icon: React.ReactNode; @@ -28,71 +27,86 @@ export interface FeatureConfig { inactiveColor: string; } +// 功能方块:方块样式展示,不再包含急停(急停已移至方向盘中键) const FEATURES: FeatureConfig[] = [ - { key: 'emergencyStop', icon: , activeColor: '#ef4444', inactiveColor: '#94a3b8' }, - { key: 'obstacleAvoidance', icon: , activeColor: '#3b82f6', inactiveColor: '#94a3b8' }, - { key: 'lowBatteryReturn', icon: , activeColor: '#f59e0b', inactiveColor: '#94a3b8' }, - { key: 'tiltProtection', icon: , activeColor: '#10b981', inactiveColor: '#94a3b8' }, - //{ key: 'findCar', icon: , activeColor: '#22c55e', inactiveColor: '#c4158c' }, - { key: 'autoback', icon: , activeColor: '#22c55e', inactiveColor: '#133c75' }, - - + { key: 'obstacleAvoidance', icon: , activeColor: '#3b82f6', inactiveColor: '#94a3b8' }, + { key: 'lowBatteryReturn', icon: , activeColor: '#f59e0b', inactiveColor: '#94a3b8' }, + { key: 'tiltProtection', icon: , activeColor: '#10b981', inactiveColor: '#94a3b8' }, + { key: 'autoback', icon: , activeColor: '#22c55e', inactiveColor: '#94a3b8' }, + { key: 'findCar', icon: , activeColor: '#ef4444', inactiveColor: '#94a3b8' }, ]; +// 急停方块(仅在 showEmergencyStop 时展示,兼容其他页面) +const EMERGENCY: FeatureConfig = { + key: 'emergencyStop', + icon: , + activeColor: '#ef4444', + inactiveColor: '#ef4444', +}; + interface RobotFeatureButtonsProps { activeFeatures?: RobotFeature[]; onToggle?: (feature: RobotFeature, enabled: boolean) => void; className?: string; + showEmergencyStop?: boolean; + sendFindCar: () => {} } const RobotFeatureButtons: React.FC = ({ activeFeatures = [], onToggle, className = '', + showEmergencyStop = true, + sendFindCar, }) => { const { t } = useTranslation(); const { userInfo } = useSelector((state: RootState) => state.user); const [active, setActive] = useState>(new Set(activeFeatures)); + const list = showEmergencyStop ? [EMERGENCY, ...FEATURES] : FEATURES; + const handleClick = (feature: RobotFeature) => { + // 急停:点击时直接下发 button7(绕过控制权限校验) + if (feature === 'emergencyStop') { + sendEmergencyStop(userInfo); + onToggle?.(feature, true); + return; + } + // 寻车:下发指令的同时,与其他功能一样切换选中状态(toggle 效果) + if (feature === 'findCar') { + sendFindCar?.(); + } const next = !active.has(feature); const nextSet = new Set(active); if (next) nextSet.add(feature); else nextSet.delete(feature); setActive(nextSet); - // 急停:点击时直接下发 button7(绕过控制权限校验) - if (feature === 'emergencyStop') sendEmergencyStop(userInfo); onToggle?.(feature, next); }; return ( -
- {FEATURES.map((f) => { +
+ {list.map((f) => { const isActive = active.has(f.key); return ( ); })} diff --git a/src/components/devices/Steerbutton.tsx b/src/components/devices/Steerbutton.tsx new file mode 100644 index 0000000..8448e97 --- /dev/null +++ b/src/components/devices/Steerbutton.tsx @@ -0,0 +1,153 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; + +interface SteerButtonProps { + icon: React.ReactNode; + label: string; + color: string; + onPressStart?: () => void; + onPressEnd?: () => void; + interval?: number; +} + +const SteerButton = ({ + icon, + label, + color, + onPressStart, + onPressEnd, + interval = 100, +}: SteerButtonProps) => { + const [pressed, setPressed] = useState(false); + + // 是否处于按下状态 + const holdingRef = useRef(false); + + // 定时发送句柄 + const timerRef = useRef | null>(null); + + // 保存最新的回调,避免定时器使用过期闭包 + const onPressStartRef = useRef(onPressStart); + const onPressEndRef = useRef(onPressEnd); + + useEffect(() => { + onPressStartRef.current = onPressStart; + }, [onPressStart]); + + useEffect(() => { + onPressEndRef.current = onPressEnd; + }, [onPressEnd]); + + // 停止长按 + const stopHold = useCallback(() => { + if (!holdingRef.current) return; + + holdingRef.current = false; + + if (timerRef.current !== null) { + clearTimeout(timerRef.current); + timerRef.current = null; + } + + setPressed(false); + + // 只在有效按压结束时发送一次释放数据 + onPressEndRef.current?.(); + }, []); + + // 开始长按 + const startHold = useCallback(() => { + // 防止重复触发 + if (holdingRef.current) return; + + holdingRef.current = true; + setPressed(true); + + // 立即发送第一帧 + onPressStartRef.current?.(); + + // 持续发送 + const scheduleNext = () => { + if (!holdingRef.current) return; + + timerRef.current = setTimeout(() => { + if (!holdingRef.current) return; + + onPressStartRef.current?.(); + + scheduleNext(); + }, interval); + }; + + scheduleNext(); + }, [interval]); + + // 组件卸载时清理定时器 + useEffect(() => { + return () => { + holdingRef.current = false; + + if (timerRef.current !== null) { + clearTimeout(timerRef.current); + timerRef.current = null; + } + }; + }, []); + + return ( + + ); +}; +export default SteerButton; diff --git a/src/components/devices/XboxController.tsx b/src/components/devices/XboxController.tsx index d8981c1..bd900bb 100644 --- a/src/components/devices/XboxController.tsx +++ b/src/components/devices/XboxController.tsx @@ -1,7 +1,6 @@ import React, { useEffect, useState, useRef } from 'react'; import { useTranslation } from 'react-i18next'; - -const XboxController = ({ onGamepadUpdate }) => { +const XboxController = ({ onGamepadUpdate, onConnectionChange }) => { const { t } = useTranslation(); const [gamepadState, setGamepadState] = useState<{ buttons: boolean[]; @@ -12,22 +11,20 @@ const XboxController = ({ onGamepadUpdate }) => { axes: [0, 0, 0, 0], connected: false, }); - const requestRef = useRef(null); // 用 ref 保存最新的回调,避免 RAF 循环闭包捕获旧 props 导致权限判断失效 const onGamepadUpdateRef = useRef(onGamepadUpdate); onGamepadUpdateRef.current = onGamepadUpdate; + const onConnectionChangeRef = useRef(onConnectionChange); + onConnectionChangeRef.current = onConnectionChange; const DEAD_ZONE = 0.08; - const normalizeAxis = (v: number) => Math.abs(v) < DEAD_ZONE ? 0 : Number(v.toFixed(2)); const lastSendRef = useRef(0); const SEND_INTERVAL = 1000 / 10; // 20Hz const lastPayloadRef = useRef(''); - const updateGamepad = () => { const gp = navigator.getGamepads()[0]; - if (gp) { const state = { buttons: gp.buttons.map(b => b.pressed), @@ -35,16 +32,12 @@ const XboxController = ({ onGamepadUpdate }) => { connected: true, ts: Date.now(), }; - setGamepadState(state); - const payload = JSON.stringify({ buttons: state.buttons, axes: state.axes, }); - const now = performance.now(); - if ( now - lastSendRef.current > SEND_INTERVAL // payload !== lastPayloadRef.current @@ -59,74 +52,54 @@ const XboxController = ({ onGamepadUpdate }) => { requestRef.current = requestAnimationFrame(updateGamepad); return; } - requestRef.current = requestAnimationFrame(updateGamepad); }; useEffect(() => { requestRef.current = requestAnimationFrame(updateGamepad); - const onFocus = () => { // 页面重新获得焦点 → 立刻重拉一次 requestRef.current = requestAnimationFrame(updateGamepad); }; - window.addEventListener('focus', onFocus); - return () => { if (requestRef.current) cancelAnimationFrame(requestRef.current); window.removeEventListener('focus', onFocus); }; }, []); // ✅ 空依赖 - useEffect(() => { setTimeout(() => { window.focus(); navigator.getGamepads(); // 🔥 强制触发一次 }, 0); }, [/* 页面切换依赖 */]); - useEffect(() => { const handleConnect = (e: GamepadEvent) => { console.log('🎮 Gamepad connected:', e.gamepad.id); setGamepadState(prev => ({ ...prev, connected: true })); }; - const handleDisconnect = (e: GamepadEvent) => { console.log('❌ Gamepad disconnected'); //handleControlModal({ control: false }); setGamepadState(prev => ({ ...prev, connected: false })); }; - window.addEventListener('gamepadconnected', handleConnect); window.addEventListener('gamepaddisconnected', handleDisconnect); - return () => { window.removeEventListener('gamepadconnected', handleConnect); window.removeEventListener('gamepaddisconnected', handleDisconnect); }; }, []); - // UI mapping for Xbox Gamepad - - //点火熄火 上面俩 AB升降底盘 XY割刀加减速 button7急停 - // Buttons: 0:A, 1:B, 2:X, 3:Y, 4:LB, 5:RB, 6:LT, 7:RT, 8:Back, 9:Start, 10:LS, 11:RS, 12:Up, 13:Down, 14:Left, 15:Right + //点火熄火 上面俩 AB升降底盘 XY割刀加减速 button8急停 BUTTON4点火 BUTTON5熄火 const { buttons, axes, connected } = gamepadState; - const getAxisStyle = (axisX: number, axisY: number) => ({ transform: `translate(${axisX * 6}px, ${axisY * 6}px)`, }); - + useEffect(() => { + onConnectionChangeRef.current?.(gamepadState.connected); + }, [gamepadState.connected]); return (
- {/* 手柄硬件连接状态指示(仅表示物理手柄是否连接) */} -
- {connected ? t('devices.controllerConnected') : t('devices.controllerNotConnected')} -
{/* Main Body */} @@ -138,22 +111,23 @@ const XboxController = ({ onGamepadUpdate }) => { transform="scale(1, 1.08)" transformOrigin="200px 180px" /> - {/* Triggers & Bumpers */} + + LB + RB + {/* 左右耳朵标识:左=点火 右=熄火 */} {/* LT / RT Indicators */} - {/* Left Stick Area */} - {/* Right Stick Area */} { strokeWidth="1" strokeDasharray="2 2" /> - { /> - {/* D-Pad */} @@ -194,21 +166,28 @@ const XboxController = ({ onGamepadUpdate }) => { - - {/* Buttons (ABXY) */} + {/* Buttons (ABXY) + Text Label */} {/* A */} - {/* B */} - {/* X */} - {/* Y */} - + A - {/* Menu Buttons */} + {/* B */} + B + + {/* X */} + X + + {/* Y */} + Y + + {/* Menu Buttons + Text Label button8=急停, button9=Menu */} + 急停 + + Menu
); }; - export default XboxController; diff --git a/src/locales/en/index.ts b/src/locales/en/index.ts index 1369176..08244a7 100644 --- a/src/locales/en/index.ts +++ b/src/locales/en/index.ts @@ -286,7 +286,7 @@ idle: 'Idle', busy: 'Busy', error: 'Error', - deviceControl: 'Device Control', + deviceControl: 'Robot Control', realtimeVideo: 'Live Video', takeoff: 'Take Off', land: 'Land', @@ -632,6 +632,57 @@ landingDockSnLabel: 'Landing Dock Sn Label', leftView: 'Left View', leftWheelDrive: 'Left Wheel Drive', + gamepadControl: 'Gamepad Control', + steeringControl: 'Steering Control', + disconnectGamepadFirst: 'Please disconnect the gamepad first', + liveBadge: 'Live', + totalWorkArea: 'Total Work Area', + totalWorkDuration: 'Total Work Duration', + totalWorkDistance: 'Total Work Distance', + motionStatus: 'Motion Status', + motionMoving: 'Moving', + motionStopped: 'Stopped', + motionBlocked: 'Blocked', + rtEmergency: 'Emergency Stop', + estopTriggered: 'Triggered', + estopNormal: 'Normal', + rtLeftTargetRpm: 'Left Target RPM', + rtRightTargetRpm: 'Right Target RPM', + rtLeftMeasureRpm: 'Left Measured RPM', + rtRightMeasureRpm: 'Right Measured RPM', + rtLeftMotorRpm: 'Left Motor RPM', + rtRightMotorRpm: 'Right Motor RPM', + gamepad: { + leftStick: 'Left Stick', + leftStickDesc: 'Control direction', + rightStick: 'Right Stick', + rightStickDesc: 'Control arm', + aKey: 'A Key', + aKeyDesc: 'Raise chassis', + bKey: 'B Key', + bKeyDesc: 'Lower chassis', + xKey: 'X Key', + xKeyDesc: 'Cutter faster', + yKey: 'Y Key', + yKeyDesc: 'Cutter slower', + lbKey: 'LB', + lbDesc: 'Ignition', + rbKey: 'RB', + rbDesc: 'Shut Down', + }, + steer: { + ignition: 'Ignition', + ignitionHint: 'Start engine', + shutdown: 'Shut Down', + shutdownHint: 'Stop engine', + chassisUp: 'Raise Chassis', + chassisUpHint: 'Chassis up', + chassisDown: 'Lower Chassis', + chassisDownHint: 'Chassis down', + cutterControl: 'Cutter Control', + cutterAccel: 'Cutter Faster', + cutterDecel: 'Cutter Slower', + }, features: { title: 'Feature Control', emergencyStop: 'Emergency Stop', @@ -802,6 +853,8 @@ realtimePicture: 'Realtime Picture', realtimePowerData: 'Realtime Power Data', realtimeSpeed: 'Realtime Speed', + forwardSpeed: 'Forward Speed', + turnSpeed: 'Turn Speed', realtimeVideoMonitor: 'Realtime Video Monitor', rechargeBtn: 'Recharge Btn', rechargeCommandSent: 'Recharge Command Sent', @@ -852,6 +905,7 @@ routeSavedLocal: 'Route Saved Local', rtBattery: 'Battery', rtHeadingAngle: 'rt Heading Angle', + rtRollAngle: 'rt Roll Angle', rtHeadingStatus: 'rt Heading Status', rtInitialized: 'rt Initialized', rtLeftMotor: 'Left Motor', diff --git a/src/locales/zh/index.ts b/src/locales/zh/index.ts index 42ddd65..df5015e 100644 --- a/src/locales/zh/index.ts +++ b/src/locales/zh/index.ts @@ -301,7 +301,7 @@ const zh = { idle: '空闲', busy: '忙碌', error: '故障', - deviceControl: '设备控制', + deviceControl: '机器人控制', realtimeVideo: '实时视频', takeoff: '起飞', land: '降落', @@ -657,6 +657,59 @@ const zh = { leftWheelDrive: '左轮驱动', locationUnknown: '定位未知', + gamepadControl: '手柄控制', + steeringControl: '方向盘控制', + disconnectGamepadFirst: '请先断开手柄', + liveBadge: '直播中', + totalWorkArea: '累计作业面积', + totalWorkDuration: '累计作业时长', + totalWorkDistance: '累计作业里程', + motionStatus: '运动状态', + motionMoving: '行进中', + motionStopped: '已停止', + motionBlocked: '受阻', + rtEmergency: '急停状态', + estopTriggered: '已触发', + estopNormal: '正常', + rtLeftTargetRpm: '左目标转速', + rtRightTargetRpm: '右目标转速', + rtLeftMeasureRpm: '左测量转速', + rtRightMeasureRpm: '右测量转速', + rtLeftMotorRpm: '左电机转速', + rtRightMotorRpm: '右电机转速', + forwardSpeed: '前进速度', + turnSpeed: '转向速度', + gamepad: { + leftStick: '左摇杆', + leftStickDesc: '控制行进方向', + rightStick: '右摇杆', + rightStickDesc: '控制左右', + aKey: 'A 键', + aKeyDesc: '升底盘', + bKey: 'B 键', + bKeyDesc: '降底盘', + xKey: 'X 键', + xKeyDesc: '割刀加速', + yKey: 'Y 键', + yKeyDesc: '割刀减速', + lbKey: 'LB 键', + lbDesc: '点火', + rbKey: 'RB 键', + rbDesc: '熄火', + }, + steer: { + ignition: '点火', + ignitionHint: '发动机启动', + shutdown: '熄火', + shutdownHint: '关闭发动机', + chassisUp: '底盘升起', + chassisUpHint: '底盘上升', + chassisDown: '底盘下降', + chassisDownHint: '底盘下降', + cutterControl: '割刀控制', + cutterAccel: '割刀加速', + cutterDecel: '割刀减速', + }, features: { title: '功能控制', emergencyStop: '急停', @@ -882,16 +935,17 @@ const zh = { rtHeadingAngle: '航向角度', rtHeadingStatus: '航向状态', rtInitialized: '已初始化', - rtLeftMotor: '左电机', + rtLeftMotor: '左电机电流', rtLeftSpeed: '左速度', - rtLeftTemp: '左温度', - rtMainTemp: '主温度', + rtLeftTemp: '左电机温度', + rtMainTemp: '芯片温度', rtMode: '模式', rtPitchAngle: '俯仰角度', + rtRollAngle: '翻滚角度', rtPositioning: '定位', - rtRightMotor: '右电机', + rtRightMotor: '右电机电流', rtRightSpeed: '右速度', - rtRightTemp: '右温度', + rtRightTemp: '右电机温度', rtSatellites: '卫星数量', rtVoltage: '电压', rthMode: '返航模式', @@ -920,7 +974,7 @@ const zh = { selectWayline: '选择航线', selectedWaylineColon: '已选航线', signalSatellite: '信号卫星', - situationMap: '态势地图', + situationMap: '地图', smartAssign: '智能分配', standbyCount: '待机数量', startBtn: '开始按钮', diff --git a/src/pages/Devices.tsx b/src/pages/Devices.tsx index a3a0c0d..b553cbe 100644 --- a/src/pages/Devices.tsx +++ b/src/pages/Devices.tsx @@ -26,7 +26,7 @@ export default function DeviceIndexPage() { const menuItems = [ { key: 'overview', label: t('devices.equipmentOverview'), icon: }, - { key: 'status', label: t('devices.deviceStatus'), icon: }, + { key: 'status', label: t('devices.deviceControl'), icon: }, { key: 'wayLineTask', label: t('devices.waylineTask'), icon: }, { key: 'robotTask', label: t('devices.robotTask'), icon: }, ];