diff --git a/src/components/Map.jsx b/src/components/Map.jsx index c728e5c..2de7482 100644 --- a/src/components/Map.jsx +++ b/src/components/Map.jsx @@ -609,9 +609,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, `; } else { tooltip.innerHTML = ` -
📍 ${t('systemSetting.longitude')}:${lonStr}
-
${t('systemSetting.latitude')}:${latStr}
- `; +
📍 ${t('systemSetting.longitude')}:${lonStr}
+
${t('systemSetting.latitude')}:${latStr}
+ `; } } @@ -1665,16 +1665,17 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, handler.setInputAction((movement) => { const picked = viewer.scene.pick(movement.endPosition); const pickedRobot = (window.Cesium.defined(picked) && picked.id?.properties?.robot) ? picked.id.properties.robot.getValue() : null; - const { lon, lat } = getCursorLngLat(viewer, movement.endPosition); - if (window.Cesium.defined(lon) && Number.isFinite(lon)) { + + // ✅ 只有拾取到设备实体,才显示tooltip,空白区域直接隐藏 + if (pickedRobot) { + const { lon, lat } = getCursorLngLat(viewer, movement.endPosition); showCoordinateTooltip(tooltipRef.current, movement.endPosition, t, lon, lat, pickedRobot); - } else if (pickedRobot) { - showCoordinateTooltip(tooltipRef.current, movement.endPosition, t, NaN, NaN, pickedRobot); } else { tooltipRef.current.style.display = "none"; } }, window.Cesium.ScreenSpaceEventType.MOUSE_MOVE); + handler.setInputAction((movement) => { const picked = viewer.scene.pick(movement.position); if (window.Cesium.defined(picked) && picked.id?.properties?.robot) { diff --git a/src/components/devices/DeviceStatusPage.tsx b/src/components/devices/DeviceStatusPage.tsx index db173e6..2495b94 100644 --- a/src/components/devices/DeviceStatusPage.tsx +++ b/src/components/devices/DeviceStatusPage.tsx @@ -606,7 +606,6 @@ export default function DeviceStatusPage() { longitude: lng, latitude: lat, }, - // 让地图取最新经纬度 longitude: lng, latitude: lat, name: device?.deviceAlias || device?.callsign || device?.deviceName || t('devices.device'), diff --git a/src/components/devices/deviceController.js b/src/components/devices/deviceController.js index 6f39de1..ad70d1f 100644 --- a/src/components/devices/deviceController.js +++ b/src/components/devices/deviceController.js @@ -67,6 +67,16 @@ export default class DeviceController { wsManager.close(); } + disconnect() { + console.log('DeviceController disconnect: 断开 WebSocket'); + wsManager.close(); + this.connectedDeviceSn = null; + this.currentDevice = null; + this.wsDeviceInfo = {}; + this.locationInfo = {}; + this.isControlled = false; + this.onControlStatusChange?.(false); + } handleVisibilityChange() { if (document.visibilityState === 'hidden') { diff --git a/src/locales/en/index.ts b/src/locales/en/index.ts index dbcc216..4e671d8 100644 --- a/src/locales/en/index.ts +++ b/src/locales/en/index.ts @@ -93,6 +93,10 @@ const en = { requestError: 'Request Error', settings: 'Settings', storeValue: 'Store Value', + action: 'Action', + locate: 'Locate', + minutes: 'min', + totalCount: 'Total {{count}}', submitFail: 'Submit Fail', timeRange: 'Time Range', working: 'Working', @@ -170,6 +174,9 @@ const en = { ambientTemperature: 'Ambient Temperature', current: 'Current', currentIrradiance: 'Current Irradiance', + charge: 'Battery', + model: 'Model', + ratPower: 'Rated Power', frequency: 'Frequency', gridConnected: 'Grid Connected', gridConnection: 'Grid Connection', @@ -371,6 +378,36 @@ const en = { networkLatency: 'Network Latency', waterRiskWarning: 'Warning: Water accumulation risk in Area B, avoid it', presetRoutes: 'Preset Routes', + all: 'All', + stop: 'Stop', + currentTask: 'Current Task', + realtimePosition: 'Real-time Position', + taskCompleted: 'Task completed', + deviceSerialNumberMissing: 'Device serial number missing', + confirmExecuteRoute: 'Confirm to execute this route?', + targetDevice: 'Target Device', + routePointCount: 'Route points', + taskExecuteFailed: 'Task execution failed', + taskPauseAbnormal: 'Task pause abnormal', + areYouSureCancelTask: 'Are you sure to cancel the task?', + taskCancelled: 'Task cancelled', + taskCancelAbnormal: 'Failed to cancel the task', + taskStatusNew: 'Pending', + taskStatusExecuting: 'Executing', + taskStatusPause: 'Paused', + taskStatusFinish: 'Finished', + taskStatusCancel: 'Cancelled', + unnamedTask: 'Unnamed Task', + planId: 'Plan ID', + expectedComplete: 'Expected completion', + noCurrentTask: 'No current task', + searchRoute: 'Search route', + noRouteTip: 'No preset routes', + pointCount: 'Point count', + deviceInfo: 'Device Info', + deviceCode: 'Device Code', + siteBelonging: 'Site', + deviceLocation: 'Device location', searchPlaceholder: 'Search...', unnamedRoute: 'Unnamed Route', deleteRoute: 'Delete Route', @@ -3604,6 +3641,13 @@ const en = { fixed2Offline3: ' Offline 3', powerCurveFixed2: 'Real-time power curve', + viewDeviceDetailAndTask: 'View device detail and task', + showAllDevices: 'Show All Devices', + showOnlySelected: 'Show Selected Only', + clickDeviceOnMapTip: 'Click a device on the map to locate and view details', + focusingDevice: 'Locating device: {{name}}', + foundDevices: 'Found {{count}} devices', + gridNorm: 'Grid Normal', s11: 'today', diff --git a/src/locales/zh/index.ts b/src/locales/zh/index.ts index 476c3dc..3bc4fbc 100644 --- a/src/locales/zh/index.ts +++ b/src/locales/zh/index.ts @@ -97,6 +97,10 @@ const zh = { requestError: '请求错误', settings: '设置', storeValue: '存储值', + action: '操作', + locate: '定位', + minutes: '分钟', + totalCount: '共 {{count}} 台', submitFail: '提交失败', timeRange: '时间范围', working: '作业中', @@ -174,6 +178,9 @@ const zh = { ambientTemperature: '环境温度', current: '当前', currentIrradiance: '当前辐照度', + charge: '电量', + model: '型号', + ratPower: '额定功率', frequency: '频率', gridConnected: '电网已连接', gridConnection: '电网连接', @@ -386,6 +393,36 @@ const zh = { networkLatency: '网络延迟', waterRiskWarning: '注意:区域 B 存在积水风险,建议避开', presetRoutes: '预设路线', + all: '全部', + stop: '停止', + currentTask: '当前任务', + realtimePosition: '实时位置', + taskCompleted: '任务已完成', + deviceSerialNumberMissing: '设备序列号缺失', + confirmExecuteRoute: '确认执行该路线?', + targetDevice: '目标设备', + routePointCount: '路径点数', + taskExecuteFailed: '任务执行失败', + taskPauseAbnormal: '任务暂停异常', + areYouSureCancelTask: '确定要取消任务?', + taskCancelled: '任务已取消', + taskCancelAbnormal: '任务取消失败', + taskStatusNew: '待执行', + taskStatusExecuting: '执行中', + taskStatusPause: '已暂停', + taskStatusFinish: '已完成', + taskStatusCancel: '已取消', + unnamedTask: '未命名任务', + planId: '任务ID', + expectedComplete: '预计完成', + noCurrentTask: '暂无当前任务', + searchRoute: '搜索路径', + noRouteTip: '暂无预设路径', + pointCount: '路径点数', + deviceInfo: '设备信息', + deviceCode: '设备编码', + siteBelonging: '所属场站', + deviceLocation: '设备位置', searchPlaceholder: '搜索...', unnamedRoute: '未命名路线', deleteRoute: '删除航线', @@ -555,7 +592,7 @@ const zh = { equipmentSituationMap: '设备态势地图', execTimePoint: '执行时间点', executeDeviceColon: '执行设备', - executeNow: '执行现在', + executeNow: '执行', executeWayline: '执行航线', executeWaylineTask: '执行航线任务', executingTasks: '执行中任务', @@ -3653,6 +3690,13 @@ const zh = { fixed2Offline3: '离线 3', powerCurveFixed2: '实时功率曲线', + viewDeviceDetailAndTask: '查看设备详情与任务', + showAllDevices: '显示全部设备', + showOnlySelected: '仅显示选中设备', + clickDeviceOnMapTip: '点击地图上的设备可定位并查看详情', + focusingDevice: '正在定位设备:{{name}}', + foundDevices: '已找到 {{count}} 台设备', + gridNorm: '并网正常', s11: '今天', diff --git a/src/pages/RealTimeMonitor.tsx b/src/pages/RealTimeMonitor.tsx index 7c75332..1600b2c 100644 --- a/src/pages/RealTimeMonitor.tsx +++ b/src/pages/RealTimeMonitor.tsx @@ -1,7 +1,10 @@ -import React, { useState } from 'react'; +import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react'; import { Card, Row, Col, Table, Select, Input, Tag, - Typography, Button, Space, Avatar, Pagination + Typography, Button, Space, Avatar, Pagination, + Modal, Drawer, List, Badge, Empty, App, Tooltip, + Progress, Divider, Radio, Tabs, DatePicker, message, + Form, Switch, Alert, Descriptions, Statistic, Spin, Segmented, InputNumber } from 'antd'; import { CloudOutlined, CheckCircleOutlined, WarningOutlined, @@ -10,7 +13,12 @@ import { VideoCameraOutlined, RocketOutlined, AppstoreOutlined, RobotOutlined, BranchesOutlined, ExperimentOutlined, SearchOutlined, MoreOutlined, ArrowRightOutlined, - FullscreenOutlined, SyncOutlined + FullscreenOutlined, SyncOutlined, PlayCircleOutlined, + PauseCircleOutlined, StopOutlined, InfoCircleOutlined, + ClockCircleOutlined, EnvironmentOutlined, PlusOutlined, + SettingOutlined, ExclamationCircleOutlined, FileTextOutlined, + DeleteOutlined, AimOutlined, SendOutlined, LockOutlined, + NodeIndexOutlined, SaveOutlined, MaximizeOutlined, ReloadOutlined } from '@ant-design/icons'; import { Line, Bar, Pie } from '@ant-design/charts'; import bgMain from '../assets/images/bgmain.jpg'; @@ -18,13 +26,24 @@ import { UniversalBarChart, UniversalLineChart, UniversalPieChart } from '../com import CesiumMap from '../components/Map'; import { useTranslation } from 'react-i18next'; import { useSelector } from 'react-redux'; +import dayjs from 'dayjs'; +import envConfig from '../../env'; +import { useMqtt } from '../hooks/useMqtt'; +import DeviceController from '../components/devices/deviceController'; + +import { + getSiteDevice, getRobotRouteList, + getDeviceTastPool, getSiteDeviceTaskHistory, + excuetRoute, cancelRoute, pauseRoute, recoverRoute, + getRouteByTask, getTaskPath, + getSiteUAVList, getWayLine, createWaylineTask, getUAVState, + postFlightCommmand, getFlightTaskDetail +} from '../api/device'; const { Option } = Select; const { Search } = Input; const { Text, Title } = Typography; - -// 模拟数据扩展 - +const { RangePicker } = DatePicker; const powerTrendData = [ { time: '00:00', value: 0, type: '实时功率' }, @@ -46,153 +65,965 @@ const inverterPowerData = [ const heatmapColors = ['#52c41a', '#1890ff', '#faad14', '#1890ff', '#52c41a']; +const taskStatusColor = (status) => { + const map = { + 'NEW': '#1677ff', + 'EXECUTING': '#52c41a', + 'PAUSE': '#faad14', + 'FINISH': '#13c2c2', + 'CANCEL': '#999', + 'ERROR': '#f5222d' + }; + return map[status] || '#999'; +}; + +const getDeviceTypeIcon = (type) => { + if (type?.includes?.('ROBOT') || type?.includes?.('CLEANING') || type?.includes?.('INSPECT')) { + return ; + } + if (type?.includes?.('DRONE') || type?.includes?.('UAV')) { + return ; + } + if (type?.includes?.('CAMERA')) { + return ; + } + if (type?.includes?.('INVERTER') || type?.includes?.('INV')) { + return ; + } + if (type?.includes?.('COMBINER') || type?.includes?.('CMB')) { + return ; + } + return ; +}; + const RealTimeMonitorPage = () => { const { t } = useTranslation(); - const { currentStation } = useSelector((state: any) => state.station); + const { modal } = App.useApp(); + const { stationId, currentStation } = useSelector((state: any) => state.station); + const { userInfo } = useSelector((state: any) => state.user); + const [filterStatus, setFilterStatus] = useState('all'); - const [filterType, setFilterType] = useState(undefined); + const [filterType, setFilterType] = useState('all'); const [searchName, setSearchName] = useState(''); + const [mapViewMode, setMapViewMode] = useState('all'); const cardStyle = { borderRadius: 12, border: '1px solid #f0f0f0', boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }; + // ========= 设备/任务/路径基础数据 ========= + const [devices, setDevices] = useState([]); + const [loading, setLoading] = useState(false); + const [taskPoolList, setTaskPoolList] = useState([]); + + const [routeList, setRouteList] = useState([]); + const [refreshKey, setRefreshKey] = useState(0); + + const [planeDevices, setPlaneDevices] = useState([]); + const [listPage, setListPage] = useState(1); + const [listPageSize, setListPageSize] = useState(8); + + // ========= WebSocket + 地图交互相关 ========= + const controllerRef = useRef(null); + const isFirstConnect = useRef(true); + const [focusLocation, setFocusLocation] = useState(null); + const [execute, setExecute] = useState(false); + const [excuteStatus, setExcuteStatus] = useState('stop'); + const [points, setPoints] = useState([]); + const [polyPoints, setPolyPoints] = useState([]); + const [routeMode, setRouteMode] = useState(''); + const [clearNavLine, setClearNavLine] = useState(0); + const [clearPlanLine, setClearPlanLine] = useState(0); + const [arrivedPoint, setArrivedPoint] = useState(null); + const [robotRealtimePosition, setRobotRealtimePosition] = useState(null); + const runningRealtimePosition = useMemo(() => { + return { + lon: robotRealtimePosition?.longitude || robotRealtimePosition?.lon || 0, + lat: robotRealtimePosition?.latitude || robotRealtimePosition?.lat || 0, + heading: robotRealtimePosition?.yaw || robotRealtimePosition?.heading || 0, + }; + }, [robotRealtimePosition]); + const [runningPoolTask, setRunningPoolTask] = useState(null); + + // ========= UI 状态 ========= + const [selectedDevice, setSelectedDevice] = useState(null); + const [selectedDeviceSn, setSelectedDeviceSn] = useState(null); + const [deviceDrawerOpen, setDeviceDrawerOpen] = useState(false); + const [routeSearch, setRouteSearch] = useState(''); + + const [waylineList, setWaylineList] = useState([]); + const [waylineSearch, setWaylineSearch] = useState(''); + const [selectedWayline, setSelectedWayline] = useState(null); + const [rthModalVisible, setRthModalVisible] = useState(false); + const [tempRthAltitude, setTempRthAltitude] = useState(100); + const [waylineLoading, setWaylineLoading] = useState(false); + const [mqttDrone, setMqttDrone] = useState(null); + const [droneMqttMap, setDroneMqttMap] = useState({}); + const [activeDroneTask, setActiveDroneTask] = useState(null); + const [droneReturningHome, setDroneReturningHome] = useState(false); + const [droneTaskPaused, setDroneTaskPaused] = useState(false); + const [droneCommandLoading, setDroneCommandLoading] = useState(false); + + const [messageApi, contextHolder] = message.useMessage(); + + + // ============================================================ + // DeviceController 初始化(仅一次) + // ============================================================ + useEffect(() => { + if (!userInfo) return; + const controller = new DeviceController(userInfo, messageApi); + + controller.onLocationInfoUpdate = (pos) => { + setRobotRealtimePosition(pos); + }; + + controller.onRoutePost = (msg) => { + console.log('[RTMonitor] route_post:', msg); + const { taskId, data } = msg; + const matchedTask = taskPoolList.find(task => String(task.id) === String(taskId)); + const sameAsSelected = runningPoolTask && String(runningPoolTask.id) === String(taskId); + if ((!runningPoolTask && matchedTask) || sameAsSelected) { + if (!runningPoolTask && matchedTask) setRunningPoolTask(matchedTask); + if (data) setPoints(data); + loadTaskPath(taskId); + } + }; + + controller.init(); + controllerRef.current = controller; + + return () => { + if (controllerRef.current) { + controllerRef.current.destroy?.(); + } + controllerRef.current = null; + }; + // eslint-disable-next-line + }, []); + + // ============================================================ + // 拉取基础数据 + // ============================================================ + const fetchAllData = async () => { + if (!stationId) return; + setLoading(true); + try { + const [deviceRes, routeRes, planeRes] = await Promise.all([ + getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1, orgId: currentStation?.orgId }), + getRobotRouteList({ siteId: stationId }), + getSiteUAVList(stationId).catch(() => null) + ]); + if (deviceRes?.code === 200) setDevices(deviceRes.rows || []); + if (routeRes?.code === 200) setRouteList(routeRes.data || []); + if (planeRes?.code === 200) setPlaneDevices(planeRes.rows || []); + } catch (err) { + console.error('[RTMonitor] 拉取监控数据失败', err); + } finally { + setLoading(false); + } + }; + + const fetchTaskPoolList = async (deviceId = null) => { + if (!stationId) return []; + try { + const params = { userId: userInfo?.userId, siteId: stationId, orgId: currentStation?.orgId, pageNum: 1, pageSize: 999999 }; + if (deviceId) params.deviceId = deviceId; + const res = await getDeviceTastPool(params); + if (res.code === 200) { + const rows = res.rows || []; + + setTaskPoolList(rows); + return rows; + } + } catch (err) { console.error('[RTMonitor] 拉取任务池失败:', err); } + return []; + }; + + + // 加载任务路径并显示在地图 + const loadTaskPath = async (taskId) => { + if (!taskId) return; + try { + const res = await getRouteByTask({ taskId }); + if (res?.code === 200 && res?.data) { + const data = res.data; + let pathPoints = []; + try { + pathPoints = data.jsonData?.path || []; + setRouteMode(data?.mode || 'coverage'); + } catch (err) { + console.error('[RTMonitor] 解析任务路径数据失败:', err); + } + const mapPoints = pathPoints.map(p => ({ + lng: Number(p.lng ?? p.lon ?? p.longitude ?? p[0]), + lat: Number(p.lat ?? p.latitude ?? p[1]), + })); + setPolyPoints(mapPoints); + } + } catch (err) { + console.error('[RTMonitor] 加载任务路径失败', err); + } + }; + // 获取算法回传的实际行驶路径(路线) + const fetchDetailTaskPath = async (taskId) => { + if (!taskId) return; + try { + const res = await getTaskPath({ taskId }); + if (res?.code === 200 && res?.data) { + setPoints((res.data || [])); + } + } catch (err) { + console.error('[RTMonitor] 获取算法回传路径失败', err); + } + }; + + // 加载路线详情(预设路径点击执行时) + const fetchRouteDetailAndShow = async (routeId, routeData) => { + try { + // 先直接用 routeData 展示预定路线 + if (routeData?.points?.length) { + const pts = routeData.points; + const mapPoints = pts.map(p => ({ + lng: Number(p.lng ?? p.lon ?? p.longitude ?? p[0]), + lat: Number(p.lat ?? p.latitude ?? p[1]), + })); + setPoints(mapPoints); + setPolyPoints(mapPoints); + setRouteMode(routeData.mode || ''); + setClearPlanLine(c => c + 1); + } + + } catch (err) { + console.error('[RTMonitor] 展示路线失败', err); + } + }; + + useEffect(() => { + fetchAllData(); + }, [stationId, refreshKey]); + + const handleRefresh = () => { + setRefreshKey(prev => prev + 1); + messageApi.success(t('common.refresh')); + }; + + // ============================================================ + // 设备数据封装 + // ============================================================ + const planeDeviceRows = useMemo(() => { + return (planeDevices || []).map((d, idx) => { + const m = droneMqttMap[d.device_sn] || {}; + const lon = m.longitude || d.longitude; + const lat = m.latitude || d.latitude; + return { + id: d.device_sn || d.id || 'plane-' + idx, + name: d.drone_callsign || d.device_sn || t('devices.drone'), + deviceAlias: d.drone_callsign || d.device_sn, + serialNumber: d.device_sn, + device_sn: d.device_sn, + gateway_sn: d.gateway_sn, + type: 'plane', + category: 'plane', + typeText: t('devices.drone'), + status: d.onlineStatus === 1 ? t('devices.s59') : t('devices.offline'), + onlineStatus: d.onlineStatus === 1 ? 1 : 3, + data: d.onlineStatus === 1 ? t('devices.idle') : '-', + communication: d.onlineStatus === 1 ? '通讯正常' : '通讯中断', + updateTime: d.update_time ? dayjs(d.update_time).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'), + feStatus: d.onlineStatus === 1 ? 2 : 3, + longitude: lon, + latitude: lat, + lastRunningStatus: (lon && lat) ? { longitude: lon, latitude: lat } : undefined, + batteryLevel: d.battery ? d.battery.capacity_percent : undefined, + raw: Object.assign({}, d, { type: 'plane', deviceAlias: d.drone_callsign || d.device_sn }) + }; + }); + }, [planeDevices, droneMqttMap]); + + const deviceList = useMemo(() => { + const robots = devices.map((d, idx) => ({ + id: d.id || idx, + name: d.deviceAlias || d.deviceName || `设备-${d.serialNumber?.slice(-4) || idx}`, + serialNumber: d.serialNumber, + type: d.deviceType || 'ROBOT', + category: 'robot', + typeText: d.deviceTypeName || d.deviceType || t('devices.robot'), + status: d.feStatus == 1 ? t('devices.s59') : (d.feStatus == 2 ? t('devices.idle') : t('devices.offline')), + onlineStatus: d.onlineStatus, + data: d.currentTask ? t('devices.executing') : (d.onlineStatus === 1 ? t('devices.idle') : '-'), + communication: d.onlineStatus === 1 ? '通讯正常' : '通讯中断', + updateTime: d.updateTime || dayjs().format('YYYY-MM-DD HH:mm:ss'), + feStatus: d.feStatus, + longitude: d.longitude, + latitude: d.latitude, + batteryLevel: d.batteryLevel, + raw: d + })); + const mocks = [ + { id: 'mock-inv-1', name: '逆变器 INV-01', type: 'INVERTER', category: 'inverter', typeText: t('home.inverter'), status: t('roles.normal'), onlineStatus: 1, data: '164.2 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude + 0.0005 : 0, latitude: currentStation ? currentStation.latitude + 0.0005 : 0, isMock: true }, + { id: 'mock-inv-2', name: '逆变器 INV-02', type: 'INVERTER', category: 'inverter', typeText: t('home.inverter'), status: t('roles.normal'), onlineStatus: 1, data: '166.8 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude - 0.0003 : 0, latitude: currentStation ? currentStation.latitude + 0.0004 : 0, isMock: true }, + { id: 'mock-cb-1', name: '汇流箱 01', type: 'COMBINER_BOX', category: 'combiner', typeText: t('home.combinerBox'), status: t('roles.normal'), onlineStatus: 1, data: '32 组 / 32 组', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude + 0.0007 : 0, latitude: currentStation ? currentStation.latitude - 0.0003 : 0, isMock: true }, + { id: 'mock-ws-1', name: '气象站', type: 'WEATHER_STATION', category: 'weather', typeText: '气象站', status: t('roles.normal'), onlineStatus: 1, data: '28.0 ℃ / 815W/m²', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude - 0.0006 : 0, latitude: currentStation ? currentStation.latitude - 0.0005 : 0, isMock: true }, + ]; + return [...robots, ...planeDeviceRows, ...mocks]; + }, [devices, planeDeviceRows, currentStation]); + + const mapDevices = useMemo(() => { + const all = [...devices, ...planeDeviceRows]; + if (mapViewMode === 'selected' && (selectedDevice?.serialNumber || selectedDevice?.device_sn)) { + const sn = selectedDevice?.serialNumber || selectedDevice?.device_sn; + return all + .filter(d => (d.serialNumber == sn) || (d.device_sn == sn)) + + } + return all + .filter(d => (d?.lastRunningStatus?.latitude && d?.lastRunningStatus?.longitude) || (d?.locationMessage?.latitude && d?.locationMessage?.longitude) || (d?.longitude && d?.latitude)); + + }, [devices, planeDeviceRows, mapViewMode, selectedDevice]); + + // ============================================================ + // 点击设备:WebSocket 连接 + 地图定位 + // ============================================================ + const handleDeviceClick = (robot) => { + console.log('[RTMonitor] 点击设备:', robot); + const dev = robot; + setSelectedDevice(dev); + setSelectedDeviceSn(dev.serialNumber || dev.device_sn); + + const isMockDevice = dev?.isMock || ['INVERTER', 'COMBINER_BOX', 'WEATHER_STATION', 'METER'].includes(dev?.type); + const isDroneDevice = dev?.type === 'plane' || !!dev?.gateway_sn; + + // ---- 地图定位 ---- + if ((dev?.lastRunningStatus?.longitude && dev?.lastRunningStatus?.latitude) || (dev?.locationMessage?.longitude && dev?.locationMessage?.latitude) || (dev?.longitude && dev?.latitude)) { + setFocusLocation({ + lon: Number(dev.lastRunningStatus?.longitude || dev.locationMessage?.longitude || dev.longitude), + lat: Number(dev.lastRunningStatus?.latitude || dev.locationMessage?.latitude || dev.latitude), + type: isDroneDevice ? 'plane' : 'robot', + name: dev.deviceAlias || dev.deviceName || dev.drone_callsign || dev.serialNumber || dev.device_sn, + }); + } + + // ---- 逆变器/模拟设备:仅地图定位,不打开抽屉 ---- + if (isMockDevice) { + setDeviceDrawerOpen(false); + setMqttDrone(null); + return; + } + setExecute(true); + setDeviceDrawerOpen(true); + + + // ---- 无人机:先断开 WebSocket,再订阅该无人机 MQTT 实时数据 ---- + if (isDroneDevice) { + controllerRef.current?.disconnect?.(); + setMqttDrone(dev); + if (activeDroneTask?.device_sn !== dev.device_sn) { + setDroneReturningHome(false); + setDroneTaskPaused(false); + } else { + syncDroneTaskStatus(); + } + setClearNavLine(c => c + 1); + fetchWaylineList(); + fetchAndFocusDrone(dev); + return; + } + + // ---- 机器人:先取消 MQTT 订阅,再连接 WebSocket ---- + setMqttDrone(null); + if (dev.serialNumber && controllerRef.current) { + const isSameDevice = controllerRef.current.connectedDeviceSn === dev.serialNumber; + if (isSameDevice) { + console.log('[RTMonitor] 已连接相同设备,跳过'); + } else if (isFirstConnect.current) { + isFirstConnect.current = false; + controllerRef.current.connectDevice(dev); + } else { + controllerRef.current.switchDevice(dev); + } + setClearNavLine(c => c + 1); + } + + // ---- 刷新该设备任务数据,并在地图显示该设备正在执行任务的路线和区域 ---- + fetchTaskPoolList(dev.serialNumber).then(poolRows => { + const rows = poolRows || []; + const runningTask = rows.find(t => + (t.deviceId === dev.serialNumber) && + ['EXECUTING', 'PAUSE', 'NEW'].includes(t.taskStaus) + ); + console.log('[RTMonitor] 设备正在执行的任务:', runningTask); + if (runningTask) { + setRunningPoolTask(runningTask); + loadTaskPath(runningTask.id); + fetchDetailTaskPath(runningTask.id); + setExcuteStatus(runningTask.taskStaus === 'EXECUTING' ? 'running' : 'pause'); + } else { + setRunningPoolTask(null); + setPoints([]); + setPolyPoints([]); + setExcuteStatus('stop'); + } + }); + }; + + const typeCounts = useMemo(() => { + const c = { all: deviceList.length, robot: 0, plane: 0, inverter: 0, combiner: 0, weather: 0 }; + deviceList.forEach(d => { if (c[d.category] !== undefined) c[d.category] += 1; }); + return c; + }, [deviceList]); + + const filteredDeviceList = useMemo(() => { + return deviceList.filter(d => { + if (filterType !== 'all' && d.category !== filterType) return false; + + if (searchName) { + const kw = searchName.trim().toLowerCase(); + if (!String(d.name || '').toLowerCase().includes(kw) && !String(d.serialNumber || '').toLowerCase().includes(kw) && !String(d.typeText || '').toLowerCase().includes(kw)) return false; + } + return true; + }); + }, [deviceList, filterStatus, filterType, searchName]); + + const pagedDeviceList = useMemo(() => { + const start = (listPage - 1) * listPageSize; + return filteredDeviceList.slice(start, start + listPageSize); + }, [filteredDeviceList, listPage, listPageSize]); + const getStatusTag = (status) => { - const color = status === t('roles.normal') ? '#52c41a' : status === t('constants.sourceAlert') ? '#faad14' : '#999'; + let color = '#999'; + let text = '离线'; + if (status === 1) { + color = '#1677ff'; + text = '工作中'; + } else if (status === 2) { + color = '#52c41a'; + text = '空闲'; + } + return ( - {status} + {text} ); }; + const columns = [ { title: t('devices.deviceName'), dataIndex: 'name', key: 'name', render: (text, record) => ( - + handleDeviceClick(record.raw || record)} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
- {record.type === t('home.inverter') ? : } + {record.type?.includes?.('INV') ? : getDeviceTypeIcon(record.type)}
{text} -
+ ) }, - { title: t('common.type'), dataIndex: 'type', render: (t) => {t} }, - { title: t('workOrder.currentStatus'), dataIndex: 'status', render: getStatusTag }, - { title: t('page.fixed2RealtimePower'), dataIndex: 'data', render: (d) => {d} }, - { - title: t('page.statusFixed2'), dataIndex: 'communication', - render: (c) => ( - - {c} - - - ) - }, - { title: t('common.updateTime'), dataIndex: 'updateTime', render: (t) => {t} } - ]; - const deviceList = [ - { id: 1, name: '逆变器 INV-01', type: t('home.inverter'), status: t('roles.normal'), data: '164.2 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, - { id: 2, name: '逆变器 INV-02', type: t('home.inverter'), status: t('roles.normal'), data: '166.8 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, - { id: 3, name: '逆变器 INV-03', type: t('home.inverter'), status: t('roles.normal'), data: '162.1 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, - { id: 4, name: '逆变器 INV-04', type: t('home.inverter'), status: t('roles.normal'), data: '159.7 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, - { id: 5, name: '逆变器 INV-05', type: t('home.inverter'), status: t('constants.sourceAlert'), data: '159.8 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, - { id: 6, name: '汇流箱 01', type: t('home.combinerBox'), status: t('roles.normal'), data: '32 组 / 32 组', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, - { id: 7, name: '汇流箱 02', type: t('home.combinerBox'), status: t('roles.normal'), data: '32 组 / 32 组', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, - { id: 8, name: '气象站', type: '气象站', status: t('roles.normal'), data: '28.0 ℃ / 815W/m²', communication: '通讯正常', updateTime: '2025-05-25 10:24:15' }, + { title: t('common.type'), dataIndex: 'typeText', render: (t) => {t} }, + { title: t('workOrder.currentStatus'), dataIndex: 'feStatus', render: getStatusTag }, + //{ title: t('page.fixed2RealtimePower'), dataIndex: 'data', render: (d) => {d} }, + //{ + // title: t('page.statusFixed2'), dataIndex: 'communication', + // render: (c) => ( + // + // {c} + // + // + // ) + //}, + //{ + // title: t('common.action'), key: 'action', width: 80, + // render: (_, record) => ( + // + // + // + // ) + //} ]; + // 任务池(当前选中设备) + const deviceTasks = useMemo(() => { + if (!selectedDeviceSn) return { pool: [], current: null }; + const pool = taskPoolList.filter(t => t.deviceId === selectedDeviceSn); + const current = pool.find(t => ['EXECUTING', 'PAUSE', 'NEW'].includes(t.taskStaus)) || null; + return { pool, current }; + }, [selectedDeviceSn, taskPoolList,]); + + // 同步 runningPoolTask -> excuteStatus + useEffect(() => { + if (runningPoolTask) { + setExcuteStatus(runningPoolTask.taskStaus === 'EXECUTING' ? 'running' : runningPoolTask.taskStaus === 'PAUSE' ? 'pause' : 'stop'); + } else if (!deviceTasks.current) { + setExcuteStatus('stop'); + } + }, [runningPoolTask, deviceTasks.current]); + + // ============================================================ + // 无人机:MQTT 实时数据订阅(复用航线任务页逻辑) + // ============================================================ + const handleMqttMessage = useCallback((topic, message) => { + try { + const parsed = JSON.parse(message); + const host = parsed?.data?.host; + if (!host || host.job_number) return; + if (host.battery === undefined) return; + const sn = String(topic).split('/')[2] || ''; + setDroneMqttMap(prev => { + const nd = { ...(prev[sn] || {}) }; + if (host.battery?.capacity_percent !== undefined) nd.capacity_percent = host.battery.capacity_percent; + if (host.attitude_head !== undefined) nd.heading = host.attitude_head; + if (host.horizontal_speed !== undefined) nd.horizontal_speed = host.horizontal_speed; + if (host.vertical_speed !== undefined) nd.vertical_speed = host.vertical_speed; + if (host.height !== undefined) nd.height = host.height; + if (host.wind_speed !== undefined) nd.wind_speed = host.wind_speed; + if (host.position_state !== undefined) nd.position_state = host.position_state; + if (host.longitude !== undefined) nd.longitude = host.longitude; + if (host.latitude !== undefined) nd.latitude = host.latitude; + if (host.mode_code !== undefined) nd.mode_code = host.mode_code; + return { ...prev, [sn]: nd }; + }); + } catch (err) { + console.error('[RTMonitor] MQTT 消息解析失败:', err); + } + }, []); + + const mqttTopics = useMemo(() => { + if (!mqttDrone) return []; + const topics = []; + if (mqttDrone.device_sn) topics.push('thing/product/' + mqttDrone.device_sn + '/osd'); + if (mqttDrone.gateway_sn) topics.push('thing/product/' + mqttDrone.gateway_sn + '/osd'); + return topics; + }, [mqttDrone]); + + const selectedDroneRealtime = useMemo(() => droneMqttMap[selectedDevice?.device_sn] || {}, [droneMqttMap, selectedDevice]); + + useMqtt({ + url: envConfig.mqtt_url, + topic: mqttTopics, + onMessage: handleMqttMessage, + enabled: mqttTopics.length > 0, + }); + + // ============================================================ + // 无人机:航线列表 + 执行(复用航线任务页逻辑) + // ============================================================ + const fetchWaylineList = async () => { + try { + const res = await getWayLine(); + if (res?.code === 200 || res?.code === 0) { + setWaylineList((res?.data?.list || []).map(item => ({ ...item, label: item.name, value: item.id }))); + } else { + messageApi.error(t('devices.waylineListFetchFail')); + } + } catch (err) { + console.error('[RTMonitor] 获取航线列表失败', err); + messageApi.error(t('devices.waylineListFetchFail')); + } + }; + + const handleWaylineClick = (wayline) => { + setSelectedWayline(wayline); + const pts = wayline.points || []; + const mapped = pts.map(p => ({ lng: Number(p.longitude || p.lon || 0), lat: Number(p.latitude || p.lat || 0) })); + if (mapped.length) setPoints(mapped); + }; + + const handleDroneExecuteClick = (wayline) => { + if (!selectedDevice?.gateway_sn) { + messageApi.warning(t('devices.selectExecuteDroneFirst')); + return; + } + setSelectedWayline(wayline); + setTempRthAltitude(100); + setRthModalVisible(true); + }; + + const confirmExecuteWayline = async () => { + if (!selectedWayline || !selectedDevice?.gateway_sn) return; + setWaylineLoading(true); + try { + const payload = { + name: selectedWayline.name + '_' + dayjs().format('MMDDHHmm'), + sn: selectedDevice.gateway_sn, + wayline_uuid: selectedWayline.id || selectedWayline.uuid, + rth_altitude: tempRthAltitude, + task_type: 'immediate', + rth_mode: 'optimal', + wayline_precision_type: 'gps', + resumable_status: 'auto', + min_battery_capacity: 50, + repeat_type: 'nonrepeating', + time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone, + }; + const res = await createWaylineTask(payload); + if (res?.code === 200 || res?.code === 0) { + messageApi.success(t('devices.waylineTaskCreated')); + setRthModalVisible(false); + setActiveDroneTask({ + device_sn: selectedDevice.device_sn, + taskId: res?.data?.id || res?.data?.uuid || selectedWayline.id || selectedWayline.uuid || '', + name: payload.name, + createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), + status: 'EXECUTING', + }); + setDroneReturningHome(false); + setDroneTaskPaused(false); + } else { + messageApi.error(res?.msg || t('devices.waylineExecFail')); + } + } catch (err) { + console.error('[RTMonitor] 执行航线失败', err); + messageApi.error(t('devices.createTaskException')); + } finally { + setWaylineLoading(false); + } + }; + + const sendDroneFlightCommand = async (command) => { + const dev = selectedDevice; + if (!dev?.device_sn) { + messageApi.warning(t('devices.noDeviceSelected')); + return; + } + setDroneCommandLoading(true); + try { + const res = await postFlightCommmand({ command, deviceSn: dev.device_sn }); + if (res?.code === 200 || res?.code === 0) { + messageApi.success(t('devices.commandSent')); + if (command === 'return_home') { + setDroneReturningHome(true); + setActiveDroneTask(t => (t ? { ...t, status: 'RETURN_HOME' } : t)); + } + if (command === 'return_home_cancel') setDroneReturningHome(false); + if (command === 'flighttask_pause') { + setDroneTaskPaused(true); + setActiveDroneTask(t => (t ? { ...t, status: 'PAUSE' } : t)); + } + if (command === 'flighttask_recovery') { + setDroneTaskPaused(false); + setActiveDroneTask(t => (t ? { ...t, status: 'EXECUTING' } : t)); + } + } else { + messageApi.error(res?.msg || t('devices.commandSendFail')); + } + } catch (err) { + console.error('[RTMonitor] 下发无人机指令失败', err); + messageApi.error(t('devices.commandSendFail')); + } finally { + setDroneCommandLoading(false); + } + }; + + const syncDroneTaskStatus = async () => { + if (!activeDroneTask?.taskId) return; + try { + const res = await getFlightTaskDetail(activeDroneTask.taskId); + const st = res?.data?.status || ''; + const paused = ['paused', 'suspended', 'PAUSE', 'SUSPENDED'].includes(st); + const returning = ['return_home', 'RETURN_HOME', 'returnHome'].includes(st); + setDroneTaskPaused(paused); + setDroneReturningHome(returning); + setActiveDroneTask(t => (t ? { ...t, status: returning ? 'RETURN_HOME' : paused ? 'PAUSE' : 'EXECUTING' } : t)); + } catch (err) { + // ignore sync error + } + }; + const fetchAndFocusDrone = async (dev) => { + if (!dev?.gateway_sn || !dev?.device_sn) return; + try { + const res = await getUAVState({ sn: dev.gateway_sn, droneSn: dev.device_sn }); + const pos = res?.data; + if (pos && pos.longitude && pos.latitude) { + setFocusLocation({ + lon: Number(pos.longitude), + lat: Number(pos.latitude), + type: 'plane', + name: dev.deviceAlias || dev.device_sn, + }); + } + } catch (err) { + console.error('[RTMonitor] 获取无人机位置失败', err); + } + }; + + // ============================================================ + // 路径操作:执行/暂停/恢复/取消 + // ============================================================ + const handleRouteExecute = async (route) => { + if (!selectedDevice) { messageApi.error(t('devices.selectExecuteDevice')); return; } + if (!selectedDevice?.serialNumber) { messageApi.error(t('devices.deviceSerialNumberMissing')); return; } + modal.confirm({ + title: t('devices.confirmExecuteRoute'), + content: ( +
+

{t('devices.targetDevice')}: {selectedDevice.deviceAlias || selectedDevice.name || selectedDevice.serialNumber}

+

{t('devices.routeName')}: {route.workName || route.name}

+ {route.points?.length &&

{t('devices.routePointCount')}: {route.points.length}

} +
+ ), + okText: t('common.confirm'), + cancelText: t('common.cancel'), + onOk: async () => { + try { + const params = { deviceId: selectedDevice.serialNumber, routeId: route.id, siteId: stationId }; + if (currentStation?.orgId) params.orgId = currentStation.orgId; + const res = await excuetRoute(params); + if (res.code == 200) { + messageApi.success(t('devices.taskExecSuccess')); + // 先立即显示该路线在地图 + fetchRouteDetailAndShow(route.id, route); + // 刷新任务池 + const freshPool = await fetchTaskPoolList(selectedDevice.serialNumber); + // 自动设置当前执行任务,并在地图显示该任务的路线和区域 + const rest = (freshPool && freshPool.length ? freshPool : taskPoolList) + .filter(t => t.deviceId === selectedDevice.serialNumber); + const newTask = [...rest].sort((a, b) => new Date(b.createTime) - new Date(a.createTime))[0]; + if (newTask) { + setRunningPoolTask(newTask); + await loadTaskPath(newTask.id); + await fetchDetailTaskPath(newTask.id); + setExcuteStatus('running'); + } + } else { + console.log('[RTMonitor] 执行路径失败:', res); + messageApi.error(res.msg || t('devices.taskExecuteFailed')); + } + } catch (err) { + console.error(err); + messageApi.error(t('devices.taskExecuteException')); + } + } + }); + }; + + const handlePauseTask = async (task = runningPoolTask) => { + if (!task) return; + try { + const res = await pauseRoute({ taskId: task.id, orgId: task.orgId, siteId: stationId }); + if (res.code === 200) { + messageApi.success(t('devices.taskPaused')); + setExcuteStatus('pause'); + if (runningPoolTask?.id === task.id) setRunningPoolTask({ ...runningPoolTask, taskStaus: 'PAUSE' }); + fetchTaskPoolList(selectedDeviceSn); + } + } catch (err) { console.error(err); messageApi.error(t('devices.taskPauseAbnormal')); } + }; + + const handleRecoverTask = async (task = runningPoolTask) => { + if (!task) return; + try { + const res = await recoverRoute({ taskId: task.id, orgId: task.orgId, siteId: stationId }); + if (res.code === 200) { + messageApi.success(t('devices.taskResumed')); + setExcuteStatus('running'); + if (runningPoolTask?.id === task.id) setRunningPoolTask({ ...runningPoolTask, taskStaus: 'EXECUTING' }); + fetchTaskPoolList(selectedDeviceSn); + } + } catch (err) { console.error(err); } + }; + + const handleCancelTask = async (task = runningPoolTask) => { + if (!task) return; + modal.confirm({ + title: t('devices.confirmCancelTask'), + content: `${t('devices.areYouSureCancelTask')} ${task.planName || task.id}?`, + onOk: async () => { + try { + const res = await cancelRoute({ taskId: task.id, orgId: task.orgId, siteId: stationId }); + if (res.code === 200) { + messageApi.success(t('devices.taskCancelled')); + setRunningPoolTask(null); + setExcuteStatus('stop'); + setPoints([]); + setPolyPoints([]); + setClearNavLine(c => c + 1); + setClearPlanLine(c => c + 1); + fetchTaskPoolList(selectedDeviceSn); + } + } catch (err) { console.error(err); messageApi.error(t('devices.taskCancelAbnormal')); } + } + }); + }; + + // 过滤后的路径列表 + const filteredRoutes = useMemo(() => { + if (!routeSearch) return routeList; + const s = routeSearch.toLowerCase(); + return routeList.filter(r => + String(r.workName || r.name || '').toLowerCase().includes(s) || + String(r.workDescription || r.description || '').toLowerCase().includes(s) + ); + }, [routeList, routeSearch]); + + // ============================================================ + // 渲染 + // ============================================================ return (
-
- {t('router.realtimeMonitorCenter')} - {t('page.deviceFixed2StatusAndGeneration')} + {contextHolder} + +
+
+ {t('router.realtimeMonitorCenter')} + {t('page.deviceFixed2StatusAndGeneration')} · {currentStation?.siteName || t('common.loading')} +
+ + + +
- {/* 左侧大栏 */} - {/* 电站拓扑图 */} + {/* ---------- 地图 ---------- */} {t('page.stationTopology')}} + title={ + + {t('page.stationTopology')} + + + + {focusLocation && ( + + {t('page.focusingDevice', { name: focusLocation.name || '-' })} + + )} + + } extra={ -
- {t('roles.normal')} - {t('constants.sourceAlert')} - {t('devices.offline')} - {t('page.s2')} -
+ + + {t('roles.normal')} + + + {t('constants.sourceAlert')} + + + {t('devices.offline')} + + + + + } variant="borderless" style={{ ...cardStyle, borderRadius: 8 }} - styles={{ body: { padding: 0, position: 'relative', height: 400, overflow: 'hidden' } }} + styles={{ body: { padding: 0, position: 'relative', height: 500, overflow: 'hidden' } }} > -
- {/*