diff --git a/zlt-web/react-web/src/main/frontend/config/routes.ts b/zlt-web/react-web/src/main/frontend/config/routes.ts index 2492d721..575179ca 100644 --- a/zlt-web/react-web/src/main/frontend/config/routes.ts +++ b/zlt-web/react-web/src/main/frontend/config/routes.ts @@ -194,6 +194,11 @@ name: '设备管理', component: './device-ops/device', }, + { + path: '/device-ops/map-dashboard.html', + name: '地图仪表板', + component: './device-ops/map-dashboard', + }, { path: '/device-ops/device/:id', name: '设备详情', diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx new file mode 100644 index 00000000..dc52df80 --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx @@ -0,0 +1,2366 @@ +import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'; +import { PageContainer } from '@ant-design/pro-layout'; +import { + Card, Row, Col, Button, Space, Select, Input, Badge, Tag, Statistic, + message, Modal, Drawer, Tooltip, Divider, Typography, Collapse, + Descriptions, Progress, Alert, Switch, Slider, DatePicker +} from 'antd'; +import { + EnvironmentOutlined, DashboardOutlined, SettingOutlined, + VideoCameraOutlined, ToolOutlined, ReloadOutlined, FilterOutlined, + CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined, + ClockCircleOutlined, WarningOutlined, InfoCircleOutlined, + EyeOutlined, PlayCircleOutlined, PauseCircleOutlined, HomeOutlined, + CameraOutlined, ControlOutlined, BellOutlined, BarChartOutlined, + PauseOutlined +} from '@ant-design/icons'; +import moment from 'moment'; +import { Amap } from '@amap/amap-react'; +import ReactPlayer from 'react-player'; +import { device, getStreamUrls } from '@/services/device/api'; +import { request } from 'umi'; +import { + Device, DeviceStatus, DEVICE_STATUS_CONFIG, + generateMockDevices, calculateDeviceStats, DeviceStats +} from './mock/devices'; + +// 高德地图全局类型声明 +declare global { + interface Window { + AMap: any; + } +} + +const { RangePicker } = DatePicker; +const { Title, Text } = Typography; +const { Panel } = Collapse; + +// 真实设备接口(从监控页面复制) +interface RealDevice { + deviceSn: string; + deviceName: string; + deviceType: number; + boundStatus: number; + createTime: string; + loginTime: string; + lastUpdateTime?: string; + location?: { + latitude: number; + longitude: number; + height?: number; + heading?: number; + updateTime: string; + }; + metrics: { + temperature: number; + humidity: number; + windSpeed: number; + rainfall: number; + environmentTemperature: number; + positionQuality: number; + networkQuality: number; + droneInDock: number; + batteryCapacity: number; + batteryState: number; + workingVoltage: number; + workingCurrent: number; + acdcPowerInput: number; + backupBatteryVoltage: number; + flightTaskStep: number; + tiltAngle: number; + sdrUpQuality: number; + sdrDownQuality: number; + wirelessLinkState: number; + wirelessLinkQuality: number; + '4gLinkState': number; + '4gLinkQuality': number; + signalStrength: number; + dataRate: number; + packetLoss: number; + latency: number; + cpuUsage: number; + memoryUsage: number; + diskUsage: number; + errorCount: number; + warningCount: number; + uptime: number; + lastMaintenance: string; + nextMaintenance: string; + modeCode: number; + }; + airportStatus?: { + flightTaskStep: number; + flightTaskStepText: string; + sdrFrequency: number; + sdrUpQuality: number; + sdrDownQuality: number; + tiltAngle: number; + tiltAngleValid: number; + wirelessLink: { + sdrLinkState: number; + sdrQuality: number; + sdrFreqBand: number; + '4gLinkState': number; + '4gQuality': number; + '4gFreqBand': number; + linkWorkMode: number; + dongleNumber: number; + }; + departurePoint: { + latitude: number; + longitude: number; + height: number; + status: number; + }; + drcState: number; + mediaRemainUpload: number; + flightTaskPrepareCapacity: number; + }; +} + +// WebSocket相关接口 +interface TokenResponse { + data: { + result: string; + message: string; + status: number; + timestamp: number; + expires?: number; + }; + resp_code: number; + resp_msg: string; +} + +interface FireAlarmPayload { + headers: { + deviceName: string; + productName: string; + productId: string; + }; + messageId: string; + deviceId: string; + timestamp: number; + event: string; + data: { + data: { + temperature?: number; + humidity?: number; + wind_speed?: number; + rainfall?: number; + environment_temperature?: number; + latitude?: number; + longitude?: number; + height?: number; + heading?: number; + drone_charge_state?: { + capacity_percent: number; + state: number; + }; + position_state?: { + is_calibration: number; + rtk_number: number; + gps_number: number; + is_fixed: number; + quality: number; + }; + network_state?: { + rate: number; + type: number; + quality: number; + }; + drone_in_dock?: number; + flighttask_step_code?: number; + sdr?: { + frequency_band: number; + up_quality: number; + down_quality: number; + }; + tilt_angle?: { + valid: number; + value: number; + }; + wireless_link?: { + sdr_link_state: number; + '4g_freq_band': number; + '4g_quality': number; + link_workmode: number; + sdr_quality: number; + '4g_uav_quality': number; + sdr_freq_band: number; + '4g_link_state': number; + '4g_gnd_quality': number; + dongle_number: number; + }; + }; + deviceId: string; + timestamp: number; + }; + messageType: string; +} + +// 地图设备标记 +interface MapDeviceMarker { + device: RealDevice; + position: [number, number]; + color: string; + status: DeviceStatus; +} + +const DEFAULT_EXPIRES = 7200; // 2小时,单位秒 + +const DeviceMapDashboard: React.FC = () => { + // 基础状态 + const [devices, setDevices] = useState([]); + const [selectedDevice, setSelectedDevice] = useState(null); + const [mapCenter, setMapCenter] = useState<[number, number]>([116.397428, 39.90923]); + const [mapZoom, setMapZoom] = useState(11); + const [loading, setLoading] = useState(false); + + // 面板控制 + const [leftPanelVisible, setLeftPanelVisible] = useState(true); + const [rightPanelVisible, setRightPanelVisible] = useState(false); + const [leftPanelCollapsed, setLeftPanelCollapsed] = useState(false); + const [rightPanelCollapsed, setRightPanelCollapsed] = useState(false); + + // 筛选和搜索 + const [statusFilter, setStatusFilter] = useState('all'); + const [typeFilter, setTypeFilter] = useState('all'); + const [groupFilter, setGroupFilter] = useState('all'); + const [searchKeyword, setSearchKeyword] = useState(''); + + // 视频流相关 + const [videoStreamVisible, setVideoStreamVisible] = useState(false); + const [videoStreamUrl, setVideoStreamUrl] = useState(''); + const [videoLoading, setVideoLoading] = useState(false); + const [allStreamUrls, setAllStreamUrls] = useState<{ + pushUrl: string; + playFlvUrl: string; + playM3u8Url: string; + playRtmpUrl: string; + } | null>(null); + const [currentStreamType, setCurrentStreamType] = useState<'hls' | 'flv' | 'rtmp'>('hls'); + + // 地图相关 + const [mapInitialized, setMapInitialized] = useState(false); + const [showDeviceCard, setShowDeviceCard] = useState(false); + const [hoveredDevice, setHoveredDevice] = useState(null); + const [deviceCardPosition, setDeviceCardPosition] = useState<{ x: number; y: number }>({ x: 0, y: 0 }); + const [mapType, setMapType] = useState<'normal' | 'dark' | 'satellite'>('normal'); + + // 高德地图实例和标记管理 + const mapRef = useRef(null); + const markersRef = useRef>(new Map()); + const mapContainerRef = useRef(null); + + // WebSocket相关 + const wsRef = useRef(null); + const [wsConnected, setWsConnected] = useState(false); + const reconnectTimerRef = useRef(); + const heartbeatTimerRef = useRef(); + const [currentSubscribedDevice, setCurrentSubscribedDevice] = useState('all'); + const [currentSubscriptions, setCurrentSubscriptions] = useState([]); + + // Token缓存 + const tokenCache = { + value: '', + expire: 0, + timer: null as NodeJS.Timeout | null, + }; + + // 地图样式配置 + const mapStyles = { + normal: "amap://styles/normal", + dark: "amap://styles/dark", + satellite: "amap://styles/satellite" + }; + + // 地图样式名称 + const mapStyleNames = { + normal: '普通图', + dark: '暗夜图', + satellite: '卫星图' + }; + + // 获取WebSocket Token + const getToken = async (expires: number = DEFAULT_EXPIRES) => { + const now = Date.now(); + if (tokenCache.value && tokenCache.expire > now) { + return tokenCache.value; + } + + // 根据SDK文档更新Token获取地址 + const tokenResponse = await request('http://119.45.169.13:9900/api-device/token/query', { + method: 'GET', + params: { expires }, + }); + + if (tokenResponse.resp_code !== 0) { + throw new Error(tokenResponse.resp_msg || '获取token失败'); + } + + const { result: token, expires: expiresFromServer } = tokenResponse.data; + const expireSeconds = expiresFromServer ?? expires; + tokenCache.value = token; + tokenCache.expire = now + expireSeconds * 1000; + + if (tokenCache.timer) clearTimeout(tokenCache.timer); + tokenCache.timer = setTimeout(() => { + refreshTokenAndReconnect(); + }, expireSeconds * 1000 - 5 * 60 * 1000); + + return token; + }; + + // 刷新Token并重连 + const refreshTokenAndReconnect = async () => { + tokenCache.value = ''; + await getToken(); + if (wsRef.current) { + wsRef.current.close(); + } + await initWebSocket(); + }; + + // 获取真实设备列表 + const fetchDeviceList = async () => { + setLoading(true); + try { + const response = await device({ + page: 1, + limit: 1000, + }); + + if (response.resp_code === 0 && response.data) { + setDevices(response.data.map((item: any) => ({ + ...item, + metrics: { + temperature: 0, + humidity: 0, + windSpeed: 0, + rainfall: 0, + environmentTemperature: 0, + positionQuality: 0, + networkQuality: 0, + droneInDock: 0, + batteryCapacity: 0, + batteryState: 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + signalStrength: 0, + dataRate: 0, + packetLoss: 0, + latency: 0, + cpuUsage: 0, + memoryUsage: 0, + diskUsage: 0, + errorCount: 0, + warningCount: 0, + uptime: 0, + lastMaintenance: '', + nextMaintenance: '', + modeCode: 0, + } + }))); + } else { + console.error('获取设备列表失败:', response.resp_msg); + // 如果真实数据获取失败,使用mock数据 + const mockDevices = generateMockDevices(); + setDevices(convertMockDevicesToRealDevices(mockDevices)); + } + } catch (error) { + console.error('获取设备列表失败:', error); + // 使用mock数据作为备用 + const mockDevices = generateMockDevices(); + setDevices(convertMockDevicesToRealDevices(mockDevices)); + } finally { + setLoading(false); + } + }; + + // 将真实设备状态转换为地图状态 + const getDeviceStatus = (device: RealDevice): DeviceStatus => { + // 基于实时数据上报判断设备在线状态 + // 如果设备有最近的实时数据上报,则认为在线 + const hasRecentData = device.lastUpdateTime && + (Date.now() - new Date(device.lastUpdateTime).getTime()) < 5 * 60 * 1000; // 5分钟内有数据 + + if (!hasRecentData) return DeviceStatus.OFFLINE; + + // 检查告警状态 + if (device.metrics.errorCount > 0 || device.metrics.warningCount > 0) { + return DeviceStatus.ERROR; + } + + // 检查电量状态 + if (device.metrics.batteryCapacity < 20) { + return DeviceStatus.ERROR; + } + + // 检查网络质量 + if (device.metrics.networkQuality < 30) { + return DeviceStatus.MAINTENANCE; + } + + // 检查无人机是否在机库中 + if (device.metrics.droneInDock === 1) { + return DeviceStatus.STANDBY; + } + + // 检查模式代码(飞行任务) + if (device.metrics.modeCode > 0) { + return DeviceStatus.TASK; + } + + return DeviceStatus.STANDBY; + }; + + // 获取过滤后的设备列表 + const getFilteredDevices = (): RealDevice[] => { + return devices.filter(device => { + const status = getDeviceStatus(device); + + // 状态筛选 + if (statusFilter !== 'all' && status !== statusFilter) return false; + + // 类型筛选 + if (typeFilter !== 'all' && device.deviceType.toString() !== typeFilter) return false; + + // 分组筛选(暂时使用设备类型作为分组) + if (groupFilter !== 'all' && device.deviceType.toString() !== groupFilter) return false; + + // 关键词搜索 + if (searchKeyword && !device.deviceName.toLowerCase().includes(searchKeyword.toLowerCase()) && + !device.deviceSn.toLowerCase().includes(searchKeyword.toLowerCase())) return false; + + return true; + }); + }; + + // 获取地图设备标记 + const getMapDeviceMarkers = (): MapDeviceMarker[] => { + return getFilteredDevices() + .filter(device => device.location && device.location.latitude && device.location.longitude) + .map(device => ({ + device, + position: [device.location!.longitude, device.location!.latitude], + color: DEVICE_STATUS_CONFIG[getDeviceStatus(device)].color, + status: getDeviceStatus(device) + })); + }; + + // 计算设备统计 + const calculateDeviceStats = (): DeviceStats => { + const stats: DeviceStats = { + total: devices.length, + online: devices.filter(d => getDeviceStatus(d) !== DeviceStatus.OFFLINE).length, + offline: devices.filter(d => getDeviceStatus(d) === DeviceStatus.OFFLINE).length, + task: devices.filter(d => getDeviceStatus(d) === DeviceStatus.TASK).length, + standby: devices.filter(d => getDeviceStatus(d) === DeviceStatus.STANDBY).length, + maintenance: devices.filter(d => getDeviceStatus(d) === DeviceStatus.MAINTENANCE).length, + error: devices.filter(d => getDeviceStatus(d) === DeviceStatus.ERROR).length, + byGroup: {}, + byType: {} + }; + + // 按分组统计(使用设备类型) + devices.forEach(device => { + const group = `设备类型${device.deviceType}`; + stats.byGroup[group] = (stats.byGroup[group] || 0) + 1; + stats.byType[device.deviceType.toString()] = (stats.byType[device.deviceType.toString()] || 0) + 1; + }); + + return stats; + }; + + // 转换mock设备为RealDevice类型 + const convertMockDevicesToRealDevices = (mockDevices: any[]): RealDevice[] => { + return mockDevices.map(device => ({ + deviceSn: device.sn, + deviceName: device.name, + deviceType: device.type === '无人机' ? 1 : 2, + boundStatus: device.status === DeviceStatus.OFFLINE ? 0 : 1, + createTime: new Date().toISOString(), + loginTime: device.lastUpdate, + location: device.location ? { + latitude: device.location.latitude, + longitude: device.location.longitude, + height: device.location.altitude, + updateTime: device.lastUpdate + } : undefined, + metrics: { + temperature: device.temperature, + humidity: device.humidity, + windSpeed: 0, + rainfall: 0, + environmentTemperature: device.temperature, + positionQuality: device.signal, + networkQuality: device.signal, + droneInDock: 0, + batteryCapacity: device.battery, + batteryState: 0, + workingVoltage: 0, + workingCurrent: 0, + acdcPowerInput: 0, + backupBatteryVoltage: 0, + flightTaskStep: 0, + tiltAngle: 0, + sdrUpQuality: 0, + sdrDownQuality: 0, + wirelessLinkState: 0, + wirelessLinkQuality: 0, + '4gLinkState': 0, + '4gLinkQuality': 0, + signalStrength: device.signal, + dataRate: 0, + packetLoss: 0, + latency: 0, + cpuUsage: 0, + memoryUsage: 0, + diskUsage: 0, + errorCount: 0, + warningCount: 0, + uptime: 0, + lastMaintenance: device.lastMaintenance || '', + nextMaintenance: device.nextMaintenance || '', + modeCode: 0, + } + })); + }; + + // 处理设备点击 + const handleDeviceClick = (device: RealDevice, event: React.MouseEvent) => { + setSelectedDevice(device); + setRightPanelVisible(true); + setRightPanelCollapsed(false); + + // 定位到设备位置 + if (device.location && device.location.longitude && device.location.latitude) { + setMapCenter([device.location.longitude, device.location.latitude]); + setMapZoom(15); + message.info(`已选中设备: ${device.deviceName}`); + } else { + message.warning(`设备 ${device.deviceName} 暂无位置信息`); + } + }; + + // 处理设备悬停 + const handleDeviceHover = (device: RealDevice, event: React.MouseEvent) => { + setHoveredDevice(device); + setShowDeviceCard(true); + setDeviceCardPosition({ x: event.clientX, y: event.clientY }); + }; + + // 处理设备离开 + const handleDeviceLeave = () => { + setHoveredDevice(null); + setShowDeviceCard(false); + }; + + // 定位设备到地图 + const locateDeviceOnMap = (device: RealDevice) => { + if (device.location && device.location.longitude && device.location.latitude) { + setMapCenter([device.location.longitude, device.location.latitude]); + setMapZoom(15); + setSelectedDevice(device); + setRightPanelVisible(true); + setRightPanelCollapsed(false); + } else { + message.warning(`设备 ${device.deviceName} 暂无位置信息`); + } + }; + + // 播放视频流 + const handlePlayVideo = async (device: RealDevice) => { + setVideoLoading(true); + setVideoStreamVisible(true); + + try { + const streamUrls = await getVideoStreamUrl(device.deviceSn); + if (streamUrls) { + setVideoStreamUrl(streamUrls.playM3u8Url); + setCurrentStreamType('hls'); + message.success('视频流加载成功'); + } else { + message.error('获取视频流地址失败'); + } + } catch (error) { + console.error('播放视频失败:', error); + message.error('播放视频失败'); + } finally { + setVideoLoading(false); + } + }; + + // 关闭视频流 + const handleCloseVideo = () => { + setVideoStreamVisible(false); + setVideoStreamUrl(''); + setVideoLoading(false); + }; + + // 刷新设备数据 + const handleRefresh = () => { + setLoading(true); + setTimeout(() => { + const newDevices = generateMockDevices(); + setDevices(convertMockDevicesToRealDevices(newDevices)); + setLoading(false); + message.success('设备数据已刷新'); + }, 1000); + }; + + // 初始化数据 + useEffect(() => { + fetchDeviceList(); + initWebSocket(); + + return () => { + if (wsRef.current) { + wsRef.current.close(); + } + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + } + if (heartbeatTimerRef.current) { + clearInterval(heartbeatTimerRef.current); + } + if (tokenCache.timer) { + clearTimeout(tokenCache.timer); + } + }; + }, []); + + // 初始化地图 + useEffect(() => { + const initMap = () => { + console.log('initMap called, window.AMap:', typeof window !== 'undefined' ? !!window.AMap : 'undefined'); + console.log('mapContainerRef.current:', mapContainerRef.current); + + if (typeof window !== 'undefined' && window.AMap && mapContainerRef.current) { + console.log('开始初始化高德地图...'); + + try { + // 确保地图容器有正确的尺寸 + if (mapContainerRef.current) { + mapContainerRef.current.style.width = '100%'; + mapContainerRef.current.style.height = '100%'; + mapContainerRef.current.style.position = 'relative'; + } + + // 使用安全的地图初始化方法 + mapRef.current = safeInitMap(mapContainerRef.current); + + // 强制触发地图重绘 + setTimeout(() => { + safeRefreshMap(); + console.log('地图重绘完成'); + }, 100); + + setMapInitialized(true); + console.log('高德地图初始化成功'); + + // 验证地图是否正确显示 + setTimeout(() => { + if (mapRef.current && mapContainerRef.current) { + const mapDiv = mapContainerRef.current; + const mapCanvas = mapDiv.querySelector('canvas'); + if (mapCanvas) { + console.log('地图Canvas已创建,尺寸:', mapCanvas.width, 'x', mapCanvas.height); + } else { + console.warn('地图Canvas未找到'); + } + } + }, 500); + } catch (error) { + console.error('地图初始化失败:', error); + message.error('地图初始化失败'); + setMapInitialized(true); + } + } else if (typeof window !== 'undefined' && !window.AMap) { + console.log('开始加载高德地图...'); + const script = document.createElement('script'); + script.src = `https://webapi.amap.com/maps?v=1.4.15&key=7df3685709e341daed76e877e417e5be&plugin=AMap.Scale,AMap.ToolBar`; + script.async = true; + script.onload = () => { + console.log('高德地图加载成功'); + // 延迟初始化,确保DOM已准备好 + setTimeout(initMap, 500); + }; + script.onerror = () => { + console.error('高德地图加载失败'); + message.error('地图加载失败,请检查网络连接'); + setMapInitialized(true); + }; + document.head.appendChild(script); + } else if (typeof window !== 'undefined' && window.AMap && !mapContainerRef.current) { + console.log('AMap已加载但地图容器未创建,等待DOM渲染...'); + // AMap已加载但容器未创建,等待DOM渲染完成 + setTimeout(initMap, 200); + } else { + console.log('地图初始化条件不满足,延迟重试'); + setTimeout(initMap, 1000); + } + }; + + // 延迟初始化,确保DOM已准备好 + const timer = setTimeout(initMap, 500); + return () => clearTimeout(timer); + }, []); + + // 监听地图容器创建 + useEffect(() => { + if (mapContainerRef.current && typeof window !== 'undefined' && window.AMap && !mapRef.current) { + console.log('地图容器已创建,开始初始化地图...'); + const timer = setTimeout(() => { + if (mapContainerRef.current && !mapRef.current) { + try { + mapRef.current = safeInitMap(mapContainerRef.current); + setMapInitialized(true); + console.log('地图容器监听初始化成功'); + } catch (error) { + console.error('地图容器监听初始化失败:', error); + } + } + }, 100); + return () => clearTimeout(timer); + } + }, [mapContainerRef.current]); + + // 当设备列表更新时,重新订阅WebSocket消息 + useEffect(() => { + if (wsConnected && devices.length > 0) { + console.log(`开始订阅 ${devices.length} 个设备的实时数据`); + subscribeDeviceMessages(); + } + }, [wsConnected, devices.length]); + + // 页面加载完成后立即订阅所有设备 + useEffect(() => { + if (wsConnected && devices.length > 0) { + // 延迟订阅,确保WebSocket连接稳定 + const timer = setTimeout(() => { + subscribeDeviceMessages(); + }, 1000); + return () => clearTimeout(timer); + } + }, [wsConnected, devices.length]); + + const deviceStats = calculateDeviceStats(); + const filteredDevices = getFilteredDevices(); + const mapMarkers = getMapDeviceMarkers(); + + // 使用useMemo缓存设备列表,减少重新渲染 + const memoizedDeviceList = useMemo(() => { + return filteredDevices.map(device => ({ + ...device, + status: getDeviceStatus(device), + statusConfig: DEVICE_STATUS_CONFIG[getDeviceStatus(device)] + })); + }, [filteredDevices]); + + // 获取分组选项 + const groupOptions = Array.from(new Set(devices.map(d => d.deviceType.toString()).filter(Boolean))); + + // 创建标记图标 + const createMarkerIcon = (color: string, status: DeviceStatus) => { + const canvas = document.createElement('canvas'); + canvas.width = 32; + canvas.height = 32; + const ctx = canvas.getContext('2d'); + + if (ctx) { + // 绘制圆形背景 + ctx.beginPath(); + ctx.arc(16, 16, 14, 0, 2 * Math.PI); + ctx.fillStyle = color; + ctx.fill(); + + // 绘制白色边框 + ctx.strokeStyle = '#fff'; + ctx.lineWidth = 2; + ctx.stroke(); + + // 绘制图标 + ctx.fillStyle = '#fff'; + ctx.font = '16px Arial'; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillText(DEVICE_STATUS_CONFIG[status].icon, 16, 16); + } + + return canvas.toDataURL(); + }; + + // 更新设备标记 + const updateDeviceMarkers = useCallback(() => { + if (!mapRef.current || !window.AMap) return; + + const currentMarkers = markersRef.current; + const newMarkers = getMapDeviceMarkers(); + + // 清除不存在的标记 + currentMarkers.forEach((marker, deviceSn) => { + if (!newMarkers.find(m => m.device.deviceSn === deviceSn)) { + marker.remove(); + currentMarkers.delete(deviceSn); + } + }); + + // 添加或更新标记 + newMarkers.forEach((markerData) => { + const { device, position, color, status } = markerData; + const existingMarker = currentMarkers.get(device.deviceSn); + + if (existingMarker) { + // 更新现有标记 + existingMarker.setPosition(position); + existingMarker.setIcon({ + type: 'image', + image: createMarkerIcon(color, status), + size: [32, 32], + anchor: 'bottom-center' + }); + } else { + // 创建新标记 + const newMarker = new window.AMap.Marker({ + position, + icon: { + type: 'image', + image: createMarkerIcon(color, status), + size: [32, 32], + anchor: 'bottom-center' + }, + offset: [0, -16], + title: `${device.deviceName} (${DEVICE_STATUS_CONFIG[status].text})` + }); + + // 添加点击事件 + newMarker.on('click', () => { + handleDeviceClick(device, {} as React.MouseEvent); + }); + + // 添加鼠标事件 + newMarker.on('mouseover', () => { + setHoveredDevice(device); + setShowDeviceCard(true); + }); + + newMarker.on('mouseout', () => { + setHoveredDevice(null); + setShowDeviceCard(false); + }); + + newMarker.setMap(mapRef.current); + currentMarkers.set(device.deviceSn, newMarker); + } + }); + }, [devices, mapMarkers]); + + // 当设备数据更新时,更新地图标记 + useEffect(() => { + if (mapInitialized && mapRef.current) { + updateDeviceMarkers(); + } + }, [devices, mapInitialized, updateDeviceMarkers]); + + // WebSocket相关功能 + const initWebSocket = async () => { + try { + const token = await getToken(); + // 根据SDK文档调整WebSocket连接地址 + const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`; + + wsRef.current = new WebSocket(wsUrl); + + wsRef.current.onopen = () => { + console.log('WebSocket连接已建立'); + setWsConnected(true); + startHeartbeat(); + // 连接成功后立即订阅所有设备消息 + console.log('准备订阅所有设备消息...'); + }; + + wsRef.current.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + handleWebSocketMessage(data); + } catch (error) { + console.error('解析WebSocket消息失败:', error); + } + }; + + wsRef.current.onclose = () => { + console.log('WebSocket连接已关闭'); + setWsConnected(false); + scheduleReconnect(); + }; + + wsRef.current.onerror = (error) => { + console.error('WebSocket连接错误:', error); + setWsConnected(false); + }; + } catch (error) { + console.error('初始化WebSocket失败:', error); + setWsConnected(false); + } + }; + + const handleWebSocketMessage = (data: any) => { + console.log('收到WebSocket消息:', data); + + // 根据SDK文档调整消息处理逻辑 + if (data.type === 'result') { + // 处理订阅结果 + if (data.topic && data.topic.includes('/message/property/report')) { + // 设备属性上报 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 4) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + updateDeviceMetrics(deviceSn, data.payload); + } + } else if (data.topic && data.topic.includes('/message/event/fire_alarm')) { + // 设备事件 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 5) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + console.log(`处理设备 ${deviceSn} 的实时数据:`, data.payload); + updateDeviceMetricsFromEvent(deviceSn, data.payload); + } + } else if (data.topic && data.topic.includes('/online')) { + // 设备上线 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 4) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + handleDeviceOnline(deviceSn); + } + } else if (data.topic && data.topic.includes('/offline')) { + // 设备离线 - 从topic中提取产品ID和设备SN + const topicParts = data.topic.split('/'); + if (topicParts.length >= 4) { + const productId = topicParts[2]; + const deviceSn = topicParts[3]; + handleDeviceOffline(deviceSn); + } + } + } else if (data.type === 'authError') { + // 认证失败 + console.error('WebSocket认证失败:', data.message); + message.error('WebSocket认证失败,请检查Token'); + setWsConnected(false); + } else if (data.type === 'error') { + // 其他错误 + console.error('WebSocket错误:', data); + } + }; + + const updateDeviceMetrics = (deviceSn: string, payload: any) => { + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { + ...device, + metrics: { ...device.metrics, ...payload }, + lastUpdateTime: new Date().toISOString() + } + : device + ) + ); + }; + + const updateDeviceMetricsFromEvent = (deviceSn: string, payload: any) => { + // 从fire_alarm事件中提取实时数据 + const eventData = payload.data?.data; + if (!eventData) { + console.warn(`设备 ${deviceSn} 的实时数据格式不正确:`, payload); + return; + } + + // 提取位置信息 + const location = eventData.latitude && eventData.longitude ? { + latitude: eventData.latitude, + longitude: eventData.longitude, + height: eventData.height, + heading: eventData.heading, + updateTime: new Date().toISOString() + } : undefined; + + // 提取电量信息 + const batteryCapacity = eventData.drone_charge_state?.capacity_percent || 0; + const batteryState = eventData.drone_charge_state?.state || 0; + + // 提取环境信息 + const temperature = eventData.temperature || 0; + const humidity = eventData.humidity || 0; + const windSpeed = eventData.wind_speed || 0; + const rainfall = eventData.rainfall || 0; + const environmentTemperature = eventData.environment_temperature || 0; + + // 提取位置质量信息 + const positionQuality = eventData.position_state?.quality || 0; + const isFixed = eventData.position_state?.is_fixed || 0; + const rtkNumber = eventData.position_state?.rtk_number || 0; + const gpsNumber = eventData.position_state?.gps_number || 0; + + // 提取网络信息 + const networkQuality = eventData.network_state?.quality || 0; + const networkRate = eventData.network_state?.rate || 0; + const networkType = eventData.network_state?.type || 0; + + // 提取无人机状态 + const droneInDock = eventData.drone_in_dock || 0; + const modeCode = eventData.mode_code || 0; + + // 提取存储信息 + const storageTotal = eventData.storage?.total || 0; + const storageUsed = eventData.storage?.used || 0; + const diskUsage = storageTotal > 0 ? (storageUsed / storageTotal) * 100 : 0; + + // 提取告警状态 + const alarmState = eventData.alarm_state || 0; + const emergencyStopState = eventData.emergency_stop_state || 0; + + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { + ...device, + location: location || device.location, // 保持原有位置信息如果新数据中没有 + metrics: { + ...device.metrics, + // 环境数据 + temperature, + humidity, + windSpeed, + rainfall, + environmentTemperature, + // 电量数据 + batteryCapacity, + batteryState, + // 位置数据 + positionQuality, + // 网络数据 + networkQuality, + networkRate, + networkType, + // 无人机状态 + droneInDock, + modeCode, + // 存储数据 + diskUsage, + // 告警状态 + errorCount: alarmState > 0 ? (device.metrics.errorCount || 0) + 1 : device.metrics.errorCount || 0, + warningCount: emergencyStopState > 0 ? (device.metrics.warningCount || 0) + 1 : device.metrics.warningCount || 0, + // 信号强度(基于网络质量) + signalStrength: networkQuality, + // 数据速率(基于网络速率) + dataRate: networkRate, + // 更新时间 + uptime: Date.now() - (eventData.first_power_on || Date.now()) + }, + lastUpdateTime: new Date().toISOString() + } + : device + ) + ); + + console.log(`设备 ${deviceSn} 实时数据更新:`, { + location, + batteryCapacity, + temperature, + humidity, + positionQuality, + networkQuality, + droneInDock + }); + }; + + const handleDeviceOnline = (deviceSn: string) => { + console.log(`设备 ${deviceSn} 上线`); + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { ...device, boundStatus: 1 } + : device + ) + ); + }; + + const handleDeviceOffline = (deviceSn: string) => { + console.log(`设备 ${deviceSn} 离线`); + setDevices(prevDevices => + prevDevices.map(device => + device.deviceSn === deviceSn + ? { ...device, boundStatus: 0 } + : device + ) + ); + }; + + const subscribeDeviceMessages = (deviceSn?: string) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + return; + } + + const devicesToSubscribe = deviceSn ? [deviceSn] : devices.map(d => d.deviceSn); + setCurrentSubscriptions(devicesToSubscribe); + + // 订阅设备属性上报 - 使用通配符匹配所有设备 + const propertyMessage = { + type: 'sub', + topic: '/device/*/*/message/property/report', + parameter: {}, + id: `sub_property_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(propertyMessage)); + console.log('订阅设备属性上报:', propertyMessage.topic); + + // 订阅设备事件 - 使用通配符匹配所有设备 + const eventMessage = { + type: 'sub', + topic: '/device/*/*/message/event/fire_alarm', + parameter: {}, + id: `sub_event_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(eventMessage)); + console.log('订阅设备事件:', eventMessage.topic); + + // 订阅设备上线状态 - 使用通配符匹配所有设备 + const onlineMessage = { + type: 'sub', + topic: '/device/*/*/online', + parameter: {}, + id: `sub_online_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(onlineMessage)); + console.log('订阅设备上线:', onlineMessage.topic); + + // 订阅设备离线状态 - 使用通配符匹配所有设备 + const offlineMessage = { + type: 'sub', + topic: '/device/*/*/offline', + parameter: {}, + id: `sub_offline_all_${Date.now()}` + }; + wsRef.current.send(JSON.stringify(offlineMessage)); + console.log('订阅设备离线:', offlineMessage.topic); + }; + + const startHeartbeat = () => { + if (heartbeatTimerRef.current) { + clearInterval(heartbeatTimerRef.current); + } + + heartbeatTimerRef.current = setInterval(() => { + if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { + wsRef.current.send(JSON.stringify({ type: 'ping', timestamp: Date.now() })); + } + }, 30000); // 30秒心跳 + }; + + const scheduleReconnect = () => { + if (reconnectTimerRef.current) { + clearTimeout(reconnectTimerRef.current); + } + + reconnectTimerRef.current = setTimeout(() => { + console.log('尝试重新连接WebSocket...'); + initWebSocket(); + }, 5000); // 5秒后重连 + }; + + // 获取视频流地址 + const getVideoStreamUrl = async (deviceSn: string) => { + try { + const response = await getStreamUrls(deviceSn); + if (response.resp_code === 0 && response.data) { + setAllStreamUrls(response.data); + setVideoStreamUrl(response.data.playM3u8Url); + setCurrentStreamType('hls'); + return response.data; + } else { + message.error('获取视频流地址失败'); + return null; + } + } catch (error) { + console.error('获取视频流地址失败:', error); + message.error('获取视频流地址失败'); + return null; + } + }; + + // 切换视频流类型 + const handleSwitchStreamType = (type: 'hls' | 'flv' | 'rtmp') => { + if (!allStreamUrls) return; + + let url = ''; + switch (type) { + case 'hls': + url = allStreamUrls.playM3u8Url; + break; + case 'flv': + url = allStreamUrls.playFlvUrl; + break; + case 'rtmp': + url = allStreamUrls.playRtmpUrl; + break; + } + + if (url) { + setVideoStreamUrl(url); + setCurrentStreamType(type); + } + }; + + // 无人机控制功能 + const sendControlCommand = async (deviceSn: string, method: string, data: any = {}) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + message.error('WebSocket连接已断开,无法发送控制指令'); + return false; + } + + // 使用正确的主题格式:/device/{产品ID}/{设备SN} + const controlMessage = { + type: 'sub', + topic: `/device/D-Dock2/${deviceSn}`, + parameter: { + messageType: 'WRITE_PROPERTY', + properties: { + method: method, + data: data + }, + headers: { + async: false + } + }, + id: `control_${method}_${deviceSn}_${Date.now()}` + }; + + try { + wsRef.current.send(JSON.stringify(controlMessage)); + console.log(`发送控制指令: ${method}`, controlMessage); + return true; + } catch (error) { + console.error('发送控制指令失败:', error); + message.error('发送控制指令失败'); + return false; + } + }; + + // 摇杆控制 + const handleStickControl = async (deviceSn: string, axis: string, value: number) => { + const controlData = { + roll: 1024, // 右手左右控制(范围:0-2048,1024为中立位) + pitch: 1024, // 右手上下控制(范围:0-2048,1024为中立位) + throttle: 1024, // 左手上下控制(范围:0-2048,1024为中立位) + yaw: 1024, // 左手左右控制(范围:1024±100) + gimbal_pitch: 1024 // 云台画面上下划(范围:0-2048,1024为中立位) + }; + + controlData[axis as keyof typeof controlData] = value; + + const success = await sendControlCommand(deviceSn, 'stick_control', controlData); + if (success) { + message.success(`摇杆控制指令已发送: ${axis} = ${value}`); + } + }; + + // 相机模式切换 + const handleCameraModeSwitch = async (deviceSn: string, mode: number) => { + const modeText = ['拍照', '录像', '智能低光', '全景拍照'][mode] || '未知模式'; + const success = await sendControlCommand(deviceSn, 'camera_mode_switch', { camera_mode: mode }); + if (success) { + message.success(`相机模式已切换为: ${modeText}`); + } + }; + + // 拍照 + const handleTakePhoto = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'camera_photo_take', {}); + if (success) { + message.success('拍照指令已发送'); + } + }; + + // 开始录像 + const handleStartRecording = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'camera_recording_start', {}); + if (success) { + message.success('开始录像指令已发送'); + } + }; + + // 停止录像 + const handleStopRecording = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'camera_recording_stop', {}); + if (success) { + message.success('停止录像指令已发送'); + } + }; + + // 暂停航线任务 + const handlePauseTask = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'flighttask_pause', {}); + if (success) { + message.success('航线任务已暂停'); + } + }; + + // 返航 + const handleReturnHome = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'return_home', {}); + if (success) { + message.success('返航指令已发送'); + } + }; + + // 进入指令飞行模式 + const handleEnterDRCMode = async (deviceSn: string) => { + const success = await sendControlCommand(deviceSn, 'drc_mode_enter', {}); + if (success) { + message.success('已进入指令飞行模式'); + } + }; + + // 地图样式切换处理 + const handleMapStyleChange = () => { + const styleOrder: ('normal' | 'dark' | 'satellite')[] = ['normal', 'dark', 'satellite']; + const currentIndex = styleOrder.indexOf(mapType); + const nextIndex = (currentIndex + 1) % styleOrder.length; + const nextStyle = styleOrder[nextIndex]; + + setMapType(nextStyle); + + // 更新地图样式 + if (mapRef.current) { + mapRef.current.setMapStyle(mapStyles[nextStyle]); + } + }; + + // 地图加载错误处理 + const handleMapError = (error: any) => { + console.error('地图加载错误:', error); + if (mapType === 'satellite') { + message.warning('卫星图加载失败,已切换到普通图'); + setMapType('normal'); + } + }; + + // 安全的地图初始化方法 + const safeInitMap = (container: HTMLElement) => { + try { + const map = new window.AMap.Map(container, { + zoom: mapZoom, + center: mapCenter, + mapStyle: mapStyles[mapType], + viewMode: '2D', + features: ['bg', 'road'], + showBuildingBlock: false, + resizeEnable: true, + }); + + // 添加地图控件 + try { + if (window.AMap.Scale) { + map.addControl(new window.AMap.Scale()); + } + if (window.AMap.ToolBar) { + map.addControl(new window.AMap.ToolBar()); + } + } catch (error) { + console.warn('添加地图控件失败:', error); + } + + // 监听地图事件 + try { + map.on('zoomend', () => { + setMapZoom(map.getZoom()); + }); + + map.on('moveend', () => { + const center = map.getCenter(); + setMapCenter([center.lng, center.lat]); + }); + } catch (error) { + console.warn('添加地图事件监听失败:', error); + } + + return map; + } catch (error) { + console.error('创建地图实例失败:', error); + throw error; + } + }; + + // 安全的地图刷新方法 + const safeRefreshMap = () => { + if (mapRef.current) { + try { + // 尝试不同的刷新方法 + if (typeof mapRef.current.resize === 'function') { + mapRef.current.resize(); + return true; + } else if (typeof mapRef.current.setFitView === 'function') { + mapRef.current.setFitView(); + return true; + } else if (typeof mapRef.current.setZoomAndCenter === 'function') { + mapRef.current.setZoomAndCenter(mapZoom, mapCenter); + return true; + } else { + console.log('地图刷新方法不可用'); + return false; + } + } catch (error) { + console.warn('地图刷新失败:', error); + return false; + } + } + return false; + }; + + return ( +
+ {/* 顶部控制栏 */} +
+ + + + 设备运维地图 + + + + + + + + setSearchKeyword(e.target.value)} + style={{ width: 200 }} + prefix={} + /> + + + + + + + + + + + + + + + + + + + + + + + 设备: {devices.length} | 在线: {deviceStats.online} | 离线: {deviceStats.offline} + + + {wsConnected && ( + + 已订阅: 属性上报 | 事件 | 上线/离线 + + )} + + {devices.some(d => d.lastUpdateTime) && ( + + 最后更新: {new Date(Math.max(...devices.filter(d => d.lastUpdateTime).map(d => new Date(d.lastUpdateTime!).getTime()))).toLocaleTimeString()} + + )} + + + +
+ + {/* 地图区域 */} +
+
+ {/* 高德地图容器 */} +
+ + {/* 设备卡片(悬停显示) */} + {showDeviceCard && hoveredDevice && ( +
+
+ {hoveredDevice.deviceName} + + {DEVICE_STATUS_CONFIG[getDeviceStatus(hoveredDevice)].text} + +
+
+
编号: {hoveredDevice.deviceSn}
+
类型: {hoveredDevice.deviceType}
+
电量: {hoveredDevice.metrics.batteryCapacity}%
+
网络: {hoveredDevice.metrics.networkQuality}%
+
温度: {hoveredDevice.metrics.temperature}°C
+
湿度: {hoveredDevice.metrics.humidity}%
+ {hoveredDevice.metrics.droneInDock !== undefined && ( +
机库: {hoveredDevice.metrics.droneInDock === 1 ? '在库' : '离库'}
+ )} + {hoveredDevice.location && ( +
位置: {hoveredDevice.location.latitude.toFixed(4)}, {hoveredDevice.location.longitude.toFixed(4)}
+ )} + {hoveredDevice.lastUpdateTime && ( +
更新: {new Date(hoveredDevice.lastUpdateTime).toLocaleTimeString()}
+ )} +
+
+ )} + + {/* 地图加载状态覆盖层 */} + {!mapInitialized && ( +
+
地图加载中...
+
+ mapInitialized: {mapInitialized ? 'true' : 'false'} +
+
+ 设备数量: {mapMarkers.length} +
+
+ AMap: {typeof window !== 'undefined' && window.AMap ? '已加载' : '未加载'} +
+
+ 地图容器: {mapContainerRef.current ? '已创建' : '未创建'} +
+
+ 地图实例: {mapRef.current ? '已创建' : '未创建'} +
+
+ )} +
+
+ + {/* 左侧统计面板 */} + {leftPanelVisible && ( +
+ setLeftPanelCollapsed(true)} + > + - + + )} + style={{ height: '100%', overflow: 'auto' }} + > + {leftPanelCollapsed ? ( +
+ +
+ ) : ( + <> + {/* 统计卡片 */} + + + + } + valueStyle={{ color: '#1890ff' }} + /> + + + + + } + valueStyle={{ color: '#52c41a' }} + suffix={`/ ${deviceStats.total}`} + /> + + + + + } + valueStyle={{ color: '#52c41a' }} + /> + + + + + } + valueStyle={{ color: '#ff4d4f' }} + /> + + + + + {/* 按分组统计 */} +
+
+ 景区分布 +
+ {Object.entries(deviceStats.byGroup).map(([group, count]) => ( +
+ {group} + {count} +
+ ))} +
+ + {/* 设备列表 */} +
+
+ 设备列表 ({memoizedDeviceList.length}) +
+
+ {memoizedDeviceList.map(device => ( +
locateDeviceOnMap(device)} + onMouseEnter={(e) => { + e.currentTarget.style.backgroundColor = '#f5f5f5'; + }} + onMouseLeave={(e) => { + e.currentTarget.style.backgroundColor = selectedDevice?.deviceSn === device.deviceSn ? '#e6f7ff' : '#fff'; + }} + > +
+
+
+ {device.deviceName} +
+
+ {device.deviceSn} +
+
+ + {device.statusConfig.text} + +
+
+ 电量: {device.metrics.batteryCapacity}% | 网络: {device.metrics.networkQuality}% | 温度: {device.metrics.temperature}°C + {device.lastUpdateTime && ( + + {new Date(device.lastUpdateTime).toLocaleTimeString()} + + )} +
+
+ ))} +
+
+ + )} +
+
+ )} + + {/* 右侧详情面板 */} + {rightPanelVisible && selectedDevice && ( +
+ + + + + )} + style={{ height: '100%', overflow: 'auto' }} + > + {rightPanelCollapsed ? ( +
+ +
+ ) : ( + <> + {/* 设备基本信息 */} + + {selectedDevice.deviceName} + {selectedDevice.deviceSn} + {selectedDevice.deviceType} + + + {DEVICE_STATUS_CONFIG[getDeviceStatus(selectedDevice)].text} + + + {selectedDevice.loginTime} + {selectedDevice.lastUpdateTime && ( + {selectedDevice.lastUpdateTime} + )} + {selectedDevice.metrics.lastMaintenance && ( + {selectedDevice.metrics.lastMaintenance} + )} + {selectedDevice.metrics.nextMaintenance && ( + {selectedDevice.metrics.nextMaintenance} + )} + + + + + {/* 操作按钮 */} +
+ 设备操作 + + + + + +
+ + {/* 无人机控制面板 */} + {selectedDevice.deviceType === 1 && ( + <> + +
+ 无人机控制 + + {/* 相机控制 */} +
+
相机控制
+ + + + + +
+ + {/* 相机模式切换 */} +
+
相机模式
+ + + + + + +
+ + {/* 飞行控制 */} +
+
飞行控制
+ + + + + +
+ + {/* 摇杆控制 */} +
+
摇杆控制
+
+ 范围:0-2048,1024为中立位 +
+ + +
Roll (左右)
+ handleStickControl(selectedDevice.deviceSn, 'roll', value)} + style={{ width: '100%' }} + /> + + +
Pitch (上下)
+ handleStickControl(selectedDevice.deviceSn, 'pitch', value)} + style={{ width: '100%' }} + /> + + +
Throttle (油门)
+ handleStickControl(selectedDevice.deviceSn, 'throttle', value)} + style={{ width: '100%' }} + /> + + +
Yaw (偏航)
+ handleStickControl(selectedDevice.deviceSn, 'yaw', value)} + style={{ width: '100%' }} + /> + +
+
+
+ + )} + + {/* 实时数据 */} +
+ 实时数据 + + +
+
电量
+
+ {selectedDevice.metrics.batteryCapacity}% +
+
+ + +
+
网络质量
+
+ {selectedDevice.metrics.networkQuality}% +
+
+ + +
+
温度
+
+ {selectedDevice.metrics.temperature}°C +
+
+ + +
+
湿度
+
+ {selectedDevice.metrics.humidity}% +
+
+ + +
+
风速
+
+ {selectedDevice.metrics.windSpeed}m/s +
+
+ + +
+
降雨量
+
+ {selectedDevice.metrics.rainfall}mm +
+
+ +
+
+ + {/* 无人机特有信息 */} + {selectedDevice.deviceType === 1 && ( + <> + +
+ 飞行信息 + + +
+
飞行模式
+
+ {selectedDevice.metrics.modeCode > 0 ? '执行中' : '待机'} +
+
+ + +
+
机库状态
+
+ {selectedDevice.metrics.droneInDock === 1 ? '在库' : '离库'} +
+
+ + +
+
位置质量
+
= 4 ? '#52c41a' : '#ff4d4f' }}> + {selectedDevice.metrics.positionQuality}/5 +
+
+ + +
+
告警状态
+
0 ? '#ff4d4f' : '#52c41a' }}> + {(selectedDevice.metrics.errorCount + selectedDevice.metrics.warningCount) > 0 ? '异常' : '正常'} +
+
+ +
+
+ + )} + + {/* 维护信息 */} + {(selectedDevice.metrics.lastMaintenance || selectedDevice.metrics.nextMaintenance) && ( + <> + +
+ 维护信息 + {selectedDevice.metrics.lastMaintenance && ( +
+ 最后维护: + {selectedDevice.metrics.lastMaintenance} +
+ )} + {selectedDevice.metrics.nextMaintenance && ( +
+ 下次维护: + {selectedDevice.metrics.nextMaintenance} +
+ )} +
+ + )} + + + + {/* 位置信息 */} +
+ 位置信息 + {selectedDevice.location ? ( +
+
纬度: {selectedDevice.location.latitude.toFixed(6)}
+
经度: {selectedDevice.location.longitude.toFixed(6)}
+ {selectedDevice.location.height && ( +
高度: {selectedDevice.location.height}m
+ )} +
+ ) : ( +
+ 暂无位置信息 +
+ )} +
+ + )} +
+
+ )} + + {/* 视频播放弹窗 */} + setVideoStreamVisible(false)} + width={800} + footer={null} + destroyOnClose + > +
+ {videoLoading ? ( +
+
正在加载视频流...
+
+ ) : videoStreamUrl ? ( +
+
+ + + + + +
+
+ { + console.error('视频播放错误:', error); + message.error('视频播放失败,请检查网络连接'); + }} + /> +
+
+ ) : ( +
+
暂无视频流
+
+ )} +
+
+
+ ); +}; + +export default DeviceMapDashboard; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/mock/devices.ts b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/mock/devices.ts new file mode 100644 index 00000000..8e596ecc --- /dev/null +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/mock/devices.ts @@ -0,0 +1,217 @@ +import moment from 'moment'; + +// 设备状态枚举 +export enum DeviceStatus { + TASK = 'task', // 任务中 - 绿色 + STANDBY = 'standby', // 待机 - 蓝色 + MAINTENANCE = 'maintenance', // 维护 - 橙色 + ERROR = 'error', // 异常 - 红色 + OFFLINE = 'offline' // 离线 - 灰色 +} + +// 设备状态配置 +export const DEVICE_STATUS_CONFIG = { + [DeviceStatus.TASK]: { + color: '#52c41a', + icon: '▶️', + text: '任务中', + bgColor: '#f6ffed' + }, + [DeviceStatus.STANDBY]: { + color: '#1890ff', + icon: '⏰', + text: '待机', + bgColor: '#f0f8ff' + }, + [DeviceStatus.MAINTENANCE]: { + color: '#fa8c16', + icon: '🔧', + text: '维护', + bgColor: '#fff7e6' + }, + [DeviceStatus.ERROR]: { + color: '#ff4d4f', + icon: '⚠️', + text: '异常', + bgColor: '#fff2f0' + }, + [DeviceStatus.OFFLINE]: { + color: '#8c8c8c', + icon: '❌', + text: '离线', + bgColor: '#f5f5f5' + } +}; + +// 设备类型 +export interface Device { + id: string; + name: string; + sn: string; + type: string; + status: DeviceStatus; + location: { + latitude: number; + longitude: number; + altitude?: number; + }; + battery: number; + signal: number; + temperature: number; + humidity: number; + lastUpdate: string; + group?: string; + description?: string; + // 新增字段 + batteryCycles?: number; // 电池循环次数 + flightHours?: number; // 飞行时长 + lastMaintenance?: string; // 最后维护时间 + nextMaintenance?: string; // 下次维护时间 + operator?: string; // 操作员 + ipAddress?: string; // IP地址 + firmwareVersion?: string; // 固件版本 +} + +// 景区位置数据(北京周边景区) +const SCENIC_SPOTS = [ + { name: '颐和园', lat: 39.9999, lng: 116.2755, group: '颐和园景区' }, + { name: '天坛公园', lat: 39.8822, lng: 116.4066, group: '天坛景区' }, + { name: '故宫博物院', lat: 39.9163, lng: 116.3972, group: '故宫景区' }, + { name: '八达岭长城', lat: 40.3569, lng: 116.0200, group: '长城景区' }, + { name: '圆明园', lat: 40.0084, lng: 116.2995, group: '圆明园景区' }, + { name: '香山公园', lat: 39.9944, lng: 116.1955, group: '香山景区' }, + { name: '北海公园', lat: 39.9254, lng: 116.3897, group: '北海景区' }, + { name: '景山公园', lat: 39.9244, lng: 116.3974, group: '景山景区' }, + { name: '天安门广场', lat: 39.9054, lng: 116.3976, group: '天安门景区' }, + { name: '奥林匹克公园', lat: 40.0024, lng: 116.3974, group: '奥体景区' }, +]; + +// 设备类型配置 +const DEVICE_TYPES = [ + { type: '无人机', prefix: 'UAV', description: '航拍无人机设备' }, + { type: '摄像头', prefix: 'CAM', description: '监控摄像头设备' }, + { type: '传感器', prefix: 'SEN', description: '环境监测传感器' }, + { type: '控制器', prefix: 'CTL', description: '智能控制器设备' }, + { type: '基站', prefix: 'BS', description: '通信基站设备' }, +]; + +// 生成随机位置(在指定景区附近) +const generateLocation = (scenicSpot: any) => { + // 在景区周围500米范围内随机生成位置 + const radius = 0.005; // 约500米 + const angle = Math.random() * 2 * Math.PI; + const distance = Math.random() * radius; + + const lat = scenicSpot.lat + distance * Math.cos(angle); + const lng = scenicSpot.lng + distance * Math.sin(angle); + + return { + latitude: lat, + longitude: lng, + altitude: Math.floor(Math.random() * 100) + 50 + }; +}; + +// 生成模拟设备数据 +export const generateMockDevices = (): Device[] => { + const mockDevices: Device[] = []; + + // 为每个景区生成2-4个设备 + SCENIC_SPOTS.forEach((spot, spotIndex) => { + const deviceCount = Math.floor(Math.random() * 3) + 2; // 2-4个设备 + + for (let i = 1; i <= deviceCount; i++) { + const deviceType = DEVICE_TYPES[Math.floor(Math.random() * DEVICE_TYPES.length)]; + const status = Object.values(DeviceStatus)[Math.floor(Math.random() * Object.values(DeviceStatus).length)]; + const deviceId = `${spotIndex + 1}_${i}`; + + // 生成设备编号 + const sn = `${deviceType.prefix}${(spotIndex + 1).toString().padStart(2, '0')}${i.toString().padStart(2, '0')}`; + + // 生成位置 + const location = generateLocation(spot); + + // 生成电池循环次数(仅无人机) + const batteryCycles = deviceType.type === '无人机' ? Math.floor(Math.random() * 200) + 1 : undefined; + + // 生成飞行时长(仅无人机) + const flightHours = deviceType.type === '无人机' ? Math.floor(Math.random() * 1000) + 10 : undefined; + + // 生成维护时间 + const lastMaintenance = moment().subtract(Math.floor(Math.random() * 30), 'days').format('YYYY-MM-DD'); + const nextMaintenance = moment().add(Math.floor(Math.random() * 30) + 7, 'days').format('YYYY-MM-DD'); + + mockDevices.push({ + id: `device_${deviceId}`, + name: `${deviceType.type}${deviceId}`, + sn, + type: deviceType.type, + status, + location, + battery: Math.floor(Math.random() * 100) + 1, + signal: Math.floor(Math.random() * 100) + 1, + temperature: Math.floor(Math.random() * 40) + 10, + humidity: Math.floor(Math.random() * 60) + 20, + lastUpdate: moment().subtract(Math.floor(Math.random() * 60), 'minutes').format('YYYY-MM-DD HH:mm:ss'), + group: spot.group, + description: `${deviceType.description},位于${spot.name}`, + batteryCycles, + flightHours, + lastMaintenance, + nextMaintenance, + operator: `操作员${Math.floor(Math.random() * 10) + 1}`, + ipAddress: `192.168.${Math.floor(Math.random() * 255) + 1}.${Math.floor(Math.random() * 255) + 1}`, + firmwareVersion: `v${Math.floor(Math.random() * 5) + 1}.${Math.floor(Math.random() * 10)}.${Math.floor(Math.random() * 10)}` + }); + } + }); + + return mockDevices; +}; + +// 设备统计接口 +export interface DeviceStats { + total: number; + online: number; + offline: number; + task: number; + standby: number; + maintenance: number; + error: number; + byGroup: Record; + byType: Record; +} + +// 计算设备统计 +export const calculateDeviceStats = (devices: Device[]): DeviceStats => { + const stats: DeviceStats = { + total: devices.length, + online: devices.filter(d => d.status !== DeviceStatus.OFFLINE).length, + offline: devices.filter(d => d.status === DeviceStatus.OFFLINE).length, + task: devices.filter(d => d.status === DeviceStatus.TASK).length, + standby: devices.filter(d => d.status === DeviceStatus.STANDBY).length, + maintenance: devices.filter(d => d.status === DeviceStatus.MAINTENANCE).length, + error: devices.filter(d => d.status === DeviceStatus.ERROR).length, + byGroup: {}, + byType: {} + }; + + // 按分组统计 + devices.forEach(device => { + if (device.group) { + stats.byGroup[device.group] = (stats.byGroup[device.group] || 0) + 1; + } + stats.byType[device.type] = (stats.byType[device.type] || 0) + 1; + }); + + return stats; +}; + +// 获取景区列表 +export const getScenicSpots = () => { + return SCENIC_SPOTS.map(spot => ({ + name: spot.name, + group: spot.group, + location: { latitude: spot.lat, longitude: spot.lng } + })); +}; \ No newline at end of file diff --git a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx index f4f39aeb..eb9cd6d5 100644 --- a/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx +++ b/zlt-web/react-web/src/main/frontend/src/pages/device-ops/monitor/index.tsx @@ -13,7 +13,9 @@ import { DashboardOutlined, BarChartOutlined, SettingOutlined, BellOutlined, EyeOutlined, ReloadOutlined, DownloadOutlined, FilterOutlined, PlayCircleOutlined, PauseCircleOutlined, StopOutlined, CameraOutlined, - VideoCameraOutlined, SoundOutlined, BulbOutlined, ToolOutlined + VideoCameraOutlined, SoundOutlined, BulbOutlined, ToolOutlined, + ControlOutlined, HomeOutlined, PauseOutlined, PlayOutlined, + CameraOutlined as CameraIcon, VideoCameraOutlined as VideoIcon } from '@ant-design/icons'; import { device, getStreamUrls } from '@/services/device/api'; import { request } from 'umi'; @@ -434,6 +436,30 @@ const DeviceMonitor: React.FC = () => { const [useReactPlayer, setUseReactPlayer] = useState(true); const [videoStreamStatus, setVideoStreamStatus] = useState<'loading' | 'playing' | 'error' | 'ended' | 'stalled'>('loading'); + // 设备控制相关状态 + const [controlVisible, setControlVisible] = useState(false); + const [currentControlDevice, setCurrentControlDevice] = useState(null); + const [controlLoading, setControlLoading] = useState(false); + const [controlError, setControlError] = useState(''); + const [controlSuccess, setControlSuccess] = useState(''); + + // 摇杆控制状态 + const [stickControl, setStickControl] = useState({ + roll: 1024, // 右手左右控制 + pitch: 1024, // 右手上下控制 + throttle: 1024, // 左手上下控制 + yaw: 1024, // 左手左右控制 + gimbal_pitch: 1024 // 云台画面上下划 + }); + + // 相机控制状态 + const [cameraMode, setCameraMode] = useState(0); // 0=拍照,1=录像,2=智能低光,3=全景拍照 + const [isRecording, setIsRecording] = useState(false); + + // 飞行控制状态 + const [flightMode, setFlightMode] = useState<'idle' | 'manual' | 'task' | 'return'>('idle'); + const [isInDRCMode, setIsInDRCMode] = useState(false); + const tokenCache = { value: '', expire: 0, @@ -1487,6 +1513,9 @@ const DeviceMonitor: React.FC = () => { handlePlayVideo(record)}> 视频流 + handleOpenControl(record)}> + 设备控制 + ), }, @@ -2069,11 +2098,20 @@ const DeviceMonitor: React.FC = () => { } }; - // 录制功能 - const handleToggleRecording = () => { - setVideoRecording(!videoRecording); - // 这里可以添加实际的录制逻辑 - console.log('录制状态:', !videoRecording); + // 开始/停止录像 + const handleToggleVideoRecording = async () => { + if (!currentControlDevice) return; + + const method = isRecording ? 'camera_recording_stop' : 'camera_recording_start'; + const success = await sendControlCommand( + currentControlDevice.deviceSn, + method + ); + + if (success) { + setIsRecording(!isRecording); + setControlSuccess(isRecording ? '停止录像指令已发送' : '开始录像指令已发送'); + } }; // 全屏功能 @@ -2481,6 +2519,218 @@ const DeviceMonitor: React.FC = () => { ); }; + // 发送设备控制指令 + const sendControlCommand = async (deviceSn: string, method: string, data: any = {}) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { + setControlError('WebSocket连接未建立,无法发送控制指令'); + return false; + } + + try { + setControlLoading(true); + setControlError(''); + setControlSuccess(''); + + const messageId = `control-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; + + const controlMessage = { + type: "sub", + topic: `/device-message-sender/D-Dock2/${deviceSn}`, + parameter: { + messageType: "WRITE_PROPERTY", + properties: { + method: method, + data: data + }, + headers: { + async: false + } + }, + id: messageId + }; + + console.log('发送控制指令:', JSON.stringify(controlMessage, null, 2)); + + wsRef.current.send(JSON.stringify(controlMessage)); + + // 等待响应 + return new Promise((resolve) => { + const timeout = setTimeout(() => { + setControlError('控制指令超时,请检查设备状态'); + setControlLoading(false); + resolve(false); + }, 10000); // 10秒超时 + + const originalOnMessage = wsRef.current!.onmessage; + wsRef.current!.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + if (data.type === 'result' && data.id === messageId) { + clearTimeout(timeout); + setControlLoading(false); + + if (data.payload && data.payload.success !== false) { + setControlSuccess('控制指令执行成功'); + resolve(true); + } else { + setControlError(data.payload?.message || '控制指令执行失败'); + resolve(false); + } + + // 恢复原始消息处理 + if (originalOnMessage) { + wsRef.current!.onmessage = originalOnMessage; + } + } else { + // 继续处理其他消息 + if (originalOnMessage) { + originalOnMessage.call(wsRef.current!, event); + } + } + } catch (error) { + console.error('解析控制响应失败:', error); + } + }; + }); + } catch (error) { + console.error('发送控制指令失败:', error); + setControlError('发送控制指令失败'); + setControlLoading(false); + return false; + } + }; + + // 摇杆控制 + const handleStickControl = async (axis: string, value: number) => { + if (!currentControlDevice) return; + + const newStickControl = { ...stickControl, [axis]: value }; + setStickControl(newStickControl); + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'stick_control', + newStickControl + ); + + if (success) { + console.log('摇杆控制成功:', axis, value); + } + }; + + // 相机模式切换 + const handleCameraModeSwitch = async (mode: number) => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'camera_mode_switch', + { camera_mode: mode } + ); + + if (success) { + setCameraMode(mode); + setControlSuccess(`相机模式切换为: ${getCameraModeText(mode)}`); + } + }; + + // 拍照 + const handleTakePhoto = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'camera_photo_take' + ); + + if (success) { + setControlSuccess('拍照指令已发送'); + } + }; + + // 暂停航线任务 + const handlePauseTask = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'flighttask_pause' + ); + + if (success) { + setFlightMode('idle'); + setControlSuccess('航线任务已暂停'); + } + }; + + // 返航 + const handleReturnHome = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'return_home' + ); + + if (success) { + setFlightMode('return'); + setControlSuccess('返航指令已发送'); + } + }; + + // 进入DRC模式 + const handleEnterDRCMode = async () => { + if (!currentControlDevice) return; + + const success = await sendControlCommand( + currentControlDevice.deviceSn, + 'drc_mode_enter' + ); + + if (success) { + setIsInDRCMode(true); + setFlightMode('manual'); + setControlSuccess('已进入指令飞行模式'); + } + }; + + // 获取相机模式文本 + const getCameraModeText = (mode: number) => { + const modeMap: Record = { + 0: '拍照', + 1: '录像', + 2: '智能低光', + 3: '全景拍照' + }; + return modeMap[mode] || '未知模式'; + }; + + // 打开设备控制面板 + const handleOpenControl = (device: Device) => { + setCurrentControlDevice(device); + setControlVisible(true); + setControlError(''); + setControlSuccess(''); + setControlLoading(false); + }; + + // 关闭设备控制面板 + const handleCloseControl = () => { + setControlVisible(false); + setCurrentControlDevice(null); + setControlError(''); + setControlSuccess(''); + setControlLoading(false); + // 重置摇杆到中立位 + setStickControl({ + roll: 1024, + pitch: 1024, + throttle: 1024, + yaw: 1024, + gimbal_pitch: 1024 + }); + }; + return ( {/* 顶部控制栏 */} @@ -3208,7 +3458,7 @@ const DeviceMonitor: React.FC = () => { ,
+ + {/* 设备控制弹窗 */} + + + {currentControlDevice ? `${currentControlDevice.deviceName} 设备控制` : '设备控制'} + + } + open={controlVisible} + onCancel={handleCloseControl} + footer={[ + , + ]} + width={1000} + destroyOnClose + > +
+ {/* 状态提示 */} + {controlError && ( + + )} + + {controlSuccess && ( + + )} + + {controlLoading && ( + + )} + + + {/* 飞行控制标签页 */} + + + + + + + + + + + + + + + + + + + + {flightMode === 'idle' ? '空闲' : + flightMode === 'manual' ? '手动控制' : + flightMode === 'task' ? '任务执行' : + flightMode === 'return' ? '返航中' : '未知'} + + + + + {isInDRCMode ? '已启用' : '未启用'} + + + + + {currentControlDevice?.boundStatus === 1 ? '在线' : '离线'} + + + + + + + + + {/* 摇杆控制标签页 */} + + + + + +
+ 左右控制 (Roll): {stickControl.roll} + handleStickControl('roll', value)} + disabled={controlLoading || !isInDRCMode} + /> +
+
+ 上下控制 (Pitch): {stickControl.pitch} + handleStickControl('pitch', value)} + disabled={controlLoading || !isInDRCMode} + /> +
+
+
+ + + + + +
+ 上下控制 (Throttle): {stickControl.throttle} + handleStickControl('throttle', value)} + disabled={controlLoading || !isInDRCMode} + /> +
+
+ 左右控制 (Yaw): {stickControl.yaw} + handleStickControl('yaw', value)} + disabled={controlLoading || !isInDRCMode} + /> +
+
+
+ + + + +
+ 云台上下 (Gimbal Pitch): {stickControl.gimbal_pitch} + handleStickControl('gimbal_pitch', value)} + disabled={controlLoading || !isInDRCMode} + /> +
+
+ +
+
+ + {/* 相机控制标签页 */} + + + + + +
+ 当前模式: {getCameraModeText(cameraMode)} +
+ + + + +
+
+ + + + + + + + + + + +
+
+
+
+
); };