1835 lines
56 KiB
TypeScript
1835 lines
56 KiB
TypeScript
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,
|
||
} 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 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';
|
||
const { RangePicker } = DatePicker;
|
||
|
||
const { Text } = Typography;
|
||
|
||
|
||
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 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 [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 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;
|
||
}
|
||
|
||
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<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,
|
||
};
|
||
}
|
||
|
||
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]);
|
||
|
||
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 (
|
||
<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)' }}>{t('devices.deviceStatus')}</Typography.Title>
|
||
</div>
|
||
|
||
|
||
<div style={{ padding: 0 }}>
|
||
{contextHolder}
|
||
|
||
{/* 页面顶部按钮区域 */}
|
||
{!isUAV && (
|
||
<div
|
||
style={{
|
||
marginBottom: 8,
|
||
padding: '4px 0px',
|
||
background: '#f5f7fa',
|
||
borderRadius: 8,
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
justifyContent: 'space-between',
|
||
gap: 12,
|
||
}}
|
||
>
|
||
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
|
||
<Text strong>{t('devices.pathPlanning')}:</Text>
|
||
<Text type="secondary">{t('devices.markedPointsCount', { count: markedPoints?.length })}</Text>
|
||
</div>
|
||
<Space size="middle">
|
||
<Space>
|
||
<span>{t('devices.workMode')}</span>
|
||
<Switch
|
||
size="small"
|
||
checked={isLoopMode}
|
||
onChange={handleChange}
|
||
/>
|
||
<span>{isLoopMode ? t('devices.bowMode') : t('devices.abMode')}</span>
|
||
</Space>
|
||
<Button
|
||
type="primary"
|
||
onClick={handleMarkPoint}
|
||
disabled={!realtimePosition}
|
||
>
|
||
{t('devices.markPoint')}
|
||
</Button>
|
||
<Button
|
||
type="default"
|
||
onClick={handleUndoMark}
|
||
disabled={markedPoints?.length === 0}
|
||
>
|
||
{t('devices.undoMark')}
|
||
</Button>
|
||
<Button
|
||
type="default"
|
||
onClick={handleClearPoints}
|
||
>
|
||
{t('devices.clearMarks')}
|
||
</Button>
|
||
{/*<Button
|
||
type="primary"
|
||
ghost
|
||
onClick={handleComplete}
|
||
disabled={markedPoints?.length < 2}
|
||
>
|
||
{t('devices.complete')}
|
||
</Button>*/}
|
||
<Button
|
||
type="primary"
|
||
onClick={handleOpenSaveModal}
|
||
//disabled={!completeFlag}
|
||
>
|
||
{t('common.save')}
|
||
</Button>
|
||
</Space>
|
||
</div>
|
||
)}
|
||
|
||
<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') : t('devices.robot')}
|
||
</Tag>
|
||
|
||
<Tag color={device?.onlineStatus == 1 ? 'green' : 'default'}>
|
||
{device?.onlineStatus === 1 ? 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={<EnvironmentOutlined />}
|
||
onClick={handleFindCar}
|
||
>
|
||
{t('devices.features.findCar')}
|
||
</Button>
|
||
<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}
|
||
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>
|
||
) : (
|
||
// 机器人原布局
|
||
<Row gutter={[16, 16]} align="stretch">
|
||
<Col xs={24} lg={16}>
|
||
<Card className="ds-card"
|
||
title={
|
||
<>
|
||
<VideoCameraOutlined />
|
||
{t('devices.realtimeVideoMonitor')}
|
||
</>
|
||
}
|
||
variant="borderless"
|
||
style={{ borderRadius: 12, marginBottom: 8, height: '100%' }}
|
||
styles={{ body: { padding: 12, height: 'calc(100vh - 240px)', minHeight: 380, display: 'flex', flexDirection: 'column' } }}
|
||
|
||
extra={
|
||
<Button
|
||
size="small"
|
||
icon={isVideoPlaying ? <PauseOutlined /> : <PlayCircleOutlined />}
|
||
onClick={toggleVideoPlay}
|
||
>
|
||
{isVideoPlaying ? t('video.stop') : t('video.play')}
|
||
</Button>
|
||
}
|
||
>
|
||
<Space style={{ marginBottom: 8, flexShrink: 0 }} align="start" >
|
||
<Button type={mowerView === 'front' ? 'primary' : 'default'} onClick={() => setMowerView('front')}>{t('devices.frontView')}</Button>
|
||
<Button type={mowerView === 'back' ? 'primary' : 'default'} onClick={() => setMowerView('back')}>{t('devices.backView')}</Button>
|
||
<Button type={mowerView === 'left' ? 'primary' : 'default'} onClick={() => setMowerView('left')}>{t('devices.leftView')}</Button>
|
||
<Button type={mowerView === 'right' ? 'primary' : 'default'} onClick={() => setMowerView('right')}>{t('devices.rightView')}</Button>
|
||
<Button type={mowerView === 'all' ? 'primary' : 'default'} onClick={() => setMowerView('all')}>{t('devices.panorama')}</Button>
|
||
{mowerView == "all" ? <> <div style={{
|
||
|
||
background: 'rgba(0,0,0,0.7)',
|
||
color: '#fff',
|
||
padding: '10px 12px',
|
||
borderRadius: 8,
|
||
fontSize: 11,
|
||
zIndex: 10,
|
||
backdropFilter: 'blur(4px)'
|
||
}}>
|
||
<div style={{ marginBottom: 6, fontWeight: 600, color: '#1890ff' }}>{t('devices.robotStatus')}</div>
|
||
<div style={{ display: 'flex', gap: '3px 10px', flexWrap: 'wrap' }}>
|
||
<span>{t('devices.rtBattery')}</span>
|
||
<span style={{ color: ((runningStatus?.battery_percentage ?? runningStatus?.battery) || 0) < 20 ? '#ff4d4f' : '#52c41a' }}>
|
||
{(runningStatus?.battery_percentage ?? runningStatus?.battery) !== undefined
|
||
? `${runningStatus?.battery_percentage ?? runningStatus?.battery}%`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtVoltage')}</span>
|
||
<span>
|
||
{(runningStatus?.battery_voltage ?? runningStatus?.voltage) !== undefined
|
||
? `${Number(runningStatus?.battery_voltage ?? runningStatus?.voltage).toFixed(2)}V`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtLeftMotor')}</span>
|
||
<span>
|
||
{(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent) !== undefined
|
||
? `${Number(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent).toFixed(2)}A`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtRightMotor')}</span>
|
||
<span>
|
||
{(runningStatus?.right_motor_current ?? runningStatus?.rightCurrent) !== undefined
|
||
? `${Number(runningStatus?.right_motor_current ?? runningStatus?.rightCurrent).toFixed(2)}A`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtLeftSpeed')}</span>
|
||
<span>
|
||
{(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed) !== undefined
|
||
? `${Number(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed).toFixed(1)}rpm`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtRightSpeed')}</span>
|
||
<span>
|
||
{(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed) !== undefined
|
||
? `${Number(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed).toFixed(1)}rpm`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtLeftTemp')}</span>
|
||
<span>
|
||
{(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp) !== undefined
|
||
? formatTemperature(Number(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp), 1).label
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtRightTemp')}</span>
|
||
<span>
|
||
{(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp) !== undefined
|
||
? formatTemperature(Number(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp), 1).label
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtMainTemp')}</span>
|
||
<span>
|
||
{(runningStatus?.main_temperature ?? runningStatus?.chipTemp) !== undefined
|
||
? formatTemperature(Number(runningStatus?.main_temperature ?? runningStatus?.chipTemp), 1).label
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtHeadingAngle')}</span>
|
||
<span>
|
||
{runningStatus?.yaw !== undefined ? `${Number(runningStatus?.yaw).toFixed(1)}°` : '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtPitchAngle')}</span>
|
||
<span>
|
||
{runningStatus?.pitch !== undefined ? `${Number(runningStatus?.pitch).toFixed(1)}°` : '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtHeadingStatus')}</span>
|
||
<span>
|
||
{(runningStatus?.heading_status ?? runningStatus?.headingStatus) !== undefined
|
||
? (runningStatus?.heading_status ?? runningStatus?.headingStatus) === '1'
|
||
? t('devices.rtInitialized')
|
||
: t('devices.uninitialized')
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtPositioning')}</span>
|
||
<span>
|
||
{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')}
|
||
</span>
|
||
|
||
<span>{t('devices.rtSatellites')}</span>
|
||
<span>{t('devices.satelliteCount', { count: runningStatus?.satelliteCnt || 0 })}</span>
|
||
|
||
<span>{t('devices.rtMode')}</span>
|
||
<span>
|
||
{(runningStatus?.control_mode ?? runningStatus?.controlMode) !== undefined
|
||
? (runningStatus?.control_mode ?? runningStatus?.controlMode) === '1'
|
||
? t('devices.localMode')
|
||
: (runningStatus?.control_mode ?? runningStatus?.controlMode) === '3'
|
||
? t('devices.remoteMode')
|
||
: t('constants.locationUnknown')
|
||
: '-'}
|
||
</span>
|
||
</div>
|
||
|
||
</div>
|
||
</> : null}
|
||
</Space>
|
||
|
||
{/* 视频容器:剩余空间 */}
|
||
<div style={{ position: 'relative', flex: 1, minHeight: 0, borderRadius: 8, overflow: 'hidden', background: '#0a0e1a' }}>
|
||
{/* 视频层:停止时不渲染 / 未播放时为空,不影响状态面板 */}
|
||
{isVideoPlaying && (
|
||
mowerView === 'all' ? (
|
||
(
|
||
<div style={{ width: '100%', height: '100%' }}>
|
||
<MowerAllView
|
||
serialNumber={device?.serialNumber}
|
||
robotVideo={robotVideo}
|
||
error={error}
|
||
ready={ready}
|
||
/>
|
||
</div>
|
||
)
|
||
) : mowerView === 'front' ? (
|
||
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
|
||
{/*<AgrtcRoomRobot CHANNEL={device?.serialNumber || ''} />*/}
|
||
<AgrtcRoomRobot CHANNEL={"41-thream03"} />
|
||
<CarReverseGuideLine
|
||
direction="forward"
|
||
steer={steerXY.x * 45}
|
||
visible={isVideoPlaying}
|
||
/>
|
||
</div>
|
||
) : (
|
||
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
|
||
<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}
|
||
visible={isVideoPlaying}
|
||
/>
|
||
)}
|
||
</div>
|
||
)
|
||
)}
|
||
|
||
{!isVideoPlaying && (
|
||
<div style={{
|
||
width: '100%', height: '100%',
|
||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||
flexDirection: 'column', gap: 12,
|
||
color: 'rgba(14, 78, 198, 0.35)',
|
||
}}>
|
||
<VideoCameraOutlined style={{ fontSize: 56, opacity: 0.6 }} />
|
||
<div style={{ fontSize: 15 }}>
|
||
{!isVideoPlaying ? t('devices.videoStopped') : t('video.videoLoading')}
|
||
</div>
|
||
<div style={{ fontSize: 12, opacity: 0.7 }}>
|
||
{!isVideoPlaying ? t('devices.clickPlayHint') : ''}
|
||
</div>
|
||
</div>
|
||
)}
|
||
{/* 单视频(非全景)模式状态叠加层:始终渲染,和视频层解耦 */}
|
||
{mowerView !== 'all' && (
|
||
<div style={{
|
||
position: 'absolute',
|
||
top: 8,
|
||
left: 8,
|
||
background: 'rgba(0,0,0,0.7)',
|
||
color: '#fff',
|
||
padding: '10px 12px',
|
||
borderRadius: 8,
|
||
fontSize: 11,
|
||
zIndex: 10,
|
||
backdropFilter: 'blur(4px)',
|
||
boxShadow: '0 4px 16px rgba(0,0,0,0.4)',
|
||
border: '1px solid rgba(24,144,255,0.2)',
|
||
}}>
|
||
<div style={{ marginBottom: 6, fontWeight: 600, color: '#1890ff' }}>{t('devices.robotStatus')}</div>
|
||
<div style={{ display: 'grid', gridTemplateColumns: 'auto auto', gap: '3px 10px' }}>
|
||
<span>{t('devices.rtBattery')}</span>
|
||
<span style={{ color: ((runningStatus?.battery_percentage ?? runningStatus?.battery) || 0) < 20 ? '#ff4d4f' : '#52c41a' }}>
|
||
{(runningStatus?.battery_percentage ?? runningStatus?.battery) !== undefined
|
||
? `${runningStatus?.battery_percentage ?? runningStatus?.battery}%`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtVoltage')}</span>
|
||
<span>
|
||
{(runningStatus?.battery_voltage ?? runningStatus?.voltage) !== undefined
|
||
? `${Number(runningStatus?.battery_voltage ?? runningStatus?.voltage).toFixed(2)}V`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtLeftMotor')}</span>
|
||
<span>
|
||
{(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent) !== undefined
|
||
? `${Number(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent).toFixed(2)}A`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtRightMotor')}</span>
|
||
<span>
|
||
{(runningStatus?.right_motor_current ?? runningStatus?.rightCurrent) !== undefined
|
||
? `${Number(runningStatus?.right_motor_current ?? runningStatus?.rightCurrent).toFixed(2)}A`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtLeftSpeed')}</span>
|
||
<span>
|
||
{(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed) !== undefined
|
||
? `${Number(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed).toFixed(1)}rpm`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtRightSpeed')}</span>
|
||
<span>
|
||
{(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed) !== undefined
|
||
? `${Number(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed).toFixed(1)}rpm`
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtLeftTemp')}</span>
|
||
<span>
|
||
{(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp) !== undefined
|
||
? formatTemperature(Number(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp), 1).label
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtRightTemp')}</span>
|
||
<span>
|
||
{(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp) !== undefined
|
||
? formatTemperature(Number(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp), 1).label
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtMainTemp')}</span>
|
||
<span>
|
||
{(runningStatus?.main_temperature ?? runningStatus?.chipTemp) !== undefined
|
||
? formatTemperature(Number(runningStatus?.main_temperature ?? runningStatus?.chipTemp), 1).label
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtHeadingAngle')}</span>
|
||
<span>
|
||
{runningStatus?.yaw !== undefined ? `${Number(runningStatus?.yaw).toFixed(1)}°` : '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtPitchAngle')}</span>
|
||
<span>
|
||
{runningStatus?.pitch !== undefined ? `${Number(runningStatus?.pitch).toFixed(1)}°` : '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtHeadingStatus')}</span>
|
||
<span>
|
||
{(runningStatus?.heading_status ?? runningStatus?.headingStatus) !== undefined
|
||
? (runningStatus?.heading_status ?? runningStatus?.headingStatus) === '1'
|
||
? t('devices.rtInitialized')
|
||
: t('devices.uninitialized')
|
||
: '-'}
|
||
</span>
|
||
|
||
<span>{t('devices.rtPositioning')}</span>
|
||
<span>
|
||
{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')}
|
||
</span>
|
||
|
||
<span>{t('devices.rtSatellites')}</span>
|
||
<span>{t('devices.satelliteCount', { count: runningStatus?.satelliteCnt || 0 })}</span>
|
||
|
||
<span>{t('devices.rtMode')}</span>
|
||
<span>
|
||
{(runningStatus?.control_mode ?? runningStatus?.controlMode) !== undefined
|
||
? (runningStatus?.control_mode ?? runningStatus?.controlMode) === '1'
|
||
? t('devices.localMode')
|
||
: (runningStatus?.control_mode ?? runningStatus?.controlMode) === '3'
|
||
? t('devices.remoteMode')
|
||
: t('constants.locationUnknown')
|
||
: '-'}
|
||
</span>
|
||
</div>
|
||
</div>
|
||
|
||
)
|
||
}
|
||
</div>
|
||
</Card>
|
||
</Col>
|
||
|
||
{/* 右边 - 地图 + 控制手柄方向盘 + 功能按钮 三个面板,高度与左侧视频对齐 */}
|
||
<Col xs={24} lg={8}>
|
||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, height: 'calc(100vh - 240px)', minHeight: 380 }}>
|
||
{/* 地图 */}
|
||
<Card
|
||
title={
|
||
<>
|
||
<GlobalOutlined />
|
||
{t('devices.situationMap')}
|
||
</>
|
||
}
|
||
extra={
|
||
<Space size={4}>
|
||
<Button
|
||
size="small"
|
||
type="primary"
|
||
icon={<EnvironmentOutlined />}
|
||
onClick={handleFindCar}
|
||
>
|
||
{t('devices.features.findCar')}
|
||
</Button>
|
||
<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"
|
||
className="ds-card"
|
||
style={{ borderRadius: 12, flex: 1, minHeight: 0 }}
|
||
styles={{ body: { padding: 12, height: 'calc(100% - 57px)' } }}
|
||
>
|
||
<CesiumMap
|
||
ref={mapRef}
|
||
devices={[mapDevices]}
|
||
points={points}
|
||
markedPoints={markedPoints}
|
||
realtimePosition={realtimePosition}
|
||
realtimeType={realtimeType}
|
||
drawRealTime={true}
|
||
finishPoint={arrivedPoint}
|
||
ifClearNavLine={clearNavLine}
|
||
ifClearPlanLine={clearPlanLine}
|
||
from="deviceStatus" onMarkPoint={handleMapMarkPoint} onClearDraw={(fn) => { clearDrawRef.current = fn; }}
|
||
/>
|
||
</Card>
|
||
|
||
{/* 手柄 + 方向盘 一个面板 */}
|
||
<Card
|
||
title={
|
||
<>
|
||
<ControlOutlined />
|
||
{t('devices.remoteControl')}
|
||
</>
|
||
}
|
||
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>
|
||
}
|
||
variant="borderless"
|
||
className="ds-card"
|
||
style={{ borderRadius: 12, background: '#0f172a', flex: 1, minHeight: 0, position: 'relative' }}
|
||
styles={{
|
||
header: { color: '#fff' },
|
||
body: {
|
||
padding: 12,
|
||
display: 'flex',
|
||
flexDirection: 'row',
|
||
flexWrap: 'wrap',
|
||
gap: 12,
|
||
height: 'calc(100% - 57px)',
|
||
overflow: 'auto',
|
||
alignItems: 'center',
|
||
justifyContent: 'center',
|
||
},
|
||
}}
|
||
>
|
||
|
||
|
||
{/* Xbox 手柄 - 左侧,缩小显示 */}
|
||
<div
|
||
style={{
|
||
display: 'flex',
|
||
alignItems: 'center',
|
||
justifyContent: 'center',
|
||
flex: '0 0 auto',
|
||
minWidth: 320,
|
||
transform: 'scale(0.82)',
|
||
transformOrigin: 'left center',
|
||
}}
|
||
>
|
||
<XboxController
|
||
onGamepadUpdate={handleGamepadUpdate}
|
||
/>
|
||
</div>
|
||
|
||
{/* 方向盘 + 滑块 - 右侧 */}
|
||
<div
|
||
style={{
|
||
flex: '1 1 auto',
|
||
display: 'flex',
|
||
flexDirection: 'column',
|
||
justifyContent: 'center',
|
||
alignItems: 'center',
|
||
}}
|
||
>
|
||
<DPadControl
|
||
onGamepadUpdate={(state) => {
|
||
handleGamepadUpdate(state);
|
||
}}
|
||
onSpeedChange={(speed) => {
|
||
//console.log(`[DeviceStatusPage] Speed slider: ${Math.round(speed * 100)}%`);
|
||
}}
|
||
/>
|
||
</div>
|
||
</Card>
|
||
|
||
|
||
{/* 功能按钮 单独一个面板 */}
|
||
<Card
|
||
title={
|
||
<>
|
||
<SafetyOutlined style={{ color: '#fa541c' }} />
|
||
{t('devices.features.title')}
|
||
</>
|
||
}
|
||
variant="borderless"
|
||
style={{ borderRadius: 12, flex: '0 0 auto' }}
|
||
styles={{
|
||
header: { color: '#fff' },
|
||
body: { padding: 12 },
|
||
}}
|
||
>
|
||
<RobotFeatureButtons
|
||
activeFeatures={['response', 'obstacleAvoidance', 'lowBatteryReturn', 'tiltProtection']}
|
||
onToggle={(feature, enabled) => {
|
||
console.log(`[DeviceStatusPage] Feature toggled: ${feature} = ${enabled}`);
|
||
}}
|
||
/>
|
||
</Card>
|
||
</div>
|
||
</Col>
|
||
</Row>
|
||
)}
|
||
|
||
<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 >
|
||
);
|
||
}
|