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

1410 lines
40 KiB
TypeScript
Raw Normal View History

2026-05-20 15:12:51 +08:00
import React, {
useState,
useEffect,
useMemo,
useRef,
useCallback,
} from 'react';
2026-05-11 16:34:44 +08:00
import {
2026-05-20 15:12:51 +08:00
Row,
Col,
Card,
Tag,
Typography,
Space,
Empty,
Descriptions,
Badge,
Progress,
Button,
Select,
message,
Modal,
2026-06-24 15:47:52 +08:00
Switch,
2026-05-11 16:34:44 +08:00
} from 'antd';
2026-05-20 15:12:51 +08:00
2026-05-11 16:34:44 +08:00
import {
2026-05-20 15:12:51 +08:00
DashboardOutlined,
GlobalOutlined,
VideoCameraOutlined,
ControlOutlined,
CameraOutlined,
ThunderboltOutlined,
EnvironmentOutlined,
DeleteOutlined,
2026-05-11 16:34:44 +08:00
} from '@ant-design/icons';
2026-05-20 15:12:51 +08:00
2026-05-27 15:08:26 +08:00
import {
getsinglePlan,
2026-05-27 15:08:26 +08:00
getsinglePlanTrack,
getFlightTaskDetail,
getUAVState,
getSiteDevice,
getSiteUAVList,
addRoute,
2026-05-27 15:08:26 +08:00
} from '../../api/device.ts';
2026-08-04 16:11:27 +08:00
import { useLocation } from 'react-router-dom';
2026-05-27 15:08:26 +08:00
2026-05-11 16:34:44 +08:00
import XboxController from './XboxController';
2026-05-25 10:30:20 +08:00
import DroneVideoPlayer from './DroneVideoPlayer';
2026-05-12 08:34:13 +08:00
import CesiumMap from '../Map.jsx';
2026-05-12 10:34:50 +08:00
import { useSelector } from 'react-redux';
import { RootState } from '@/src/store/index.ts';
import { useWebRTCPlayer } from '../useWebRTCStream.tsx';
import VideoPlayer from '../VideoPlayer.tsx';
2026-05-20 15:12:51 +08:00
import DeviceController from './DeviceController';
2026-05-22 08:03:30 +08:00
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';
2026-08-06 13:39:14 +08:00
import { PauseOutlined, PlayCircleOutlined } from '@ant-design/icons';
2026-08-12 11:29:44 +08:00
import { useTranslation } from 'react-i18next';
2026-05-22 08:03:30 +08:00
const { RangePicker } = DatePicker;
2026-05-12 11:11:30 +08:00
2026-05-12 10:34:50 +08:00
const { Text } = Typography;
export default function DeviceStatusPage() {
2026-08-12 11:29:44 +08:00
const { t } = useTranslation();
2026-05-20 15:12:51 +08:00
const { userInfo } = useSelector((state: RootState) => state.user);
2026-08-04 16:33:52 +08:00
const { stationId, currentStation } = useSelector((state: RootState) => state.station);
2026-06-01 15:44:02 +08:00
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);//完成点
2026-06-24 15:47:52 +08:00
const [isLoopMode, setIsLoopMode] = useState(true);
2026-07-07 16:06:40 +08:00
const controllerRef = useRef<DeviceController | null>(null);
const [messageApi, contextHolder] = message.useMessage();
2026-08-06 13:39:14 +08:00
// 视频播放开关
const [isVideoPlaying, setIsVideoPlaying] = useState(false);
const toggleVideoPlay = useCallback(() => {
setIsVideoPlaying(prev => !prev);
}, []);
2026-07-07 16:06:40 +08:00
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 [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 [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); // 地图 ref
2026-08-04 16:11:27 +08:00
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const urlSn = queryParams.get('sn'); // 拿到路由上的sn
2026-06-24 15:47:52 +08:00
// 开关切换回调
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([
2026-08-04 16:33:52 +08:00
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
2026-08-12 11:29:44 +08:00
|| 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) {
2026-08-04 16:11:27 +08:00
// 优先从url参数匹配设备
if (urlSn) {
const target = devicesAll.find(d =>
(d.device_sn || d.serialNumber) === urlSn
);
if (target) {
setSelectedSn(urlSn);
2026-08-06 13:39:14 +08:00
setIsVideoPlaying(false);
2026-08-04 16:11:27 +08:00
return;
}
}
// url无sn / 没匹配到对应设备:默认选中第一个
const firstDevice = devicesAll[0];
setSelectedSn(firstDevice.device_sn || firstDevice.serialNumber);
2026-08-06 13:39:14 +08:00
setIsVideoPlaying(false);
}
2026-08-04 16:11:27 +08:00
}, [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]);
2026-06-01 15:44:02 +08:00
// 设备选择变化时,调用回调并更新内部状态
const handleDeviceSelectChange = (val) => {
setSelectedSn(val);
// 切换设备时清空之前的标记点等
setMarkedPoints([]);
setCompleteFlag(false);
setSavePath(null);
};
2026-06-01 15:44:02 +08:00
// 当MQTT数据更新时,更新持久化数据(只在有新数据时更新)
const handleMqttMessage = (topic, message) => {
2026-06-02 10:08:23 +08:00
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`);
2026-06-01 15:44:02 +08:00
}
return topics;
}, [isUAV, device]);
// 订阅MQTT消息
useMqtt({
url: envConfig.mqtt_url,
topic: mqttTopics,
onMessage: handleMqttMessage,
});
2026-06-01 15:44:02 +08:00
// 合并无人机和机场数据
2026-06-01 15:44:02 +08:00
const currentDroneData = React.useMemo(() => {
return { ...persistentHostData, ...persistentDroneData };
}, [persistentDroneData, persistentHostData]);
// 实时位置数据(用于地图)
2026-05-20 15:12:51 +08:00
2026-05-12 10:34:50 +08:00
const runningStatus = useMemo(() => {
// 判断对象是否为空
if ((!wsDeviceInfo || Object.keys(wsDeviceInfo).length === 0) && !isUAV) {
return {};
}
if (isUAV) {
return {
...wsDeviceInfo,
};
}
2026-05-20 15:12:51 +08:00
const base = device?.lastRunningStatus || {};
return isUAV
? base
: {
...base,
...wsDeviceInfo,
2026-05-12 10:34:50 +08:00
};
}, [device, wsDeviceInfo, isUAV]);
2026-05-11 16:34:44 +08:00
2026-05-20 15:12:51 +08:00
const { video: robotVideo, error, ready } = useWebRTCPlayer(
2026-08-06 13:39:14 +08:00
(!isUAV && isVideoPlaying) ? (device?.serialNumber || '') : '',
(!isUAV && isVideoPlaying)
? `webrtc://1.95.137.212/live/livestream/${device?.serialNumber}`
: ''
2026-05-20 15:12:51 +08:00
);
2026-08-06 13:39:14 +08:00
//const { video: robotVideo, error, ready } = useWebRTCPlayer(
// !isUAV ? device?.serialNumber : '',
// `webrtc://1.95.137.212/live/livestream/${device?.serialNumber}`,
//);
2026-05-11 16:34:44 +08:00
const getVal = (val) => val === "no_rain" ? "无" : (val || '-');
const realtimePosition = React.useMemo(() => {
// 1. 无人机:优先用 MQTT 实时数据
if (isUAV) {
if (currentDroneData?.longitude && currentDroneData?.latitude) {
return {
lon: currentDroneData.longitude,
lat: currentDroneData.latitude,
heading: currentDroneData.heading || 0,
};
}
return null;
}
// 2. 机器人:从 wsDeviceInfo / runningStatus 取实时经纬度
const robotLon = runningStatus.longitude || wsDeviceInfo.longitude;
const robotLat = runningStatus.latitude || wsDeviceInfo.latitude;
if (robotLon && robotLat) {
return {
lon: robotLon,
lat: robotLat,
//heading: -98
2026-07-07 16:06:40 +08:00
heading: runningStatus.yaw || wsDeviceInfo.yaw || 0,
};
}
return null;
}, [isUAV, currentDroneData, runningStatus, wsDeviceInfo]);
2026-05-12 10:34:50 +08:00
2026-05-20 15:12:51 +08:00
useEffect(() => {
const controller = new DeviceController(userInfo, messageApi);
controller.onDeviceInfoUpdate = setWsDeviceInfo;
controller.onControlStatusChange = setIsControlled;
controller.onHasControlRightChange = setHasControlRight;
controller.onRequestControlStatusChange = setConnecting;
controller.onWsStatusChange = setWsStatus;
controller.handleArrivedPoint = handleFinishEdPoint;
2026-05-12 10:34:50 +08:00
2026-05-20 15:12:51 +08:00
controller.onPermissionRequest = (content) => {
setModalContent(content);
setIsModalOpen(true);
2026-05-12 10:34:50 +08:00
};
2026-05-20 15:12:51 +08:00
controller.init();
2026-05-12 10:34:50 +08:00
2026-05-20 15:12:51 +08:00
controllerRef.current = controller;
2026-05-12 10:34:50 +08:00
2026-05-20 15:12:51 +08:00
return () => {
controller?.destroy();
controllerRef.current?.destroy();
2026-05-20 15:12:51 +08:00
controllerRef.current = null;
2026-06-04 15:39:46 +08:00
2026-05-20 15:12:51 +08:00
};
2026-06-04 15:39:46 +08:00
}, []);
2026-05-12 10:34:50 +08:00
useEffect(() => {
2026-07-07 16:06:40 +08:00
if (!device || !controllerRef.current || !device?.serialNumber || isUAV) {
//controllerRef.current?.destroy();
//setWsDeviceInfo({});
return;
}
setWsDeviceInfo({});
2026-05-12 10:34:50 +08:00
2026-05-20 15:12:51 +08:00
controllerRef.current.connectDevice(device);
}, [device?.serialNumber]);
2026-05-12 10:34:50 +08:00
2026-05-27 15:08:26 +08:00
// 定时获取无人机状态
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);
}
};
2026-06-01 15:44:02 +08:00
fetchUavState();
}, [isUAV, device]);
2026-05-27 15:08:26 +08:00
// 获取执行中任务的轨迹
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([]);
}
};
2026-05-27 15:08:26 +08:00
fetchExecutingTaskTrack();
2026-05-27 15:08:26 +08:00
}, [isUAV, device]);
2026-05-12 08:48:33 +08:00
const mapDevices = useMemo(() => {
if (!device) return null;
2026-06-01 15:44:02 +08:00
// 优先使用持久化MQTT数据,其次使用uavState
const lng = currentDroneData?.longitude ?? uavState?.longitude ?? runningStatus.longitude ?? device.longitude;
const lat = currentDroneData?.latitude ?? uavState?.latitude ?? runningStatus.latitude ?? device.latitude;
2026-05-20 15:12:51 +08:00
return {
2026-05-12 08:48:33 +08:00
...device,
lastRunningStatus: {
...device.lastRunningStatus,
longitude: lng,
latitude: lat,
2026-05-12 08:48:33 +08:00
},
// 让地图取最新经纬度
longitude: lng,
latitude: lat,
name: device.deviceAlias || device.callsign || device.deviceName || '设备',
2026-05-20 15:12:51 +08:00
type: isUAV
? 'drone'
2026-08-12 11:29:44 +08:00
: device.productName?.includes(t('constants.mower'))
2026-05-20 15:12:51 +08:00
? 'mower'
: 'robot',
2026-05-12 08:48:33 +08:00
};
2026-06-01 15:44:02 +08:00
}, [device, isUAV, runningStatus, uavState, currentDroneData]);
const realtimeDevice = useMemo(() => {
if (!device) return null;
return {
...device,
2026-06-01 15:44:02 +08:00
...uavState,
...currentDroneData, // 持久化数据最后覆盖,确保优先显示
};
2026-06-01 15:44:02 +08:00
}, [device, uavState, currentDroneData]);
2026-05-12 10:34:50 +08:00
2026-05-20 15:12:51 +08:00
const handleGamepadUpdate = useCallback((state) => {
controllerRef.current?.sendGamepad(state);
}, []);
const handleControlModal = useCallback(() => {
controllerRef.current?.requestControl();
}, []);
const handleOk = () => {
controllerRef.current?.sendPermissionRequest(
true,
'switchResult',
);
setIsControlled(false);
2026-05-20 15:12:51 +08:00
setIsModalOpen(false);
};
const handleCancel = () => {
2026-05-20 15:12:51 +08:00
controllerRef.current?.sendPermissionRequest(
false,
'switchResult',
);
setIsControlled(true);
2026-05-20 15:12:51 +08:00
setIsModalOpen(false);
};
const fix2 = (val) => {
if (val === null || val === undefined || isNaN(val)) {
return '-';
}
return Number(val).toFixed(2);
};
// 打点功能
const handleMarkPoint = () => {
if (!realtimePosition) {
message.warning('无法获取实时位置,请检查设备连接');
return;
}
const newPoint = {
lon: Number(realtimePosition.lon),
lat: Number(realtimePosition.lat),
};
setMarkedPoints([...markedPoints, newPoint]);
messageApi.success(`已标记第 ${markedPoints.length + 1} 个点`);
};
// 清空标记点
const handleClearPoints = () => {
setMarkedPoints([]);
setCompleteFlag(false);
setSavePath(null);
};
// 完成功能 - 调用路径规划接口
const handleComplete = async () => {
2026-06-24 15:47:52 +08:00
//如果时弓子模式
if (isLoopMode) {
if (markedPoints.length < 3) {
messageApi.warning('请至少标记 3 个点');
return;
}
2026-06-24 15:47:52 +08:00
try {
// 准备路径规划请求参数
const positionPoints = [...markedPoints];
const requestParams = {
reference: {
lat: positionPoints[0].lat,
lon: positionPoints[0].lon,
},
heading: 0,
outer: {
position: positionPoints.map(point => ({
lat: point.lat,
lon: point.lon,
})),
sideWidth: 0.0,
},
holes: [],
workType: 0,
};
2026-06-24 15:47:52 +08:00
const response = await fetch('https://servicepathplan.satabot.com/api/path', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestParams),
});
2026-06-24 15:47:52 +08:00
const result = await response.json();
2026-06-24 15:47:52 +08:00
if (result) {
const path = result?.data?.path?.map(p => {
return {
lng: p.lon,
lat: p.lat
}
2026-06-24 15:47:52 +08:00
})
setPoints(path);
setSavePath({
path: path, // 存储返回的路径结果
outer: requestParams?.outer?.position?.map(p => {
return {
lng: p.lon,
lat: p.lat
}
}
),
planModel: 0,
});
setCompleteFlag(true);
messageApi.success('路径规划完成');
}
} catch (error) {
console.error('路径规划失败:', error);
messageApi.error('路径规划失败,请重试');
}
2026-06-24 15:47:52 +08:00
} else {
const positionPoints = [...markedPoints].map(item => {
return {
lng: item.lon,
lat: item.lat
}
});
setPoints(positionPoints);
setSavePath({
path: positionPoints, // 存储返回的路径结果
outer: [],
planModel: 2,
});
setCompleteFlag(true);
}
2026-06-24 15:47:52 +08:00
};
// 打开保存模态框
const handleOpenSaveModal = () => {
if (!completeFlag) {
messageApi.warning('请先点击完成生成路径');
return;
}
setPlotName('');
setIsSaveModalVisible(true);
};
// 保存功能
const handleSave = async () => {
if (!plotName.trim()) {
messageApi.warning('请输入地块名称');
return;
}
setIsSaving(true);
try {
// 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
const workRecord = {
workName: plotName,
siteId: stationId,
jsonData: savePath,
};
formData.append(
"workRecord",
new Blob([JSON.stringify(workRecord)], {
type: "application/json"
})
);
//formData.append('workRecord', JSON.stringify(workRecord));
// 5. 调用保存接口
const res = await addRoute(formData);
if (res.code === 200) {
2026-08-12 11:29:44 +08:00
messageApi.success(t('common.saveSuccess'));
setIsSaveModalVisible(false);
// 重置状态
setMarkedPoints([]);
setCompleteFlag(false);
setSavePath(null);
} else {
2026-08-12 11:29:44 +08:00
messageApi.error(res.msg || t('common.saveFail'));
}
} catch (error) {
console.error('保存失败:', error);
2026-08-12 11:29:44 +08:00
messageApi.error(t('common.saveFail'));
} finally {
setIsSaving(false);
}
};
const realtimeType = useMemo(() => {
return isUAV ? 'plane' : 'car';
}, [isUAV]);
2026-05-12 10:34:50 +08:00
if (!device) {
2026-05-20 15:12:51 +08:00
return (
<Empty
description="请选择设备"
style={{ marginTop: 100 }}
/>
);
2026-05-12 10:34:50 +08:00
}
2026-05-12 08:48:33 +08:00
2026-05-11 16:34:44 +08:00
return (
2026-08-03 14:38:28 +08:00
<div style={{ background: '#f5f7fa', minHeight: '100%', padding: 0 }}>
<div style={{ padding: '4px 0px 8px' }}>
2026-08-12 11:29:44 +08:00
<Typography.Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.2vw, 18px)' }}>{t('devices.deviceStatus')}</Typography.Title>
2026-08-03 14:38:28 +08:00
</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>路径规划:</Text>
<Text type="secondary">已标记 {markedPoints.length} 个点</Text>
</div>
<Space size="middle">
<Space>
<span>作业方式</span>
<Switch
size="small"
checked={isLoopMode}
onChange={handleChange}
/>
<span>{isLoopMode ? '弓字' : 'AB点'}</span>
</Space>
<Button
type="primary"
onClick={handleMarkPoint}
disabled={!realtimePosition}
>
打点
</Button>
<Button
type="default"
onClick={handleClearPoints}
>
清空标记
</Button>
<Button
type="primary"
ghost
onClick={handleComplete}
disabled={markedPoints.length < 2}
>
完成
</Button>
<Button
type="primary"
onClick={handleOpenSaveModal}
disabled={!completeFlag}
>
保存
</Button>
</Space>
</div>
)}
2026-05-20 15:12:51 +08:00
<div
style={{
2026-06-17 11:14:14 +08:00
marginBottom: 8,
display: 'flex',
alignItems: 'center',
gap: 12,
flexWrap: 'wrap',
}}
>
2026-08-03 14:38:28 +08:00
<Text strong>选择设备:</Text>
<Select
style={{ width: 380, minWidth: 280 }}
value={selectedSn}
onChange={handleDeviceSelectChange}
2026-08-03 14:38:28 +08:00
showSearch
optionFilterProp="label"
placeholder="请选择设备"
allowClear={false}
loading={devicesAll.length === 0}
2026-08-03 14:38:28 +08:00
options={[
{
2026-08-12 11:29:44 +08:00
label: t('devices.robot'),
title: 'robot',
options: devicesAll.filter(item => !item.gateway_sn && !item.drone_callsign && item.serialNumber).map(item => ({
2026-08-03 14:38:28 +08:00
value: item.device_sn || item.serialNumber,
label: `${item.deviceAlias || item.deviceName || '未知设备'} `,
2026-08-03 14:38:28 +08:00
})),
},
{
2026-08-12 11:29:44 +08:00
label: t('constants.uav'),
title: 'uav',
options: devicesAll.filter(item => item.gateway_sn || item.drone_callsign).map(item => ({
2026-08-03 14:38:28 +08:00
value: item.device_sn,
label: `${item.drone_callsign || item.callsign || '未知无人机'}`,
2026-08-03 14:38:28 +08:00
})),
},
].filter(group => group.options.length > 0)}
2026-08-03 14:38:28 +08:00
/>
2026-05-20 15:12:51 +08:00
<Tag color={isUAV ? 'cyan' : 'blue'}>
2026-08-12 11:29:44 +08:00
{isUAV ? t('constants.uav') : t('devices.robot')}
2026-08-03 14:38:28 +08:00
</Tag>
2026-05-21 17:04:21 +08:00
<Tag color={device?.onlineStatus == 1 ? 'green' : 'default'}>
2026-08-12 11:29:44 +08:00
{device?.onlineStatus === 1 ? t('devices.online') : t('devices.offline')}
</Tag>
2026-05-11 16:34:44 +08:00
2026-08-03 14:38:28 +08:00
</div>
{/* 无人机专用布局 */}
{isUAV ? (
<Row gutter={[16, 16]} align="stretch">
{/* 左侧:机场视频 + 地图 */}
<Col xs={24} lg={8}>
{/* 无人机场视频 + 机场状态 */}
<Card
title={
<>
<VideoCameraOutlined />
无人机场视频
</>
}
bordered={false}
style={{ borderRadius: 12, marginBottom: 8 }}
bodyStyle={{ 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
title={
<>
<GlobalOutlined />
位置态势图
</>
}
extra={
<Space size={4}>
<Button
size="small"
type="primary"
icon={<DeleteOutlined />}
onClick={() => setClearNavLine((v) => v + 1)}
>
清空实时轨迹
</Button>
<Button
size="small"
danger
icon={<DeleteOutlined />}
onClick={() => {
setPoints([]);
setClearPlanLine((v) => v + 1);
}}
>
清空规划航线
</Button>
</Space>
}
bordered={false}
style={{ borderRadius: 12 }}
bodyStyle={{ padding: 12, height: 400 }}
>
<CesiumMap
ref={mapRef}
devices={[mapDevices]}
points={points}
markedPoints={markedPoints}
realtimePosition={realtimePosition}
realtimeType={realtimeType}
drawRealTime={true}
finishPoint={arrivedPoint}
ifClearNavLine={clearNavLine}
ifClearPlanLine={clearPlanLine}
from="deviceStatus"
/>
2026-08-03 14:38:28 +08:00
</Card>
</Col>
{/* 右侧:无人机视频 + 无人机状态 */}
<Col xs={24} lg={16}>
{/* 无人机视频 + 无人机状态 */}
<Card
title={
<>
<VideoCameraOutlined />
无人机视频
</>
}
bordered={false}
style={{ borderRadius: 12, marginBottom: 8 }}
bodyStyle={{ 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
title={
<>
<VideoCameraOutlined />
实时视频监控
</>
}
bordered={false}
style={{ borderRadius: 12, marginBottom: 8 }}
bodyStyle={{ padding: 12, height: 'calc(100vh - 220px)', minHeight: 500 }}
2026-08-06 13:39:14 +08:00
extra={
<Button
size="small"
icon={isVideoPlaying ? <PauseOutlined /> : <PlayCircleOutlined />}
onClick={toggleVideoPlay}
>
2026-08-12 11:29:44 +08:00
{isVideoPlaying ? t('video.stop') : t('video.play')}
2026-08-06 13:39:14 +08:00
</Button>
}
2026-08-03 14:38:28 +08:00
>
<Space style={{ marginBottom: 8, }} align="start" >
<Button type={mowerView === 'front' ? 'primary' : 'default'} onClick={() => setMowerView('front')}>前视</Button>
<Button type={mowerView === 'back' ? 'primary' : 'default'} onClick={() => setMowerView('back')}>后视</Button>
<Button type={mowerView === 'left' ? 'primary' : 'default'} onClick={() => setMowerView('left')}>左视</Button>
<Button type={mowerView === 'right' ? 'primary' : 'default'} onClick={() => setMowerView('right')}>右视</Button>
<Button type={mowerView === 'all' ? 'primary' : 'default'} onClick={() => setMowerView('all')}>全景</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' }}>机器人状态</div>
<div style={{ display: 'flex', gap: '3px 10px', flexWrap: 'wrap' }}>
<span>电量:</span>
<span style={{ color: (runningStatus.battery || 0) < 20 ? '#ff4d4f' : '#52c41a' }}>
{runningStatus.battery !== undefined ? `${runningStatus.battery}%` : '-'}
</span>
<span>电压:</span>
<span>{runningStatus.voltage !== undefined ? `${Number(runningStatus.voltage).toFixed(2)}V` : '-'}</span>
<span>左电机:</span>
<span>{runningStatus.leftCurrent !== undefined ? `${Number(runningStatus.leftCurrent).toFixed(2)}A` : '-'}</span>
<span>右电机:</span>
<span>{runningStatus.rightCurrent !== undefined ? `${Number(runningStatus.rightCurrent).toFixed(2)}A` : '-'}</span>
<span>左速度:</span>
<span>{runningStatus.leftMeasureSpeed !== undefined ? `${Number(runningStatus.leftMeasureSpeed).toFixed(1)}rpm` : '-'}</span>
<span>右速度:</span>
<span>{runningStatus.rightMeasureSpeed !== undefined ? `${Number(runningStatus.rightMeasureSpeed).toFixed(1)}rpm` : '-'}</span>
<span>左温度:</span>
<span>{runningStatus.leftMotorTemp !== undefined ? `${Number(runningStatus.leftMotorTemp).toFixed(1)}℃` : '-'}</span>
<span>右温度:</span>
<span>{runningStatus.rightMotorTemp !== undefined ? `${Number(runningStatus.rightMotorTemp).toFixed(1)}℃` : '-'}</span>
<span>主控温度:</span>
<span>{runningStatus.chipTemp !== undefined ? `${Number(runningStatus.chipTemp).toFixed(1)}℃` : '-'}</span>
<span>航向角:</span>
<span>{runningStatus.yaw !== undefined ? `${Number(runningStatus.yaw).toFixed(1)}°` : '-'}</span>
<span>俯仰角:</span>
<span>{runningStatus.pitch !== undefined ? `${Number(runningStatus.pitch).toFixed(1)}°` : '-'}</span>
<span>航向角状态:</span>
<span>{runningStatus.headingStatus !== undefined ? `${runningStatus.headingStatus == 1 ? '初始化' : '未初始化'}` : '-'}</span>
<span>定位:</span>
<span>
2026-08-12 11:29:44 +08:00
{runningStatus.qual == 0 ? t('constants.locationInvalid') :
2026-08-03 14:38:28 +08:00
runningStatus.qual == 1 ? 'GPS单点' :
runningStatus.qual == 2 ? 'DGPS差分' :
runningStatus.qual == 4 ? 'RTK固定' :
2026-08-12 11:29:44 +08:00
runningStatus.qual == 5 ? 'RTK浮点' : t('constants.locationUnknown')}
2026-08-03 14:38:28 +08:00
</span>
<span>卫星:</span>
<span>{runningStatus.satelliteCnt || 0}颗</span>
<span>模式:</span>
<span>
{runningStatus.controlMode == 1 ? '本地' :
2026-08-12 11:29:44 +08:00
runningStatus.controlMode == 3 ? '远程' : t('constants.locationUnknown')}
2026-08-03 14:38:28 +08:00
</span>
</div>
</div>
</> : null}
</Space>
2026-08-03 14:38:28 +08:00
{/* 视频层:停止时不渲染 / 未播放时为空,不影响状态面板 */}
{robotVideo && isVideoPlaying && (
mowerView === 'all' ? (
<div style={{ width: '100%', height: '100%' }}>
2026-08-03 14:38:28 +08:00
<MowerAllView
serialNumber={device?.serialNumber}
2026-08-03 14:38:28 +08:00
robotVideo={robotVideo}
2026-07-08 10:25:11 +08:00
error={error}
ready={ready}
/>
</div>
2026-08-03 14:38:28 +08:00
) : (
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
<VideoPlayer
deviceId={device?.serialNumber}
idx={
mowerView === 'front' ? 1
: mowerView === 'back' ? 2
: mowerView === 'left' ? 3
: 4
}
className="w-full h-full object-contain"
video={robotVideo}
error={error}
ready={ready}
/>
</div>
)
)}
{/* 视频未加载 / 停止播放的占位 */}
{(!robotVideo || !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 }}>
2026-08-12 11:29:44 +08:00
{!isVideoPlaying ? '已停止视频' : t('video.videoLoading')}
</div>
<div style={{ fontSize: 12, opacity: 0.7 }}>
{!isVideoPlaying ? '点击右上角「播放」按钮开启视频' : ''}
</div>
</div>
)}
{/* 单视频(非全景)模式状态叠加层:始终渲染,和视频层解耦 */}
{mowerView !== 'all' && (
<div style={{
position: 'absolute',
top: 106,
left: 20,
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' }}>机器人状态</div>
<div style={{ display: 'grid', gridTemplateColumns: 'auto auto', gap: '3px 10px' }}>
<span>电量:</span>
<span style={{ color: (runningStatus.battery || 0) < 20 ? '#ff4d4f' : '#52c41a' }}>
{runningStatus.battery !== undefined ? `${runningStatus.battery}%` : '-'}
</span>
<span>电压:</span>
<span>{runningStatus.voltage !== undefined ? `${Number(runningStatus.voltage).toFixed(2)}V` : '-'}</span>
<span>左电机:</span>
<span>{runningStatus.leftCurrent !== undefined ? `${Number(runningStatus.leftCurrent).toFixed(2)}A` : '-'}</span>
<span>右电机:</span>
<span>{runningStatus.rightCurrent !== undefined ? `${Number(runningStatus.rightCurrent).toFixed(2)}A` : '-'}</span>
<span>左速度:</span>
<span>{runningStatus.leftMeasureSpeed !== undefined ? `${Number(runningStatus.leftMeasureSpeed).toFixed(1)}rpm` : '-'}</span>
<span>右速度:</span>
<span>{runningStatus.rightMeasureSpeed !== undefined ? `${Number(runningStatus.rightMeasureSpeed).toFixed(1)}rpm` : '-'}</span>
<span>左温度:</span>
<span>{runningStatus.leftMotorTemp !== undefined ? `${Number(runningStatus.leftMotorTemp).toFixed(1)}℃` : '-'}</span>
<span>右温度:</span>
<span>{runningStatus.rightMotorTemp !== undefined ? `${Number(runningStatus.rightMotorTemp).toFixed(1)}℃` : '-'}</span>
<span>主控温度:</span>
<span>{runningStatus.chipTemp !== undefined ? `${Number(runningStatus.chipTemp).toFixed(1)}℃` : '-'}</span>
<span>航向角:</span>
<span>{runningStatus.yaw !== undefined ? `${Number(runningStatus.yaw).toFixed(1)}°` : '-'}</span>
<span>俯仰角:</span>
<span>{runningStatus.pitch !== undefined ? `${Number(runningStatus.pitch).toFixed(1)}°` : '-'}</span>
<span>航向角状态:</span>
<span>{runningStatus.headingStatus !== undefined ? `${runningStatus.headingStatus == 1 ? '初始化' : '未初始化'}` : '-'}</span>
<span>定位:</span>
<span>
2026-08-12 11:29:44 +08:00
{runningStatus.qual == 0 ? t('constants.locationInvalid') :
runningStatus.qual == 1 ? 'GPS单点' :
runningStatus.qual == 2 ? 'DGPS差分' :
runningStatus.qual == 4 ? 'RTK固定' :
2026-08-12 11:29:44 +08:00
runningStatus.qual == 5 ? 'RTK浮点' : t('constants.locationUnknown')}
</span>
<span>卫星:</span>
<span>{runningStatus.satelliteCnt || 0}颗</span>
<span>模式:</span>
<span>
{runningStatus.controlMode == 1 ? '本地' :
2026-08-12 11:29:44 +08:00
runningStatus.controlMode == 3 ? '远程' : t('constants.locationUnknown')}
</span>
</div>
</div>
)
}
2026-08-03 14:38:28 +08:00
</Card>
</Col>
{/* 右边 - 占1格,上部地图,下部远程控制 */}
<Col xs={24} lg={8} style={{ display: 'flex', flexDirection: 'column', }}>
{/* 地图 */}
<Card
title={
<>
<GlobalOutlined />
位置态势图
</>
}
extra={
<Space size={4}>
<Button
size="small"
type="primary"
icon={<DeleteOutlined />}
onClick={() => setClearNavLine((v) => v + 1)}
>
清空实时轨迹
</Button>
<Button
size="small"
danger
icon={<DeleteOutlined />}
onClick={() => {
setPoints([]);
setClearPlanLine((v) => v + 1);
}}
>
清空规划航线
</Button>
</Space>
}
bordered={false}
style={{ borderRadius: 12, marginBottom: 8, flex: 1, minHeight: 280 }}
bodyStyle={{ padding: 12, height: 'calc((100vh - 260px) / 2)', minHeight: 280 }}
>
<CesiumMap
ref={mapRef}
devices={[mapDevices]}
points={points}
markedPoints={markedPoints}
realtimePosition={realtimePosition}
realtimeType={realtimeType}
drawRealTime={true}
finishPoint={arrivedPoint}
ifClearNavLine={clearNavLine}
ifClearPlanLine={clearPlanLine}
from="deviceStatus"
/>
</Card>
{/* 远程控制面板 */}
<Card
title={
<>
<ControlOutlined />
远程控制
</>
}
bordered={false}
style={{ borderRadius: 12, background: '#0f172a', flex: 1, minHeight: 280, }}
headStyle={{ color: '#fff' }}
bodyStyle={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 'calc(100% - 57px)' }}
>
<XboxController
onGamepadUpdate={handleGamepadUpdate}
handleControlModal={handleControlModal}
isControlled={isControlled}
hasControlRight={hasControlRight}
isConnecting={connecting}
/>
</Card>
</Col>
</Row>
)}
2026-07-08 10:25:11 +08:00
2026-08-03 14:38:28 +08:00
<Modal
open={isModalOpen}
onOk={handleOk}
onCancel={handleCancel}
title={modalContent.title}
2026-08-12 11:29:44 +08:00
okText={t('common.ok')}
cancelText={t('common.cancel')}
2026-08-03 14:38:28 +08:00
>
<p>{modalContent.content}</p>
</Modal>
{/* 保存路径模态框 */}
<Modal
open={isSaveModalVisible}
title="保存路径"
onOk={handleSave}
onCancel={() => setIsSaveModalVisible(false)}
2026-08-12 11:29:44 +08:00
okText={t('common.save')}
cancelText={t('common.cancel')}
2026-08-03 14:38:28 +08:00
confirmLoading={isSaving}
>
<div style={{ marginBottom: 16 }}>
<label style={{ display: 'block', marginBottom: 8 }}>地块名称</label>
<input
type="text"
value={plotName}
onChange={(e) => setPlotName(e.target.value)}
placeholder="请输入地块名称"
style={{
width: '100%',
padding: '8px 12px',
border: '1px solid #d9d9d9',
borderRadius: 4,
fontSize: 14,
}}
/>
</div>
2026-08-03 14:38:28 +08:00
{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' }}>保存中...</div>
</div>
)}
<style>
{`
@keyframes spin {
to {
transform: rotate(360deg);
}
}
`}
2026-08-03 14:38:28 +08:00
</style>
</Modal>
</div>
</div >
2026-05-11 16:34:44 +08:00
);
}