import React, { useState, useEffect, useRef, useMemo } from 'react'; import { Layout, Card, Row, Col, Statistic, Tag, Button, Table, Typography, Space, Progress, Badge, Timeline, message, Select, Modal, Space as AntSpace } from 'antd'; import { EnvironmentOutlined, RobotOutlined, BranchesOutlined, ThunderboltOutlined, CheckCircleOutlined, PauseOutlined, RocketOutlined, SyncOutlined, WarningOutlined, CloudOutlined, ClockCircleOutlined, ReloadOutlined, AimOutlined, ApiOutlined, SettingOutlined, PlusOutlined, ArrowRightOutlined, EditOutlined, FullscreenOutlined, InfoCircleOutlined, CarOutlined } from '@ant-design/icons'; import DroneLivePlayer from '../VolcRtcPlayer.jsx'; import DroneVideoPlayer from './DroneVideoPlayer'; import AgoraTextTest from '../AgoraRtc.tsx'; import { useWebRTCPlayer } from '../useWebRTCStream.tsx'; import VideoPlayer from '../VideoPlayer.tsx.tsx'; import CesiumMap from '../Map.jsx'; import { getUAVState, getSiteDevice, getSiteUAVList } from '@/api/device.ts'; import { useMqtt } from '@/hooks/useMqtt'; import envConfig from '../../../env'; import { useSelector } from 'react-redux'; import { RootState } from '@/store'; const { Content } = Layout; const { Text, Title } = Typography; const taskTimeline = [ { time: '10:24:18', color: 'blue', text: 'UAV-C01 开始执行清洗航线 C-05', status: '任务开始' }, { time: '10:21:35', color: 'orange', text: 'RBT-01 开始执行巡检航线 P-02', status: '任务开始' }, { time: '10:18:02', color: 'green', text: 'GR-02 开始除草作业 G-01', status: '任务开始' }, { time: '10:15:47', color: 'gray', text: 'UAV-C02 任务待命就绪', status: '待命就绪' }, { time: '10:12:33', color: 'blue', text: 'UAV-C01 再次返机补水', status: '返机补给' }, { time: '09:58:10', color: 'green', text: 'RBT-02 完成巡检航线 P-01', status: '任务完成' }, ]; const logs = [ { time: '10:24:35', device: 'UAV-C01', type: '命令', desc: '起飞指令下发,开始作业' }, { time: '10:21:40', device: 'RBT-01', type: '命令', desc: '开始巡检任务 P-02' }, { time: '10:20:11', device: 'UAV-C02', type: '命令', desc: '转入待命状态' }, { time: '10:18:05', device: 'GR-02', type: '命令', desc: '除草作业开始 G-01' }, { time: '10:12:35', device: 'UAV-C01', type: '告警', desc: '返航补水' }, { time: '10:05:22', device: 'RBT-01', type: '事件', desc: '电量较低,建议回充', level: '低电量' }, ]; export default function DeviceOverviewPage({ onViewStatus, selectedSn, onDeviceSelect }) { const { userInfo } = useSelector((state: RootState) => state.user); const { stationId } = useSelector((state: RootState) => state.station); const [zoomedVideo, setZoomedVideo] = useState(null); const [mowerView, setMowerView] = useState('front'); const [videoSource, setVideoSource] = useState('drone'); 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([]); // 获取数据 const fetchAllData = async () => { if (!stationId) return; try { // 1. 同时发请求 const [deviceRes, planeRes] = await Promise.all([ getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1 }), 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 || '无人机', })); setDevices(devData); setPlaneDevices(planeData); // 合并所有设备 const all = [...devData, ...planeData]; setDevicesAll(all); } catch (err) { console.error('数据请求失败', err); } }; useEffect(() => { fetchAllData(); }, [userInfo, stationId]); // 当前选中设备(切换时才变) const selectedDevice = useMemo(() => { const sn = selectedSn || (devicesAll?.[0]?.device_sn || devicesAll?.[0]?.serialNumber); return devicesAll?.find(item => (item.device_sn || item.serialNumber) === sn) || null; }, [devicesAll, selectedSn]); const isUAV = !!selectedDevice?.gateway_sn; // ======================== 核心优化:视频用设备对象(绝不随MQTT刷新)======================== const videoDevice = useMemo(() => { if (!selectedDevice) return null; return { ...selectedDevice }; }, [selectedDevice]); // 只有切设备才变 → 视频不闪 // ======================== UI显示用(MQTT实时更新)======================== const realtimeDevice = useMemo(() => { if (!selectedDevice) return null; return { ...selectedDevice, ...uavState, ...persistentHostData, ...persistentDroneData, }; }, [selectedDevice, uavState, persistentHostData, persistentDroneData?.wind_speed]); console.log('实时设备数据:', realtimeDevice); // MQTT消息处理 const handleMqttMessage = (topic, message) => { console.log('DeviceOverviewPage MQTT Topic:', topic); console.log('DeviceOverviewPage MQTT Message:', message); console.log('实时设备数据:', realtimeDevice); try { const parsed = JSON.parse(message); console.log('MQTT解析结果:', parsed); 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`); } console.log('DeviceOverviewPage 订阅的MQTT主题:', topics); return topics; }, [selectedDevice]); useMqtt({ url: envConfig.mqtt_url, topic: mqttTopics, onMessage: handleMqttMessage, }); // 机器人视频 const { video: robotVideo, error, ready } = useWebRTCPlayer( !isUAV ? selectedDevice?.serialNumber || '' : '', `webrtc://1.95.137.212/live/livestream/${selectedDevice?.serialNumber}`, ); // 顶部统计卡片 const dynamicTopCards = useMemo(() => { const totalDrones = planedevices?.length || 0; const onlineDrones = planedevices?.filter(d => d.onlineStatus === 1).length || 0; const totalRobots = devicesAll?.filter(d => d.productName?.includes('巡检')).length || 0; const activeRobots = devicesAll?.filter(d => d.productName?.includes('巡检') && d.onlineStatus === 1).length || 0; const totalMowers = devicesAll?.filter(d => d.productName?.includes('割草机')).length || 0; const activeMowers = devicesAll?.filter(d => d.productName?.includes('割草机') && d.onlineStatus === 1).length || 0; const washDroneStandby = planedevices?.filter(d => d.productName?.includes('清洗') && d.onlineStatus === 1).length || 0; return [ { title: '无人机机场状态', icon: , value: `${onlineDrones} / ${totalDrones}`, sub: `可调度 ${onlineDrones} 架`, color: '#1890ff' }, { title: '机器人', icon: , value: `${totalMowers} 台`, sub: `作业中 ${activeMowers}`, color: '#13c2c2' }, { title: '无人机', icon: , value: `${totalDrones} 架`, sub: `待命 ${washDroneStandby}`, color: '#eb2f96' }, { title: '设备平均电量', icon: , value: '86%', sub: '', color: '#52c41a' }, { title: '今日任务执行', icon: , value: '12 / 15', sub: '完成率 80%', color: '#2f54eb' }, ]; }, [devicesAll, planedevices]); // 设备调度列表 const dynamicScheduleList = useMemo(() => { return devicesAll?.map((d, index) => ({ id: d.deviceId || index, name: d.deviceAlias || d.deviceName || d.callsign || '未知设备', type: d.productName || '未知类型', status: d.onlineStatus === 1 ? '在线' : '离线', mode: d.status === 4 ? '待命' : '作业中', capacity_percent: d.capacity_percent || 100, position: d.position || '站内', task: d.status === 4 ? '待命' : '作业中', comm: d.rssi ? `${d.rssi}dBm` : '良好' })) || []; }, [devicesAll]); const handleStart = () => message.success('任务已启动'); const handlePause = () => message.info('任务已暂停'); const handleReturn = () => message.info('返航指令已下发'); const handleRecharge = () => message.info('回充指令已下发'); const handleEmergencyStop = () => message.error('已触发急停!'); const fix2 = (val) => { if (val === null || val === undefined || isNaN(val)) return '-'; return Number(val).toFixed(2); }; const getVal = (val) => val == "no_rain" ? "无" : (val || '-'); const handleDeviceChange = (id) => { if (onDeviceSelect) onDeviceSelect(id); }; // 获取无人机状态 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); } catch (err) { console.error('获取无人机状态失败', err); } } else { setUavState(null); } }; fetchUavState(); }, [isUAV, selectedDevice]); return ( {dynamicTopCards.map((card, idx) => (
{card.icon}
{card.title}
{card.value}
{card.sub &&
{card.sub}
}
))}
装备协同态势图} extra={