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

1543 lines
62 KiB
TypeScript
Raw Normal View History

import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
2026-05-11 10:47:51 +08:00
import {
Layout, Card, Row, Col, Statistic, Tag, Button, Table,
Typography, Space, Progress, Badge, Timeline, message,
2026-06-12 17:34:35 +08:00
Select, Modal, Space as AntSpace,
2026-11-12 09:59:37 +08:00
Input, Tooltip,
Empty
2026-05-11 10:47:51 +08:00
} from 'antd';
import {
EnvironmentOutlined, RobotOutlined, BranchesOutlined,
ThunderboltOutlined, CheckCircleOutlined, PauseOutlined,
RocketOutlined, SyncOutlined, WarningOutlined,
CloudOutlined, ClockCircleOutlined, ReloadOutlined,
AimOutlined, ApiOutlined, SettingOutlined,
PlusOutlined, ArrowRightOutlined,
2026-05-18 17:25:41 +08:00
EditOutlined, FullscreenOutlined, InfoCircleOutlined,
CarOutlined
2026-05-11 10:47:51 +08:00
} from '@ant-design/icons';
2026-08-04 16:11:27 +08:00
import { useNavigate } from 'react-router-dom';
2026-05-11 14:59:36 +08:00
import DroneLivePlayer from '../VolcRtcPlayer.jsx';
2026-05-25 10:30:20 +08:00
import DroneVideoPlayer from './DroneVideoPlayer';
2026-05-12 11:11:30 +08:00
import AgoraTextTest from '../AgoraRtc.tsx';
import { useWebRTCPlayer } from '../useWebRTCStream.tsx';
import VideoPlayer from '../VideoPlayer.tsx';
2026-09-08 15:59:41 +08:00
2026-11-02 12:51:12 +08:00
import DeviceController from './DeviceController';
2026-09-08 15:59:41 +08:00
import AgrtcRoomRobot from '../AgrtcRoomRobot';
import CesiumMap from '../Map.jsx';
import DeviceParamModal from './DeviceParamModal';
import { getUAVState, getSiteDevice, getSiteUAVList, getsinglePlan, getRobotTaskList, getDeviceTotalData, updateDeviceAliasApi, hasPermission } from '@/api/device.ts';
import { getAlarmList, handleAlarm } from '@/api/alarmApi.js';
2026-11-12 09:59:37 +08:00
2026-06-02 13:50:00 +08:00
import dayjs from 'dayjs';
import { useMqtt } from '@/hooks/useMqtt';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
2026-06-02 13:50:00 +08:00
import envConfig from '../../../env';
2026-06-12 17:34:35 +08:00
import utils from '@/lib/utils.ts';
import { useUnitFormatter } from '@/lib/units';
2026-08-12 11:29:44 +08:00
import { useTranslation } from 'react-i18next';
import { sendEmergencyStop, subscribeEmergencyStop, syncEmergencyStop } from './emergencyStopControl';
2026-11-12 09:59:37 +08:00
import AlarmLevelTag from '../AlarmLevelTag.tsx';
import { getDeviceTastPool } from '@/api/device.ts';
import { backToRestPointCommand } from '@/api/mapEdit';
import './DeviceOverviewPage.css';
2026-05-11 10:47:51 +08:00
const { Content } = Layout;
const { Text, Title } = Typography;
// 告警时间兼容:Java LocalDateTime 数组 / ISO 字符串 / 时间戳
const formatAlarmTime = (value: any, fmt = 'YYYY-MM-DD HH:mm:ss') => {
if (value === null || value === undefined || value === '') return '';
if (Array.isArray(value)) {
const [y, mo, d, h = 0, mi = 0, se = 0] = value;
if (!y) return '';
const dt = dayjs(new Date(y, mo - 1, d, h, mi, se));
return dt.isValid() ? dt.format(fmt) : '';
}
const dt = dayjs(value);
return dt.isValid() ? dt.format(fmt) : String(value);
};
// 告警标题:alarmTitle 是编码时改用 alarmContent 中文描述
const isAlarmCode = (value: any) => typeof value === 'string' && /^[A-Z][A-Z0-9_]*$/.test(value);
const getAlarmTitleText = (record: any) => {
const title = record?.alarmTitle;
return (isAlarmCode(title) ? record?.alarmContent : (title || record?.alarmContent)) || record?.alarmNo || '';
};
// 告警级别:兼容数字 1-4 / CRITICAL 等别名
const ALARM_LEVEL_ALIAS: Record<string, string> = {
'1': 'ERROR', '2': 'WARNING', '3': 'INFO', '4': 'INFO',
CRITICAL: 'ERROR', MAJOR: 'WARNING', MINOR: 'INFO',
};
const resolveAlarmLevel = (record: any) => {
const raw = String(record?.alertLevel ?? record?.alarmLevel ?? 'INFO').toUpperCase();
return ALARM_LEVEL_ALIAS[raw] || raw;
};
2026-05-11 10:47:51 +08:00
export default function DeviceOverviewPage() {
2026-08-12 11:29:44 +08:00
const { t } = useTranslation();
const { userInfo } = useSelector((state: RootState) => state.user);
2026-08-04 16:33:52 +08:00
const { stationId, currentStation } = useSelector((state: RootState) => state.station);
const { formatTemperature } = useUnitFormatter();
2026-05-22 15:53:15 +08:00
const [zoomedVideo, setZoomedVideo] = useState(null);
const [mowerView, setMowerView] = useState('front');
const [videoSource, setVideoSource] = useState('drone');
2026-05-27 15:08:26 +08:00
const [uavState, setUavState] = useState(null);
const [persistentDroneData, setPersistentDroneData] = useState(null);
const [persistentHostData, setPersistentHostData] = useState(null);
const [devices, setDevices] = useState([]);
const [planedevices, setPlaneDevices] = useState([]);
const [devicesAll, setDevicesAll] = useState([]);
2026-06-02 13:50:00 +08:00
const [taskStats, setTaskStats] = useState({ completed: 12, total: 15 });
2026-06-03 14:16:31 +08:00
const [deviceStatistics, setDeviceStatistics] = useState(null);
const [currentSelectedRobot, setCurrentSelectedRobot] = useState(null);
2026-11-02 12:51:12 +08:00
const [realtimeMap, setRealtimeMap] = useState<any>({});
// 急停锁存状态:与 DPadControl / XboxController 共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
2026-11-02 12:51:12 +08:00
const controllerRef = useRef<DeviceController | null>(null);
const [messageApi, contextHolder] = message.useMessage();
2026-11-12 09:59:37 +08:00
const [taskList, setTaskList] = useState<any[]>([]);
const [alarmList, setAlarmList] = useState<any[]>([]);
2026-06-12 17:34:35 +08:00
// 编辑机器人弹窗相关
const [editRobotModalOpen, setEditRobotModalOpen] = useState(false);
const [currentEditRobot, setCurrentEditRobot] = useState(null);
const [editAliasInput, setEditAliasInput] = useState('');
const [editLoading, setEditLoading] = useState(false);
// 设备参数弹窗相关
const [paramModalOpen, setParamModalOpen] = useState(false);
const [currentParamDevice, setCurrentParamDevice] = useState<any>(null);
2026-08-04 16:11:27 +08:00
const navigate = useNavigate();
2026-08-06 13:39:14 +08:00
const [robotPlayActive, setRobotPlayActive] = useState<boolean>(false);
2026-11-12 09:59:37 +08:00
const [taskPoolList, setTaskPoolList] = useState<any[]>([]);
2026-08-04 16:11:27 +08:00
2026-08-14 09:02:52 +08:00
const taskTimeline = [
{ time: '10:24:18', color: 'blue', text: t('devices.uavC01ExecuteFixed2CleaningC05'), status: '任务开始' },
{ time: '10:21:35', color: 'orange', text: t('devices.rbt01ExecuteFixed2InspectionP02'), status: '任务开始' },
{ time: '10:18:02', color: 'green', text: t('devices.gr02G01'), status: '任务开始' },
{ time: '10:15:47', color: 'gray', text: t('devices.uavC02TaskSuspended2'), status: '待命就绪' },
{ time: '10:12:33', color: 'blue', text: t('devices.uavC01'), status: '返机补给' },
{ time: '09:58:10', color: 'green', text: t('devices.rbt02CompleteFixed2InspectionP01'), status: '任务完成' },
];
2026-11-12 09:59:37 +08:00
const fetchTaskPoolList = async () => {
if (!stationId) return;
try {
const params = {
userId: userInfo?.userId,
siteId: stationId,
orgId: currentStation?.orgId,
pageNum: 1,
pageSize: 10
};
const res = await getDeviceTastPool(params);
if (res.code === 200) {
const list = res.rows || [];
list.map(item => {
return {
time: dayjs(item.createTime).format('HH:mm:ss'),
color: item.taskStaus === 'EXECUTING' ? 'green' : 'blue',
text: item.workName || t('devices.unnamedTask'),
status: item.taskStaus === 'EXECUTING' ? t('devices.executing') : item.taskStaus === 'FAILED' ? t('devices.executeFail') : item.taskStaus === 'COMPLETED' ? t('devices.statusFinished') : item.taskStaus === 'CANCELED' ? t('devices.taskCanceled') : t('devices.taskStatusNew')
}
})
setTaskPoolList(list);
}
} catch (err) {
console.error('获取任务池失败:', err);
}
};
2026-08-14 09:02:52 +08:00
2026-08-12 11:29:44 +08:00
2026-06-12 17:34:35 +08:00
// 获取数据
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);
}
};
2026-08-04 16:11:27 +08:00
const onViewStatus = (sn) => {
navigate(`/devices/status?sn=${sn}`);
}
2026-06-03 14:16:31 +08:00
const getRealtimeColor = (status: any) => {
const s = Number(status);
if (s === 1) return 'green';
if (s === 2) return 'blue';
return 'red';
};
const mapDevices = useMemo(() => {
const base = [...devices];
const knownKeys = new Set();
base.forEach((d: any) => {
const k = d?.serialNumber ?? d?.device_sn ?? d?.id;
if (k != null && k !== '') knownKeys.add(String(k));
});
// mapPush 推的是 { [设备id]: 实时记录 },同时兼容数组结构
const rtList: any[] = Array.isArray(realtimeMap) ? realtimeMap : Object.values(realtimeMap || {});
const extras = rtList
.filter((rt: any) =>
Number.isFinite(Number(rt.lng)) &&
Number.isFinite(Number(rt.lat)) &&
!(Number(rt.lng) === 0 && Number(rt.lat) === 0) &&
!knownKeys.has(String(rt.id))
)
.map((rt: any) => ({
id: rt?.id,
name: rt?.name || rt?.alias || `设备-${String(rt?.id).slice(-4)}`,
serialNumber: rt?.id,
status: rt?.status,
color: getRealtimeColor(rt?.status),
longitude: rt?.lng,
latitude: rt?.lat,
heading: rt?.yaw,
batteryLevel: rt?.battery,
updateTime: rt?.updateTime,
feStatus: rt?.feStatus,
taskId: rt?.t,
isRealtimeOnly: true,
emergencyStop: rt?.emergencyStop,
// 同步写入 locationMessage / lastRunningStatus,确保 Map.jsx 设备渲染 useEffect 能读到实时坐标
locationMessage: { longitude: rt?.lng, latitude: rt?.lat, heading: rt?.yaw, batteryLevel: rt?.battery },
lastRunningStatus: { longitude: rt?.lng, latitude: rt?.lat, heading: rt?.yaw, batteryLevel: rt?.battery },
raw: { ...rt },
}));
// 关键:把静态列表中已有设备的位置/状态用实时数据覆盖,
// 否则 base 里的设备永远只有接口返回的旧坐标,地图实体不会实时动
const rtMapDict: any = Array.isArray(realtimeMap)
? realtimeMap.reduce((acc: any, r: any, i: number) => { acc[String(r?.id ?? i)] = r; return acc; }, {})
: (realtimeMap || {});
const baseOverridden = base.map((d) => {
const k = String(d?.serialNumber ?? d?.device_sn ?? d?.id ?? "");
const rt = rtMapDict[k];
if (!rt) return { ...d, color: 'red' };
return {
...d,
longitude: rt.lng ?? d.longitude,
latitude: rt.lat ?? d.latitude,
heading: rt.yaw ?? d.heading,
batteryLevel: rt.battery ?? d.batteryLevel,
feStatus: rt.feStatus ?? d.feStatus,
status: rt.status ?? d.status,
color: getRealtimeColor(rt.status),
hasAlarm: !!rt.hasAlarm,
taskId: rt.t ?? rt.taskId ?? d.taskId,
updateTime: rt.updateTime ?? d.updateTime,
locationMessage: {
longitude: rt.lng ?? d.locationMessage?.longitude,
latitude: rt.lat ?? d.locationMessage?.latitude,
heading: rt.yaw ?? d.locationMessage?.heading,
batteryLevel: rt.battery ?? d.locationMessage?.batteryLevel,
},
lastRunningStatus: {
longitude: rt.lng ?? d.lastRunningStatus?.longitude,
latitude: rt.lat ?? d.lastRunningStatus?.latitude,
heading: rt.yaw ?? d.lastRunningStatus?.heading,
batteryLevel: rt.battery ?? d.lastRunningStatus?.batteryLevel,
},
};
});
const all = [...baseOverridden, ...extras];
return all.filter((d: any) =>
(d?.lastRunningStatus?.latitude && d?.lastRunningStatus?.longitude) ||
(d?.locationMessage?.latitude && d?.locationMessage?.longitude) ||
(d?.longitude && d?.latitude)
);
}, [devices, realtimeMap]);
const formatTime = (seconds) => {
const time = Number(seconds || 0);
if (time >= 86400) {
return `${(time / 86400).toFixed(2)} d`;
}
return `${(time / 3600).toFixed(2)} h`;
};
2026-06-12 17:34:35 +08:00
// 打开编辑弹窗
const openEditRobotModal = (record) => {
// 仅机器人允许编辑,无人机直接提示
const isRobot = !record.gateway_sn && !record.drone_callsign;
if (!isRobot) {
2026-08-14 09:02:52 +08:00
message.info(t('devices.editFixed2RobotFixed2Device'));
2026-06-12 17:34:35 +08:00
return;
}
setCurrentEditRobot(record);
setEditAliasInput(record.deviceAlias || record.deviceName || '');
setEditRobotModalOpen(true);
};
// 确认保存别名
const handleSaveRobotAlias = async () => {
if (!currentEditRobot || !editAliasInput.trim()) {
2026-08-14 09:02:52 +08:00
utils.message.warning(t('devices.fixed2Device'));
2026-06-12 17:34:35 +08:00
return;
}
setEditLoading(true);
try {
const data = {
deviceId: currentEditRobot.serialNumber,
deviceAlias: editAliasInput.trim()
}
const sn = currentEditRobot.device_sn || currentEditRobot.serialNumber;
const res = await updateDeviceAliasApi(data);
if (res.code === 200 && res.data == true) {
fetchAllData();
2026-08-14 09:02:52 +08:00
utils.message.success(t('devices.modifiedSuccessfullyFixed2'));
2026-06-12 17:34:35 +08:00
setEditRobotModalOpen(false);
} else {
2026-08-14 09:02:52 +08:00
utils.message.error(t('devices.fixed2ModificationFailed'));
2026-06-12 17:34:35 +08:00
}
} catch (err) {
console.error('修改别名报错', err);
2026-08-14 09:02:52 +08:00
utils.message.error(t('devices.fixed2Fixed2AbnormalModificationFailedFixed2'));
2026-06-12 17:34:35 +08:00
} finally {
setEditLoading(false);
}
};
2026-11-02 12:51:12 +08:00
useEffect(() => {
if (!userInfo || !stationId) return;
const controller = new DeviceController(userInfo, messageApi, stationId);
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
// 全局推送的新告警:合并到列表顶部(按 id 去重),只显示最近 5 条
controller.onDeviceErrorPush = (payload: any) => {
const incoming: any[] = Array.isArray(payload?.alarms) ? payload.alarms : [];
setAlarmList(incoming);
};
2026-11-02 12:51:12 +08:00
controllerRef.current = controller;
return () => {
if (controllerRef.current) controllerRef.current.closeMapPush();
};
}, [userInfo, stationId]);
useEffect(() => {
fetchAllData();
2026-11-12 09:59:37 +08:00
fetchAlarmList();
fetchTaskPoolList();
}, [stationId]);
2026-06-02 13:50:00 +08:00
useEffect(() => {
fetchTaskStats();
}, [devicesAll.length]);
// 获取今日任务统计
const fetchTaskStats = async () => {
if (!stationId) return;
try {
const todayStart = dayjs().startOf('day').unix();
const todayEnd = dayjs().endOf('day').unix();
let completedCount = 0;
let totalCount = 0;
// 1. 获取无人机今日任务
if (planedevices?.length > 0) {
try {
const sns = planedevices.map(item => item.gateway_sn);
const droneRes = await getsinglePlan({ sns, beginAt: todayStart, endAt: todayEnd });
if (droneRes?.code === 200 && droneRes.data) {
let droneTasks = [];
Object.values(droneRes.data).forEach((item: any) => {
if (item.list) droneTasks = droneTasks.concat(item.list);
});
totalCount += droneTasks.length;
// 计算无人机完成的任务
completedCount += droneTasks.filter(t =>
['success', 'completed', 'executed', 'FINISH', 'COMPLETED'].includes(t.status)
).length;
}
} catch (err) {
console.error('获取无人机任务统计失败', err);
}
}
// 2. 获取机器人今日任务
try {
const robotRes = await getRobotTaskList({ siteId: String(stationId) });
if (robotRes?.code == 200 && robotRes.data) {
2026-11-12 09:59:37 +08:00
setTaskList(robotRes?.data?.slice(0, 5) ?? []);
2026-06-02 13:50:00 +08:00
const todayRobotTasks = robotRes.data.filter((t: any) => {
// 简单判断是今日的任务
if (t.createTime) {
const taskTime = dayjs(t.createTime);
return taskTime.isAfter(dayjs().startOf('day')) && taskTime.isBefore(dayjs().endOf('day'));
}
return true; // 默认都算
});
totalCount += todayRobotTasks.length;
// 计算机器人完成的任务
completedCount += todayRobotTasks.filter((t: any) =>
['FINISH', 'FINISHED', 'COMPLETED', 'completed'].includes(t.taskStaus)
).length;
}
} catch (err) {
console.error('获取机器人任务统计失败', err);
}
setTaskStats({ completed: completedCount, total: totalCount });
} catch (err) {
console.error('获取任务统计失败', err);
setTaskStats({ completed: 12, total: 15 });
}
};
2026-06-01 15:44:02 +08:00
2026-11-12 09:59:37 +08:00
// 当前选中设备(切换时才变)
const selectedDevice = useMemo(() => {
const sn = currentSelectedRobot || (devicesAll?.[0]?.device_sn || devicesAll?.[0]?.serialNumber);
2026-05-12 08:34:13 +08:00
return devicesAll?.find(item => (item.device_sn || item.serialNumber) === sn) || null;
}, [devicesAll, currentSelectedRobot]);
2026-05-12 08:34:13 +08:00
2026-05-22 15:53:15 +08:00
const isUAV = !!selectedDevice?.gateway_sn;
2026-06-03 14:16:31 +08:00
useEffect(() => {
if (isUAV || !selectedDevice?.serialNumber) return;
const params = {
deviceId: selectedDevice?.serialNumber,
}
getDeviceTotalData(params).then((res) => {
if (res.code == 200) {
setDeviceStatistics(res.data || {})
}
})
}, [selectedDevice])
2026-05-22 15:53:15 +08:00
// ======================== 核心优化:视频用设备对象(绝不随MQTT刷新)========================
const videoDevice = useMemo(() => {
if (!selectedDevice) return null;
return { ...selectedDevice };
}, [selectedDevice]); // 只有切设备才变 → 视频不闪
2026-11-02 12:51:12 +08:00
// ======================== UI显示用(MQTT/WS实时更新)========================
const realtimeDevice = useMemo(() => {
if (!selectedDevice) return null;
2026-11-02 12:51:12 +08:00
const sn = selectedDevice.device_sn || selectedDevice.serialNumber;
const wsData = realtimeMap[sn] || {};
2026-11-16 14:33:48 +08:00
//setDeviceStatistics(wsData || {})
2026-11-02 12:51:12 +08:00
return {
...selectedDevice,
...uavState,
...persistentHostData,
...persistentDroneData,
2026-11-02 12:51:12 +08:00
...wsData,
// 统一字段名
capacity_percent: wsData.battery_level ?? wsData.battery ?? wsData.capacity_percent ?? persistentDroneData?.capacity_percent ?? selectedDevice.capacity_percent ?? 100
};
2026-11-02 12:51:12 +08:00
}, [selectedDevice, uavState, persistentHostData, persistentDroneData, realtimeMap]);
// 实时数据里的急停状态同步到共享锁存状态:true=已急停,false=未急停
useEffect(() => {
syncEmergencyStop(realtimeDevice?.emergencyStop);
}, [realtimeDevice?.emergencyStop]);
// MQTT消息处理
const handleMqttMessage = useCallback((topic, message) => {
2026-06-02 10:08:23 +08:00
try {
const parsed = JSON.parse(message);
if (parsed.data?.host) {
const { host } = parsed.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('MQTT解析失败', err);
}
}, []);
// MQTT订阅
const mqttTopics = useMemo(() => {
if (!isUAV || !selectedDevice) return [];
const topics = [];
if (selectedDevice.device_sn) {
topics.push(`thing/product/${selectedDevice.device_sn}/osd`);
}
if (selectedDevice.gateway_sn && selectedDevice.gateway_sn !== selectedDevice.device_sn) {
topics.push(`thing/product/${selectedDevice.gateway_sn}/osd`);
}
return topics;
}, [selectedDevice]);
useMqtt({
url: envConfig.mqtt_url,
topic: mqttTopics,
onMessage: handleMqttMessage,
enabled: mqttTopics.length > 0,
});
// 机器人视频
2026-08-06 13:39:14 +08:00
// 机器人视频:只有 robotPlayActive = true 才真正拉流
2026-05-22 15:53:15 +08:00
const { video: robotVideo, error, ready } = useWebRTCPlayer(
2026-09-08 15:59:41 +08:00
(!isUAV && robotPlayActive && !selectedDevice?.hasHost) ? (selectedDevice?.serialNumber || '') : '',
2026-08-06 13:39:14 +08:00
(!isUAV && robotPlayActive)
? `webrtc://1.95.137.212/live/livestream/${selectedDevice?.serialNumber}`
: ''
2026-05-22 15:53:15 +08:00
);
const getDevivePermisstion = (data) => {
const params = {
deviceId: data.serialNumber,
}
setCurrentParamDevice(data);
setParamModalOpen(true);
return;
hasPermission(params).then(res => {
if (res.code == 200) {
if (res.data) {
} else {
2026-08-14 09:02:52 +08:00
utils.message.error(t('devices.noPermission'));
}
}
})
}
// 手动处理告警:handleStatus=2 表示已关闭
const handleAlarmItem = async (record: any) => {
const alarmId = record?.id;
if (!alarmId) return;
try {
const res = await handleAlarm({ alarmId, handleStatus: 2 });
if (res?.code === 200) {
messageApi.success(t('alerts.handleSuccess'));
setAlarmList((prev) => prev.filter((a) => a.id !== alarmId));
} else {
messageApi.error(res?.msg || t('alerts.handleFail'));
}
} catch (err) {
console.error('处理告警失败', err);
messageApi.error(t('alerts.handleFail'));
}
};
2026-11-12 09:59:37 +08:00
const fetchAlarmList = async () => {
try {
const res = await getAlarmList({ pageNum: 1, pageSize: 5, siteId: stationId });
if (res.code === 200) {
setAlarmList(res.rows?.slice(0, 5) ?? []);
}
} catch (err) {
messageApi.error(t('common.loadFailed'));
} finally {
}
};
// 顶部统计卡片
//feStatus; 1任务中 / 2空闲
const dynamicTopCards = useMemo(() => {
2026-05-11 14:59:36 +08:00
const totalDrones = planedevices?.length || 0;
2026-11-02 12:51:12 +08:00
const onlineDrones = planedevices?.filter(d => {
const rt = realtimeMap[d.device_sn];
return rt ? rt.status !== 'OFFLINE' : d.onlineStatus === 1;
}).length || 0;
const totalRobots = devices?.filter(d => !d.gateway_sn).length || 0;
const onlineRobots = devices?.filter(d => {
if (d.gateway_sn) return false;
const rt = realtimeMap[d.serialNumber];
return rt ? rt.status !== 'OFFLINE' : d.onlineStatus === 1;
}).length || 0;
const activeMowers = devices?.filter(d => {
const rt = realtimeMap[d.serialNumber];
return rt ? rt.status === 'EXECUTING' : d.feStatus == 1;
}).length || 0;
const washDroneStandby = planedevices?.filter(d => {
const rt = realtimeMap[d.device_sn];
return rt ? rt.status === 'IDLE' : true; // 简化逻辑
}).length || 0;
2026-06-02 13:50:00 +08:00
// 今日任务执行统计
const completedTasks = taskStats.completed;
const totalTasks = taskStats.total;
const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
2026-05-11 14:59:36 +08:00
return [
2026-06-02 14:15:16 +08:00
{
2026-08-14 09:02:52 +08:00
title: t('devices.fixed2DroneAirportFixed2StatusFixed2'),
icon: <EnvironmentOutlined className="device-overview-top-icon-blue" />,
2026-06-02 14:15:16 +08:00
value: `${onlineDrones} / ${totalDrones}`,
sub: `${t('devices.distributable')} ${onlineDrones} ${t('devices.UnitsDrone')}`,
2026-06-02 14:15:16 +08:00
color: '#165DFF',
iconBg: '#E8F3FF'
},
{
2026-08-12 11:29:44 +08:00
title: t('home.inspectionRobot'),
icon: <RobotOutlined className="device-overview-top-icon-cyan" />,
2026-11-02 12:51:12 +08:00
value: `${onlineRobots} / ${totalRobots}`,
sub: `${t('devices.online')} ${onlineRobots}`,
2026-06-02 14:15:16 +08:00
color: '#13c2c2',
iconBg: '#E6FFFA'
},
{
2026-08-14 09:02:52 +08:00
title: t('devices.mowingRobot'),
icon: <CarOutlined className="device-overview-top-icon-purple" />,
2026-11-02 12:51:12 +08:00
value: `${totalRobots} ${t('devices.UnitsRobot')}`,
sub: `${t('devices.executing')} ${activeMowers}`,
2026-06-02 14:15:16 +08:00
color: '#722ED1',
iconBg: '#F9F0FF'
},
{
2026-08-14 09:02:52 +08:00
title: t('devices.washDrone'),
icon: <CloudOutlined className="device-overview-top-icon-pink" />,
value: `${totalDrones} ${t('devices.UnitsDrone')}`,
sub: `${t('devices.waiting')} ${washDroneStandby}`,
2026-06-02 14:15:16 +08:00
color: '#eb2f96',
iconBg: '#FFF1F3'
},
{
2026-08-14 09:02:52 +08:00
title: t('devices.todayTaskExecute'),
icon: <CheckCircleOutlined className="device-overview-top-icon-indigo" />,
2026-06-02 14:15:16 +08:00
value: `${completedTasks} / ${totalTasks}`,
sub: `${t('devices.completionRate')} ${completionRate}%`,
2026-06-02 14:15:16 +08:00
color: '#2f54eb',
iconBg: '#E8F3FF'
},
2026-05-11 14:59:36 +08:00
];
2026-11-02 12:51:12 +08:00
}, [devices, planedevices, realtimeMap, taskStats]);
const handleAutoBack = () => {
const payload = {
deviceId: selectedDevice?.serialNumber,
orgId: currentStation?.orgId,
siteId: stationId,
}
backToRestPointCommand(payload).then(res => {
if (res.code == 200) {
message.success(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2'));
} else {
message.error(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2Failed'));
}
}).catch(err => {
console.error('返回休息点失败', err);
})
}
2026-05-11 14:59:36 +08:00
// 设备调度列表
const dynamicScheduleList = useMemo(() => {
2026-11-02 12:51:12 +08:00
return devicesAll?.map((d, index) => {
const sn = d.serialNumber || d.device_sn;
const rt = realtimeMap[sn] || {};
const online = rt.status !== undefined ? (rt.status !== 'OFFLINE' ? 1 : 0) : d.onlineStatus;
// 状态 / 电量优先取实时消息
const rtFeStatus = rt?.status;
const rtBattery = rt.battery ?? rt.battery_level ?? rt.capacity_percent ?? undefined;
2026-11-02 12:51:12 +08:00
return {
...d,
id: d.deviceId || index,
name: d.deviceAlias || d.deviceName || d.callsign || '未知设备',
type: d.deviceType || "割草机",
status: online === 1 ? t('devices.online') : t('devices.offline'),
onlineStatus: online,
mode: rt.status === 'EXECUTING' ? '作业中' : rt.status === 'IDLE' ? t('devices.idle') : (d.feStatus == 1 ? '作业中' : d.feStatus == 2 ? t('devices.idle') : '离线'),
feStatus: rtFeStatus,
capacity_percent: rtBattery ?? d.capacity_percent ?? 100,
lastRunningStatus: {
...(d.lastRunningStatus || {}),
battery: rtBattery ?? d.lastRunningStatus?.battery ?? d?.vehicleMessage?.battery
},
2026-11-02 12:51:12 +08:00
position: rt.position || d.position || '站内',
task: rt.currentTaskName || d.task || (d.status === 4 ? '待命' : '作业中'),
comm: rt.rssi ? `${rt.rssi}dBm` : (d.rssi ? `${d.rssi}dBm` : '良好'),
work_area: rt.work_area || 0
};
}) || [];
}, [devicesAll, realtimeMap]);
2026-05-11 14:59:36 +08:00
2026-08-14 09:02:52 +08:00
const handleStart = () => message.success(t('devices.fixed2TaskSuspended22'));
const handlePause = () => message.info(t('devices.taskPaused'));
const handleReturn = () => message.info(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2'));
const handleRecharge = () => message.info(t('devices.commandIssuedFixed2'));
// 急停:点击时直接下发 button7(绕过控制权限校验),并提示已触发
const handleEmergencyStop = async () => {
const next = await sendEmergencyStop(selectedDevice?.serialNumber || "");
if (next) message.error(t('devices.estopTriggered'));
else message.success(t('devices.estopNormal'));
};
2026-05-22 15:53:15 +08:00
2026-05-11 11:59:17 +08:00
const fix2 = (val) => {
if (val === null || val === undefined || isNaN(val)) return '-';
return Number(val).toFixed(2);
};
2026-05-11 14:59:36 +08:00
const getVal = (val) => val == "no_rain" ? "无" : (val || '-');
2026-05-11 11:59:17 +08:00
2026-05-11 14:59:36 +08:00
const handleDeviceChange = (id) => {
setCurrentSelectedRobot(id);
2026-08-06 13:39:14 +08:00
setRobotPlayActive(false);
2026-05-11 11:59:17 +08:00
};
2026-05-11 10:47:51 +08:00
// 获取无人机状态
2026-05-27 15:08:26 +08:00
useEffect(() => {
const fetchUavState = async () => {
if (isUAV && selectedDevice?.gateway_sn && selectedDevice?.device_sn) {
try {
const res = await getUAVState({
sn: selectedDevice.gateway_sn,
droneSn: selectedDevice.device_sn
});
if (res.code === 200) setUavState(res.data);
2026-05-27 15:08:26 +08:00
} catch (err) {
console.error('获取无人机状态失败', err);
}
} else {
setUavState(null);
}
};
2026-06-01 15:44:02 +08:00
fetchUavState();
}, [selectedDevice]);
2026-05-27 15:08:26 +08:00
2026-05-11 10:47:51 +08:00
return (
<div className="device-overview-page">
<div className="device-overview-title-wrap">
<Typography.Title level={4} className="device-overview-title">{t('devices.fixed2Equipment')}</Typography.Title>
2026-08-03 14:38:28 +08:00
</div>
<Content className="device-overview-content">
<Row gutter={[12, 12]} className="device-overview-top-row">
2026-08-03 14:38:28 +08:00
{dynamicTopCards.map((card, idx) => (
<Col key={idx} className="device-overview-top-col">
2026-08-03 14:38:28 +08:00
<Card
variant="borderless"
className="device-overview-stat-card"
2026-08-03 14:38:28 +08:00
>
{/* 左侧文字区域 */}
<div className="device-overview-stat-info">
<div className="device-overview-stat-title">
2026-08-03 14:38:28 +08:00
{card.title}
</div>
<div className="device-overview-stat-value" style={{ '--card-color': card.color } as React.CSSProperties}>
2026-08-03 14:38:28 +08:00
{card.value}
</div>
{/* 底部环比/备注 */}
{card.sub && <div className="device-overview-stat-sub">
2026-08-03 14:38:28 +08:00
{card.sub}
</div>}
2026-05-11 10:47:51 +08:00
</div>
2026-08-03 14:38:28 +08:00
{/* 右侧圆形图标区域 */}
<div
className="device-overview-stat-icon" style={{ '--icon-bg': card.iconBg || '#f0f7ff' } as React.CSSProperties}
2026-08-03 14:38:28 +08:00
>
{card.icon}
</div>
</Card>
</Col>
))}
</Row>
<Row gutter={[8, 8]}>
<Col xs={24} lg={14}>
<Card title={<><EnvironmentOutlined />{t('devices.fixed2Equipment')}</>} extra={<Button type="text" icon={<SettingOutlined />} />} variant="borderless" className="device-overview-card device-overview-map-card">
<div className="device-overview-map-container">
{/*<div style={{ position: 'absolute', zIndex: 11, top: 12, left: 12, background: 'rgba(255,255,255,0.95)', borderRadius: 6, padding: 8 }}>
2026-08-14 09:02:52 +08:00
<div style={{ fontSize: 11, fontWeight: 60, marginBottom: 4 }}>{t('devices.s22')}</div>
2026-08-03 14:38:28 +08:00
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 10 }}>
2026-08-14 09:02:52 +08:00
<div><span style={{ color: '#1890ff' }}>———</span>{t('devices.fixed2Inspection')}</div>
<div><span style={{ color: '#fa8c16' }}>———</span>{t('devices.robotPath')}</div>
<div><span style={{ color: '#52c41a' }}>———</span>{t('devices.cleaningPath')}</div>
<div>{t('devices.locationFixed2')}</div>
<div>{t('devices.dronePositionFixed2')}</div>
<div><span style={{ color: '#1890ff' }}>●</span>{t('devices.chargePointFixed2')}</div>
<div><span style={{ color: '#ff4d4f' }}>■</span>{t('devices.s9')}</div>
2026-08-03 14:38:28 +08:00
</div>
</div>*/}
<CesiumMap devices={mapDevices} mapLayer={currentStation?.siteMapName} />
2026-06-02 14:15:16 +08:00
</div>
2026-08-03 14:38:28 +08:00
</Card>
2026-06-02 14:15:16 +08:00
<Card title={<><SettingOutlined />{t('devices.fixed2EquipmentListFixed2')}</>} extra={<Button type="text" icon={<ReloadOutlined />} onClick={fetchAllData} />} variant="borderless" className="device-overview-card">
2026-08-03 14:38:28 +08:00
<Table rowKey={(record) => record.id || record.serialNumber || record.device_sn} size="small" pagination={false}
columns={[
{ title: t('devices.fixed2EquipmentFixed2NameFixed2'), dataIndex: 'name', width: 180 },
2026-08-03 14:38:28 +08:00
{
2026-11-12 09:59:37 +08:00
title: t('common.type'), dataIndex: 'deviceType',
render: (text, record) => {
if (record.deviceType == "U") return t('devices.uav');
if (record.deviceType == "M") return t("devices.mower");
if (record.deviceType == "I") return t("devices.robot");
return record.deviceType || record.type || t('devices.robot');
2026-08-03 14:38:28 +08:00
}
2026-11-12 09:59:37 +08:00
},
//{
// title: t('workOrder.currentStatus'),
// dataIndex: 'onlineStatus',
// width: 70,
// render: (s) => {
// const text = s === 1 ? t('devices.online') : t('devices.offline');
// const color = s === 1 ? 'success' : 'default';
// return <Tag color={color} style={{ margin: 0 }}>{text}</Tag>;
// }
//},
{
title: t('workOrder.currentStatus'), dataIndex: 'feStatus', width: 70, render: (text) => {
let color;
if (text == '1') color = 'processing';
if (text == '2') color = 'success';
if (text == '3') color = 'default'; // default 就是灰色标签
return <Tag color={color} className="device-overview-tag-flat">
{text == '1' ? "工作中" : text == '2' ? "空闲中" : "离线"}
</Tag>;
2026-08-03 14:38:28 +08:00
}
},
{
2026-08-12 11:29:44 +08:00
title: t('devices.batteryLevel'),
2026-08-03 14:38:28 +08:00
dataIndex: 'lastRunningStatus',
width: 70,
render: (lastRunningStatus) => {
const v = lastRunningStatus?.battery ?? "--";
2026-08-03 14:38:28 +08:00
return <Progress
percent={v}
size="small"
status={v < 40 ? 'exception' : 'active'}
/>;
}
},
// { title: t('aiAnalysis.location'), dataIndex: 'position', width: 90 },
2026-11-02 12:51:12 +08:00
//{ title: '累计作业面积', dataIndex: 'work_area', width: 110, render: v => `${Number(v || 0).toFixed(2)} ㎡` },
2026-08-14 09:02:52 +08:00
//{ title: t('devices.fixed2CurrentFixed2TaskSuspended2Fixed2'), dataIndex: 'task', width: 100 },
//{ title: t('devices.statusFixed2'), dataIndex: 'comm', width: 100, render: v => <Badge status={v && v.includes('-') ? 'warning' : 'success'} text={v} /> },
2026-08-03 14:38:28 +08:00
{
2026-08-12 11:29:44 +08:00
title: t('roles.actions'),
2026-08-03 14:38:28 +08:00
key: 'action',
width: 150,
2026-08-03 14:38:28 +08:00
//fixed: 'right',
render: (_, record) => (
<Space size={4}>
2026-08-03 14:38:28 +08:00
<Button
size="small"
type="text"
icon={<EditOutlined />}
onClick={() => openEditRobotModal(record)}
2026-08-12 11:29:44 +08:00
title={t('roles.edit')}
2026-08-03 14:38:28 +08:00
/>
2026-08-14 09:02:52 +08:00
<Tooltip title={t('devices.deviceParamSetting')}>
<Button
size="small"
type="text"
icon={<SettingOutlined />}
onClick={() => {
getDevivePermisstion(record);
}}
/>
</Tooltip>
2026-08-03 14:38:28 +08:00
</Space>
)
}]}
dataSource={dynamicScheduleList}
scroll={{ x: 'max-content', y: 280 }}
/>
</Card>
<Row wrap={false} gutter={16} className="device-overview-panels-row">
2026-11-12 09:59:37 +08:00
<Col flex="1 1 0">
<Card
title={<>
<SettingOutlined /> <span>{t('devices.TaskLog')}</span>
</>}
variant="borderless"
className="device-overview-panel-card"
2026-11-12 09:59:37 +08:00
>
<Table
rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTime}
2026-11-12 09:59:37 +08:00
size="small"
pagination={false}
dataSource={taskList}
scroll={{ x: 'max-content' }}
columns={[
{ title: t('common.createTime'), dataIndex: 'startTime', width: 90, render: (v) => <span className="device-overview-text-13">{v}</span> },
{ title: t('devices.deviceId'), dataIndex: 'deviceId', width: 100, render: (v) => <span className="device-overview-text-13">{v}</span> },
2026-11-12 09:59:37 +08:00
{
title: t('devices.executionPlan'),
width: 280,
render: (_, record) => {
const rule = record.deviceTaskPlanRules || {};
const { type, startDate, dayTime, days, dayOfMonth } = rule;
// 周映射
const weekMap = {
SUNDAY: t('devices.sun'),
MONDAY: t('devices.mon'),
TUESDAY: t('devices.tue'),
WEDNESDAY: t('devices.wed'),
THURSDAY: t('devices.thu'),
FRIDAY: t('devices.fri'),
SATURDAY: t('devices.sat')
};
switch (type) {
case 'DAY':
return t('devices.planByDay', { startDate: startDate || '', dayTime: dayTime || '' });
case 'WEEK':
const weekText = (days || []).map(d => weekMap[d]).join('、');
return t('devices.planByWeek', { weekText, dayTime: dayTime || '' });
case 'MONTH':
const monthText = (dayOfMonth || []).map(d => t('devices.daySuffix', { day: d })).join('、');
return t('devices.planByMonth', { monthText, dayTime: dayTime || '' });
default:
return t('devices.unknownPlan');
}
}
},
{
title: t('devices.executionCycle'),
width: 320,
render: (_, record) => {
return `${record.startTime || ''} - ${record.finishTime || ''}`;
}
},
{
title: t('roles.status'),
dataIndex: 'taskStaus',
width: 100,
render: (status, record) => {
console.log('status', status, record);
const statusMap = {
'NEW': { color: 'default', text: t('devices.statusNew') },
'EXECUTING': { color: 'processing', text: t('workOrder.inProgress') },
'PAUSE': { color: 'warning', text: t('devices.statusPaused') },
'FINISH': { color: 'success', text: t('devices.statusFinished') },
'FAILED': { color: 'error', text: t('devices.statusFailed') },
"CANCELING": { color: 'warning', text: t('devices.statusCanceling') },
};
const item = statusMap[status] || { color: 'default', text: record.taskStausTranslate || t('constants.locationUnknown') };
return <Tag color={item.color}>{record.taskStausTranslate}</Tag>;
2026-11-12 09:59:37 +08:00
}
},
{ title: t('devices.taskName'), dataIndex: 'planName' },
]}
/>
<div className="device-overview-more">
<Button type="link" size="small" className="device-overview-more-btn" onClick={() => navigate('/devices/robotTask')}>
2026-11-12 09:59:37 +08:00
{t('devices.viewMoreLogs')}
</Button>
</div>
</Card>
</Col>
<Col flex="1 1 0">
<Card
title={<>
<SettingOutlined /> <span>{t('devices.AlertRecord')}</span>
</>}
variant="borderless"
className="device-overview-panel-card"
2026-11-12 09:59:37 +08:00
>
<Table
rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTitle}
2026-11-12 09:59:37 +08:00
size="small"
pagination={false}
dataSource={alarmList}
scroll={{ x: 'max-content' }}
columns={[
{
title: t('common.time'),
dataIndex: 'alarmTime',
width: 145,
render: (v) => <span className="device-overview-time-nowrap">{formatAlarmTime(v) || '-'}</span>
},
{
title: t('devices.device'),
dataIndex: 'deviceName',
width: 110,
ellipsis: true,
render: (v, record) => <span className="device-overview-text-12">{record?.deviceAlias || record?.deviceId || v || '-'}</span>
},
2026-11-12 09:59:37 +08:00
{
title: t('alerts.alarmTitle'),
dataIndex: 'alarmContent',
width: 220,
render: (_, record) => {
const text = getAlarmTitleText(record);
return (
<Tooltip title={text}>
<span className="device-overview-text-12">{text || '-'}</span>
</Tooltip>
);
}
},
{
title: t('alerts.alertLevel'),
2026-11-12 09:59:37 +08:00
width: 70,
render: (_, record) => <AlarmLevelTag level={resolveAlarmLevel(record)} size="small" />
2026-11-12 09:59:37 +08:00
},
{
title: t('alerts.handle'),
width: 70,
render: (_, record) => record?.handleStatus === 2
? <Tag className="device-overview-handled-tag">{t('alerts.handled')}</Tag>
: (
<Button type="link" size="small" className="device-overview-handle-btn" onClick={() => handleAlarmItem(record)}>
{t('alerts.handle')}
</Button>
)
2026-11-12 09:59:37 +08:00
},
]}
/>
<div className="device-overview-more">
<Button type="link" size="small" className="device-overview-more-btn" onClick={() => navigate('/alerts/all')}>
2026-11-12 09:59:37 +08:00
{t('devices.viewMoreLogs')}
</Button>
</div>
</Card>
</Col>
</Row>
2026-08-03 14:38:28 +08:00
2026-05-14 09:37:15 +08:00
</Col>
2026-05-11 11:59:17 +08:00
2026-08-03 14:38:28 +08:00
<Col xs={24} lg={10}>
<Card title={<><SettingOutlined className="device-overview-control-title-icon" />{t('devices.deviceControlPanel')}</>} variant="borderless" className="device-overview-card device-overview-control-card">
2026-08-03 14:38:28 +08:00
<Select
className="device-overview-device-select"
2026-08-14 09:02:52 +08:00
placeholder={t('workOrder.selectDeviceFixed2')}
2026-08-03 14:38:28 +08:00
value={selectedDevice?.device_sn || selectedDevice?.serialNumber}
onChange={handleDeviceChange}
size="small"
showSearch
allowClear
optionFilterProp="label"
filterOption={(input, option) =>
String(option?.label || "").toLowerCase().includes(input.toLowerCase())
}
options={[
2026-08-25 16:54:36 +08:00
{ label: <span>{t('devices.robot')}</span>, options: devices.map(item => ({ value: item.device_sn || item.serialNumber, label: item.deviceAlias || item.deviceName || '未知设备' })) },
{ label: <span>{t('constants.uav')}</span>, options: planedevices.map(item => ({ value: item.device_sn, label: item.drone_callsign || item.callsign || '未知设备' })) },
2026-08-03 14:38:28 +08:00
]}
/>
{selectedDevice && (
<Row gutter={8}>
<Col span={12}>
<div className="device-overview-block-12">
<div className="device-overview-device-head">
2026-11-12 09:59:37 +08:00
{String(selectedDevice.deviceType || '').toUpperCase() === 'U' || selectedDevice.deviceName?.includes(t('constants.uav')) || selectedDevice.drone_callsign ? (
<span className="device-overview-device-type-icon"><RocketOutlined /></span>
2026-08-03 14:38:28 +08:00
) : (
<span className="device-overview-device-type-icon"><CarOutlined /></span>
2026-08-03 14:38:28 +08:00
)}
<span className="device-overview-device-name">{selectedDevice.deviceAlias || selectedDevice.drone_callsign || selectedDevice.callsign || selectedDevice.deviceName}</span>
<Tag color={realtimeDevice.status == 1 || realtimeDevice.status == 2 ? "success" : "default"} size="small" className="device-overview-tag-flat">
{realtimeDevice.status == 1 || realtimeDevice.status == 2 ? t('devices.online') : t('devices.offline')}
2026-08-03 14:38:28 +08:00
</Tag>
<Button
type="primary" size="small" ghost icon={<InfoCircleOutlined />}
className="device-overview-detail-btn"
onClick={() => onViewStatus(selectedDevice.device_sn || selectedDevice.serialNumber)}
2026-08-14 09:02:52 +08:00
>{t('common.detail')}</Button>
2026-05-11 11:59:17 +08:00
</div>
<div className="device-overview-stats-row">
<div className="device-overview-stat-cell">
<span className="device-overview-battery-icon"><ThunderboltOutlined /></span>
<span className="device-overview-text-12">{t('devices.batteryLevel')}: {fix2(realtimeDevice?.battery)}%</span>
2026-05-22 15:53:15 +08:00
</div>
2026-08-03 14:38:28 +08:00
{realtimeDevice?.environment_temperature && (
<div className="device-overview-temp-cell">
<span className="device-overview-text-12">{t('home.temperature')}</span>
<span className="device-overview-temp-value">{formatTemperature(Number(realtimeDevice.environment_temperature || 25), 1).label}</span>
2026-08-03 14:38:28 +08:00
</div>
)}
2026-05-11 11:59:17 +08:00
</div>
2026-08-03 14:38:28 +08:00
<div className="device-overview-detail-list">
2026-08-03 14:38:28 +08:00
{selectedDevice.productName && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.productType')}</span>
<span className="device-overview-text-12">{getVal(selectedDevice.productName)}</span>
2026-05-11 14:59:36 +08:00
</div>
2026-08-03 14:38:28 +08:00
)}
<div className="device-overview-detail-row-top">
<span className="device-overview-label-nowrap">{t('systemSetting.fixed2DeviceSn')}</span>
<span className="device-overview-sn-value">
2026-08-03 14:38:28 +08:00
{getVal(selectedDevice.device_sn || selectedDevice.serialNumber)}
</span>
</div>
{selectedDevice.activeTime && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.timeFixed2')}</span>
<span className="device-overview-text-12">{selectedDevice.activeTime}</span>
2026-05-27 15:08:26 +08:00
</div>
2026-08-03 14:38:28 +08:00
)}
{selectedDevice.firmwareVersion && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.firmwareVersion')}</span>
<span className="device-overview-text-12">v{selectedDevice.firmwareVersion}</span>
2026-05-11 14:59:36 +08:00
</div>
2026-08-03 14:38:28 +08:00
)}
{selectedDevice.deviceType && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.deviceType')}</span>
<span className="device-overview-text-12">{selectedDevice.deviceType}</span>
</div>
)}
2026-08-12 11:29:44 +08:00
{(selectedDevice.productName?.includes(t('constants.uav')) || selectedDevice.device_sn) && (
2026-08-03 14:38:28 +08:00
<>
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.flightAltitude')}</span>
<span className="device-overview-text-12">{fix2(realtimeDevice?.height)} m</span>
2026-08-03 14:38:28 +08:00
</div>
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.s21')}</span>
<span className="device-overview-text-12">{fix2(realtimeDevice?.wind_speed)} m/s</span>
2026-08-03 14:38:28 +08:00
</div>
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.rtkQuantityFixed2')}</span>
<span className="device-overview-text-12">
2026-08-03 14:38:28 +08:00
<Badge
showZero={true}
count={realtimeDevice?.position_state?.rtk_number || 0}
className="device-overview-rtk-badge"
2026-08-03 14:38:28 +08:00
/>
</span>
</div>
</>
)}
</div>
2026-05-11 11:59:17 +08:00
<div className="device-overview-action-row">
2026-11-16 14:33:48 +08:00
{/*<Button type="primary" style={{ borderRadius: 8, flex: 1 }} onClick={handleStart}>{t('devices.s23')}</Button>*/}
{/*<Button style={{ borderRadius: 8, flex: 1 }} onClick={handlePause}>{t('video.pause')}</Button>*/}
<Button type="primary" className="device-overview-action-btn" onClick={handleAutoBack}>{t('devices.returnHome')}</Button>
{/*<Button style={{ flex: 1, background: '#52c41a', borderColor: '#52c41a', color: "#fff", borderRadius: 8, }} onClick={handleRecharge}>{t('devices.s24')}</Button>*/}
<Button danger={!eStopActive} type={eStopActive ? 'primary' : 'default'} style={{ flex: 1, borderRadius: 8, background: eStopActive ? '#cf1322' : undefined, borderColor: eStopActive ? '#cf1322' : undefined, color: eStopActive ? '#fff' : undefined }} onClick={handleEmergencyStop}>{eStopActive ? t('devices.estopTriggered') : t('devices.s29')}</Button>
2026-08-03 14:38:28 +08:00
</div>
2026-05-11 11:59:17 +08:00
</div>
2026-08-03 14:38:28 +08:00
</Col>
<Col span={12}>
<div className="device-overview-block-8">
<div className="device-overview-video-head">
<span className="device-overview-video-title">{t('devices.s25')}</span>
2026-09-20 13:58:23 +08:00
{!isUAV && robotPlayActive && (
<div className="device-overview-video-stop">
2026-09-20 13:58:23 +08:00
<Button
size="small"
danger
onClick={() => {
setRobotPlayActive(false);
}}
>{t('devices.fixed2StopFixed2VideoFixed2')}</Button>
</div>
)}
2026-08-03 14:38:28 +08:00
{isUAV && (
<Select
size="small"
className="device-overview-video-source-select"
2026-08-03 14:38:28 +08:00
value={videoSource}
onChange={setVideoSource}
options={[
2026-08-14 09:02:52 +08:00
{ label: t('devices.videoFixed2'), value: 'station' },
{ label: t('devices.droneVideo'), value: 'drone' },
2026-08-03 14:38:28 +08:00
]}
/>
)}
</div>
2026-08-03 14:38:28 +08:00
{/* ✅ 关键:videoDevice 绝不随MQTT更新,视频永不闪烁 */}
<div className="device-overview-video-box">
2026-08-03 14:38:28 +08:00
{isUAV ? (
<DroneVideoPlayer
device={videoDevice}
height={160}
showSourceSelect={false}
videoSource={videoSource}
onSourceChange={setVideoSource}
2026-05-18 17:25:41 +08:00
/>
) : (
2026-08-06 13:39:14 +08:00
robotPlayActive ? (
2026-09-08 15:59:41 +08:00
selectedDevice?.hasHost ? (
<div className="device-overview-video-inner">
2026-09-08 15:59:41 +08:00
<AgrtcRoomRobot CHANNEL={selectedDevice?.serialNumber || ''} />
</div>
) : robotVideo ? (
2026-08-06 13:39:14 +08:00
<VideoPlayer
deviceId={selectedDevice?.device_sn || selectedDevice?.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 className="device-overview-video-loading">{t('video.videoLoading')}</div>
2026-08-06 13:39:14 +08:00
)
2026-08-03 14:38:28 +08:00
) : (
2026-08-06 13:39:14 +08:00
// ========== 未点击播放时:显示播放大按钮 ==========
<div
onClick={() => setRobotPlayActive(true)}
className="device-overview-play-overlay"
2026-08-06 13:39:14 +08:00
>
<div
className="device-overview-play-btn"
2026-08-06 13:39:14 +08:00
>
▶
</div>
2026-08-03 14:38:28 +08:00
</div>
)
)}
</div>
2026-08-06 13:39:14 +08:00
2026-05-11 10:47:51 +08:00
</div>
2026-05-11 11:59:17 +08:00
<div className="device-overview-manual-row">
{/*<Button size="large" style={{ flex: 1, borderRadius: 8 }}>{t('devices.switchManual')}</Button>*/}
2026-08-03 14:38:28 +08:00
</div>
</Col>
</Row>
)}
2026-05-11 15:15:19 +08:00
</Card>
2026-11-12 09:59:37 +08:00
{/*<Card title={<><ApiOutlined />{t('devices.fixed2AiActions')}</>} variant="borderless" style={{ borderRadius: 12, marginBottom: 8 }}>
2026-08-03 14:38:28 +08:00
<Row gutter={16} style={{ marginBottom: 8 }}>
2026-08-14 09:02:52 +08:00
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(255,77,79,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ff4d4f', fontSize: 20 }}><span role="img" aria-label="hotspot">🔥</span></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.hotspotSuspect')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#222' }}>2 <span style={{ fontSize: 12 }}>{t('devices.s32')}</span></div></div></div></Col>
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(82,196,26,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#52c41a', fontSize: 16 }}><BranchesOutlined /></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.s33')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#222' }}>3 <span style={{ fontSize: 12 }}>{t('devices.s34')}</span></div></div></div></Col>
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(24,144,255,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#1890ff', fontSize: 16 }}><CloudOutlined /></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.s35')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#222' }}>4 <span style={{ fontSize: 12 }}>{t('devices.s34')}</span></div></div></div></Col>
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(255,77,79,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ff4d4f', fontSize: 16 }}><WarningOutlined /></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.fenceAbnormal')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#ff4d4f' }}>1 <span style={{ fontSize: 12 }}>{t('devices.s32')}</span></div></div></div></Col>
2026-08-03 14:38:28 +08:00
</Row>
<Row gutter={16}>
<Col span={14}>
<div style={{ marginBottom: 12 }}>
2026-08-14 09:02:52 +08:00
<div style={{ fontSize: 16, fontWeight: 600, color: '#1890ff', marginBottom: 8 }}>{t('devices.suggestAction')}</div>
2026-08-03 14:38:28 +08:00
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, padding: '4px', borderRadius: 12, border: '1px solid #e8e8e8' }}>
2026-08-14 09:02:52 +08:00
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ color: '#1890ff' }}>⦿</span><span style={{ fontSize: 16 }}>{t('devices.executeFixed2InspectionP03')}</span></div><ArrowRightOutlined style={{ color: '#666' }} /></div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ color: '#1890ff' }}>⦿</span><span style={{ fontSize: 16 }}>{t('devices.taskSuspended2G02')}</span></div><ArrowRightOutlined style={{ color: '#666' }} /></div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ color: '#1890ff' }}>⦿</span><span style={{ fontSize: 16 }}>{t('devices.generateCleaningOrderFixed2')}</span></div><ArrowRightOutlined style={{ color: '#666' }} /></div>
2026-08-03 14:38:28 +08:00
</div>
2026-05-14 15:15:50 +08:00
</div>
2026-05-11 15:15:19 +08:00
</Col>
2026-08-03 14:38:28 +08:00
<Col span={10}>
<div style={{ display: 'flex', flexDirection: 'column', paddingBottom: "12px", gap: 16, height: '100%', justifyContent: "end" }}>
<div style={{ display: 'flex', gap: 12, flexWrap: "wrap" }}>
2026-08-14 09:02:52 +08:00
<Button type="primary" size="middle" style={{ flex: 1, borderRadius: 8, fontSize: 14 }}>{t('devices.generateTask')}</Button>
<Button size="middle" style={{ flex: 1, borderRadius: 8, fontSize: 14, border: '1px solid #1890ff', color: '#1890ff' }}>{t('devices.aiOptimizePath')}</Button>
2026-08-03 14:38:28 +08:00
</div>
2026-08-14 09:02:52 +08:00
<Button type="primary" size="middle" style={{ borderRadius: 8, fontSize: 14 }}>{t('devices.s43')}</Button>
2026-05-14 15:15:50 +08:00
</div>
2026-05-11 15:15:19 +08:00
</Col>
</Row>
2026-11-12 09:59:37 +08:00
</Card>*/}
2026-06-12 17:34:35 +08:00
2026-08-12 11:29:44 +08:00
{(selectedDevice?.productName?.includes(t('constants.uav')) || selectedDevice?.device_sn) && (
<Card title={t('devices.s60')} variant="borderless" className="device-overview-weather-card">
<div className="device-overview-weather-body">
<div className="device-overview-weather-grid">
<div className="device-overview-weather-cell"><div className="device-overview-weather-cell-label">{t('devices.s44')}</div><div className="device-overview-weather-cell-value">{fix2(realtimeDevice?.wind_speed)} m/s</div></div>
<div className="device-overview-weather-cell"><div className="device-overview-weather-cell-label">{t('home.temperature')}</div><div className="device-overview-weather-cell-value">{formatTemperature(Number(realtimeDevice?.environment_temperature || 0), 1).label}</div></div>
<div className="device-overview-weather-cell"><div className="device-overview-weather-cell-label">{t('devices.rainfall')}</div><div className="device-overview-weather-cell-value">{getVal(realtimeDevice?.rainfall)}</div></div>
<div className="device-overview-weather-cell-last"><div className="device-overview-weather-cell-label">RTK</div><div className="device-overview-weather-cell-value-good">{realtimeDevice?.position_state?.is_fixed === 'fixing_successful' ? '固定' : '未固定'}</div></div>
2026-08-03 14:38:28 +08:00
</div>
<div className="device-overview-weather-good">
2026-08-03 14:38:28 +08:00
<div className="flex items-center gap-1">
<div className="device-overview-weather-good-title">{t('devices.suitableExec')}</div>
<div className="device-overview-weather-good-icon"><CheckCircleOutlined className="device-overview-weather-good-icon-mark" /></div>
2026-08-03 14:38:28 +08:00
</div>
<div className="device-overview-weather-good-sub">{t('devices.normal')}</div>
2026-08-03 14:38:28 +08:00
</div>
</div>
</Card>
)}
2026-08-12 11:29:44 +08:00
{(!selectedDevice?.productName?.includes(t('constants.uav')) && !selectedDevice?.device_sn) && (
<Card title={<div className="device-overview-robot-title"><RobotOutlined className="device-overview-robot-title-icon" />{t('devices.fixed2RobotStatusFixed2')}</div>} variant="borderless" className="device-overview-robot-card">
<Row gutter={16} className="device-overview-robot-stats">
2026-08-03 14:38:28 +08:00
<Col span={8}>
<div className="device-overview-robot-stat"
2026-08-03 14:38:28 +08:00
onMouseEnter={e => {
e.currentTarget.style.background = '#E8F3FF';
e.currentTarget.style.borderColor = '#165DFF';
}}
onMouseLeave={e => {
e.currentTarget.style.background = '#F7F8FA';
e.currentTarget.style.borderColor = 'transparent';
}}
>
<Statistic className="device-overview-robot-statistic"
title={<span className="device-overview-robot-stat-title">{t('devices.statTotalDistance')}(m)</span>}
2026-08-03 14:38:28 +08:00
value={deviceStatistics?.distance ? Number(deviceStatistics.distance).toFixed(2) : Number(deviceStatistics?.workArea / 0.7 || 0).toFixed(2)}
2026-11-16 14:33:48 +08:00
suffix=""
2026-08-03 14:38:28 +08:00
/>
</div>
</Col>
<Col span={8}>
<div className="device-overview-robot-stat"
2026-08-03 14:38:28 +08:00
onMouseEnter={e => {
e.currentTarget.style.background = '#E8F3FF';
e.currentTarget.style.borderColor = '#165DFF';
}}
onMouseLeave={e => {
e.currentTarget.style.background = '#F7F8FA';
e.currentTarget.style.borderColor = 'transparent';
}}
>
<Statistic className="device-overview-robot-statistic"
title={<span className="device-overview-robot-stat-title">{t('devices.s50')}(㎡)</span>}
2026-08-03 14:38:28 +08:00
value={Number(deviceStatistics?.workArea || 0).toFixed(2)}
2026-11-16 14:33:48 +08:00
suffix=""
2026-08-03 14:38:28 +08:00
/>
</div>
</Col>
<Col span={8}>
<div className="device-overview-robot-stat"
2026-08-03 14:38:28 +08:00
onMouseEnter={e => {
e.currentTarget.style.background = '#E8F3FF';
e.currentTarget.style.borderColor = '#165DFF';
}}
onMouseLeave={e => {
e.currentTarget.style.background = '#F7F8FA';
e.currentTarget.style.borderColor = 'transparent';
}}
>
<Statistic
className="device-overview-robot-statistic"
title={
<span className="device-overview-robot-stat-title">
{t('devices.s51')}
</span>
}
value={formatTime(deviceStatistics?.time)}
2026-11-16 14:33:48 +08:00
suffix=""
2026-08-03 14:38:28 +08:00
/>
</div>
</Col>
</Row>
</Card>
)}
2026-06-12 17:34:35 +08:00
<Card title={<><ClockCircleOutlined />{t('devices.fixed2TaskSuspended2Fixed2ExecutionTime')}</>} variant="borderless" className="device-overview-schedule-card" extra={<div className="device-overview-schedule-extra"></div>}>
2026-11-12 09:59:37 +08:00
{taskPoolList.length > 0 ? (
<Timeline mode="left">
{taskPoolList.map((item, idx) => (
<Timeline.Item key={idx} color={item.color} label={<div className="device-overview-timeline-label">{item.time}</div>}>
<div className="device-overview-text-13">{item.text}</div>
<div className="device-overview-timeline-label">{item.status}</div>
2026-11-12 09:59:37 +08:00
</Timeline.Item>
))}
</Timeline>
) : (
<Empty description={t('common.noData')} className="device-overview-empty" />
2026-11-12 09:59:37 +08:00
)}
<div className="device-overview-more-12"><Button type="link" onClick={() => navigate('/devices/robotTask')}>{t('devices.viewMore')}</Button></div>
2026-08-03 14:38:28 +08:00
</Card>
</Col>
</Row>
{/* 机器人编辑别名弹窗 */}
<Modal
2026-08-14 09:02:52 +08:00
title={t('devices.fixed2EditFixed2RobotFixed2DeviceFixed2InfoFixed2')}
2026-08-03 14:38:28 +08:00
open={editRobotModalOpen}
onCancel={() => setEditRobotModalOpen(false)}
confirmLoading={editLoading}
onOk={handleSaveRobotAlias}
maskClosable={false}
>
{currentEditRobot && (
<div className="device-overview-edit-body">
<div className="device-overview-edit-row">
2026-08-14 09:02:52 +08:00
<Typography.Text strong>{t('devices.fixed2Fixed2DeviceSn')}</Typography.Text>
2026-08-03 14:38:28 +08:00
<Typography.Text copyable>
{currentEditRobot.device_sn || currentEditRobot.serialNumber}
</Typography.Text>
</div>
<div className="device-overview-edit-row">
2026-08-14 09:02:52 +08:00
<Typography.Text strong>{t('devices.fixed2DeviceType')}</Typography.Text>
2026-08-12 11:29:44 +08:00
<Typography.Text>{currentEditRobot.productName || t('constants.locationUnknown')}</Typography.Text>
2026-08-03 14:38:28 +08:00
</div>
<div className="device-overview-block-8">
<Typography.Text strong>{t('devices.fixed2Device')}<span className="device-overview-required-mark">*</span></Typography.Text>
2026-08-03 14:38:28 +08:00
</div>
<Input
value={editAliasInput}
onChange={e => setEditAliasInput(e.target.value)}
2026-08-14 09:02:52 +08:00
placeholder={t('devices.fixed2PleaseEnterDevice')}
2026-08-03 14:38:28 +08:00
maxLength={30}
allowClear
/>
<div className="device-overview-edit-hint">{t('devices.deviceListControlDeviceFixed2')}</div>
2026-08-03 14:38:28 +08:00
</div>
)}
</Modal>
2026-06-12 17:34:35 +08:00
{/* 设备参数查看与修改弹窗(通用组件) */}
<DeviceParamModal
open={paramModalOpen}
device={currentParamDevice}
onCancel={() => {
setParamModalOpen(false);
setCurrentParamDevice(null);
}}
onSuccess={() => {
fetchAllData();
}}
/>
2026-08-03 14:38:28 +08:00
</Content>
</div>
2026-05-11 10:47:51 +08:00
);
}