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, DatePicker } 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 { deviceRunParamSelectByDeviceId } from '@/api/stationManage/index'; 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) => ( {text} ); // 暗色控制台面板(参考图样式:细边框、小圆角、蓝色竖条标题、右侧状态 badge) const ConsolePanel = ({ title, extra, badge, children, style, bodyStyle }: any) => (
{title} {extra}{badge}
{children}
); 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 [detectReportInfo, setDeportInfo] = useState(null); // 标记本次会话是否已经发起过控制权限申请,避免手柄/方向盘高频更新时重复申请 const hasRequestedControlRef = useRef(false); const [messageApi, contextHolder] = message.useMessage(); // 视频播放开关 const [isVideoPlaying, setIsVideoPlaying] = useState(false); // 当前机器人摄像头路数(接口返回 cameraNum,1-4) const [cameraNum, setCameraNum] = useState(1); // 行车辅助线开关(仅前视/后视单路叠加) const [showGuideLine, setShowGuideLine] = useState(true); // 设备 Agora 视频频道号(后端 paramData 或 device 字段;最终兜底 SN) const toggleVideoPlay = useCallback(() => { setIsVideoPlaying(prev => !prev); }, []); // 选中机器人变化 → 拉设备参数,取 cameraNum 决定视频网格布局(1/2/4 路) 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 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); } const ConsoleRow = ({ icon, label, value }: any) => (
{icon} {label} {value}
); 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, }); useEffect(() => { const id = device?.device_sn || device?.serialNumber || selectedSn; if (!id || !stationId) { setCameraNum(1); return; } let cancelled = false; deviceRunParamSelectByDeviceId({ deviceId: id }).then((res) => { if (cancelled) return; if (res?.code === 200) { const n = Number(res.data?.cameraNum); // channel 字段:videoChannel / cameraChannel / agoraChannel / rtcChannel / channel setCameraNum(Number.isFinite(n) && n >= 1 && n <= 4 ? n : 1); console.log('[DSP] deviceRunParam res.data=', res.data); } else { setCameraNum(1); } }).catch(() => { if (!cancelled) setCameraNum(1); }); return () => { cancelled = true; }; }, [device?.device_sn, device?.serialNumber, selectedSn, stationId]); // 视角按钮:按摄像头路数动态裁剪 const viewButtons = useMemo(() => { const all = [ { key: 'all', label: t('devices.panorama') }, { key: 'front', label: t('devices.frontView'), minCams: 1 }, { key: 'back', label: t('devices.backView'), minCams: 1 }, { key: 'left', label: t('devices.leftView'), minCams: 3 }, { key: 'right', label: t('devices.rightView'), minCams: 3 }, ]; const n = Number(cameraNum) || 1; return all.filter((b) => !b.minCams || n >= b.minCams); }, [cameraNum, t]); // cameraNum 变化时自动把非法视角回退到 front useEffect(() => { const n = Number(cameraNum) || 1; if (n <= 2 && (mowerView === 'left' || mowerView === 'right')) setMowerView('front'); }, [cameraNum, mowerView]); // 合并无人机和机场数据 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 = { '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 = { blade: null, chassis: null, power: null }; const [steerState, setSteerState] = useState>(EMPTY_STEER_STATE); const steerStateRef = useRef(steerState); steerStateRef.current = steerState; // 按锁存状态组装遥控帧:割刀统一走 button2(启动=true,停止/未点击=false) const buildSteerButtons = useCallback((s: Record) => { const buttons = new Array(17).fill(false); buttons[2] = s.blade === 'start'; // 割刀:button2 buttons[0] = s.chassis === 'up'; // 底盘升起 buttons[1] = s.chassis === 'down'; // 底盘下降 buttons[4] = s.power === 'ignition'; // 点火 buttons[5] = s.power === 'shutdown'; // 熄火 return buttons; }, []); const sendSteerState = useCallback((next: Record) => { steerStateRef.current = next; setSteerState(next); handleGamepadUpdate({ buttons: buildSteerButtons(next), axes: [0, 0, 0, 0], connected: true, ts: Date.now(), }); }, [buildSteerButtons, handleGamepadUpdate]); // 点击:未激活→激活;再次点击→取消;切换同组另一个按钮时自动互斥 const toggleSteerGroup = useCallback((group: SteerGroup, value: string) => { if (blockIfGamepadConnected()) return; const prev = steerStateRef.current; sendSteerState({ ...prev, [group]: prev[group] === value ? null : value } as Record); }, [blockIfGamepadConnected, sendSteerState]); // 锁存期间每 100ms 持续发送,保持"按住"语义 useEffect(() => { if (steerState.blade === null && steerState.chassis === null && steerState.power === null) return; const id = window.setInterval(() => { const cur = steerStateRef.current; if (cur.blade === null && cur.chassis === null && cur.power === null) return; handleGamepadUpdate({ buttons: buildSteerButtons(cur), axes: [0, 0, 0, 0], connected: true, ts: Date.now(), }); }, 200); return () => window.clearInterval(id); }, [steerState, buildSteerButtons, handleGamepadUpdate]); // 切换设备时清空锁存,避免残留 useEffect(() => { steerStateRef.current = EMPTY_STEER_STATE; setSteerState(EMPTY_STEER_STATE); }, [selectedSn]); const handleControlModal = useCallback(() => { console.log('请求控制权限'); controllerRef.current?.requestControl(); }, []); // 获得控制权限后,重置"已申请"标记,以便后续失去权限时可再次提示 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 ( ); } return (
机器人控制
{contextHolder}
{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')}
)}
); }