From 26dadc95cf477c103a77e941a3efab9ea6943628 Mon Sep 17 00:00:00 2001 From: mmc <1556375442@qq.com> Date: Thu, 11 Jun 2026 17:02:23 +0800 Subject: [PATCH] =?UTF-8?q?f=E5=B0=81=E8=A3=85=E5=AE=8C=E6=88=90=E7=82=B9?= =?UTF-8?q?=20=20=20=E6=97=A0=E4=BA=BA=E6=9C=BA=E5=92=8C=20=E6=9C=BA?= =?UTF-8?q?=E5=99=A8=E4=BA=BA=20=E5=9C=B0=E5=9B=BE=E6=B8=85=E7=A9=BA?= =?UTF-8?q?=E5=AE=9E=E6=97=B6=E8=BD=A8=E8=BF=B9=E5=92=8C=E6=B8=85=E7=A9=BA?= =?UTF-8?q?=E8=A7=84=E5=88=92=E8=BD=A8=E8=BF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Map.jsx | 487 ++++++++++++++++---- src/components/devices/DeviceStatusPage.tsx | 43 ++ src/components/devices/RobotTaskPage.tsx | 43 +- src/components/devices/WayLinePage.tsx | 31 +- src/components/devices/deviceController.js | 17 +- src/lib/TracePoint/tracePoint.js | 230 ++++----- 6 files changed, 586 insertions(+), 265 deletions(-) diff --git a/src/components/Map.jsx b/src/components/Map.jsx index 9e4c0ed..cd294bb 100644 --- a/src/components/Map.jsx +++ b/src/components/Map.jsx @@ -4,10 +4,11 @@ import inspectImg from "../assets/images/inspectCar.png" import planeImg from '../assets/images/plane.png'; import cameraImg from '../assets/images/camera.png'; import droneInspectImg from '../assets/images/xunjiancar.png'; -import gecaocar from '../assets/images/gecaocar.png'; +import gecocar from '../assets/images/gecaocar.png'; import arrowImg from '../assets/images/arrow.png'; import iotImg from '../assets/images/iot.png'; import envConfig from '../../env'; +import { TracePoint, TPAction, TPMode } from '../lib/TracePoint/tracePoint'; const CYAN_ALARM_COLOR = new window.Cesium.Color( @@ -25,7 +26,7 @@ const CYAN_GLOW_COLOR = new window.Cesium.Color( ); window.Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNjk0NjI1MC0wZGYyLTQ1YzItYjJmZi0wY2M5ODEwODllYzIiLCJpZCI6Mzk3MTQxLCJpYXQiOjE3NzI1MjkwMjV9.U6qmakhDgXJVXwLFyWzSxAUOFZRrDkIsRUPP6CCdnKg"; -export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], onPathChange, from, onClearDraw }) { +export default function CesiumMap({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], onPathChange, from, onClearDraw }) { const containerRef = useRef(null); const viewerRef = useRef(null); const tooltipRef = useRef(null); @@ -34,12 +35,18 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType const entityMapRef = useRef(new Map()); const alarmMapRef = useRef(new Map()); const iotMapRef = useRef(new Map()); - const trackLineRef = useRef(null); + const planLineRef = useRef(null); // points 规划航线 + const navLineRef = useRef(null); // 完成点实时轨迹 const realtimeEntityRef = useRef(null); const realtimeLineRef = useRef(null); const realtimeTrackRef = useRef([]); + const tracePointRef = useRef(new TracePoint()); + const lastFinishPointRef = useRef(null); + const isNavigationModeRef = useRef(false); + const followCarEntityRef = useRef(null); // 跟随小车的实例 + const isCameraFlyingRef = useRef(false); const lastFlightPromiseRef = useRef(null); @@ -171,8 +178,8 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType !isNaN(Number(realtimePosition.lat)) ); - if (trackLineRef.current) { - viewer.entities.remove(trackLineRef.current); + if (planLineRef.current) { + viewer.entities.remove(planLineRef.current); } // 2. 传入的 points 本身为空 → 清空轨迹退出 @@ -180,9 +187,9 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType const viewer = viewerRef.current; if (viewer) { try { - if (trackLineRef.current) { - viewer.entities.remove(trackLineRef.current); - trackLineRef.current = null; + if (planLineRef.current) { + viewer.entities.remove(planLineRef.current); + planLineRef.current = null; } } catch (e) { } viewer.scene.requestRender(); // 强制刷新! @@ -216,14 +223,14 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType polyline: { positions: positions, width: 2, - // 实线 + 纯蓝色(核心修改) - material: Cesium.Color.BLUE.withAlpha(0.9), // 半透明蓝色实线,更美观 + // 规划航线用橙色,和实时轨迹区分 + material: Cesium.Color.ORANGE.withAlpha(0.8), clampToGround: true, disableDepthTestDistance: Number.POSITIVE_INFINITY, }, }); - trackLineRef.current = trackLine; + planLineRef.current = trackLine; // ====================== // 🚀 非实时模式 -> 自动飞到轨迹 @@ -821,6 +828,203 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType } const yellowCircleImg = useMemo(() => createYellowCircleDataUrl(30), []); + // 处理完成点 + useEffect(() => { + if (!finishPoint || !finishPoint.lng || !finishPoint.lat || !drawRealTime) { + // 没有 finishPoint 时,移除跟随小车 + const viewer = viewerRef.current; + if (viewer && followCarEntityRef.current) { + viewer.entities.remove(followCarEntityRef.current); + followCarEntityRef.current = null; + } + return; + } + console.log(22222222222) + + + + const point = { lng: finishPoint.lng, lat: finishPoint.lat }; + console.log(isNavigationModeRef.current, drawRealTime, 8888888888) + + // 如果是定位模式且还没有导航模式,则切换到导航模式 + if (!isNavigationModeRef.current && drawRealTime) { + tracePointRef.current.setMode(TPMode.NAVIGATION); + isNavigationModeRef.current = true; + } + console.log(444444444) + + + tracePointRef.current.upsert(point, TPAction.ADD); + lastFinishPointRef.current = finishPoint; + + // 更新轨迹绘制 + updateTraceLine(); + + // 更新或添加跟随小车 + + }, [finishPoint, drawRealTime]); + + // 更新跟随小车 + const updateFollowCar = (cartesianPos, heading = 0) => { + const viewer = viewerRef.current; + if (!viewer || !cartesianPos) return; + const Cesium = window.Cesium; + + const hpr = new Cesium.HeadingPitchRoll(heading, 0, 0); + const orientation = Cesium.Transforms.headingPitchRollQuaternion(cartesianPos, hpr); + + if (followCarEntityRef.current) { + followCarEntityRef.current.position = cartesianPos; + followCarEntityRef.current.orientation = orientation; + } else { + followCarEntityRef.current = viewer.entities.add({ + position: cartesianPos, + orientation: orientation, + billboard: { + image: carImg, + width: 50, + height: 50, + verticalOrigin: Cesium.VerticalOrigin.BOTTOM, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + color: Cesium.Color.YELLOW.withAlpha(0.8), + }, + }); + } + }; + + + + const updateTraceLine = (clear = false) => { + const viewer = viewerRef.current; + if (!viewer) return; + const Cesium = window.Cesium; + + // 主动清空 或 轨迹数据为空:统一清理 + if (clear) { + tracePointRef.current.reset?.(); + lastFinishPointRef.current = null; + isNavigationModeRef.current = false; + realtimeCartesianRef.current = []; + realtimeLastPointRef.current = null; + + if (navLineRef.current) { + viewer.entities.remove(navLineRef.current); + navLineRef.current = null; + } + if (followCarEntityRef.current) { + viewer.entities.remove(followCarEntityRef.current); + followCarEntityRef.current = null; + } + if (realtimeLineEntityRef.current) { + viewer.entities.remove(realtimeLineEntityRef.current); + realtimeLineEntityRef.current = null; + } + viewer.scene.requestRender(); + return; + } + + const tracePoints = tracePointRef.current.getTracePoint(); + if (!tracePoints || tracePoints.length === 0) { + if (navLineRef.current) { + viewer.entities.remove(navLineRef.current); + navLineRef.current = null; + } + if (followCarEntityRef.current) { + viewer.entities.remove(followCarEntityRef.current); + followCarEntityRef.current = null; + } + viewer.scene.requestRender(); + return; + } + console.log(tracePoints, tracePointRef.current.getMode(), "mode1111111111"); + + const validPoints = tracePoints.filter(p => { + const lng = Number(p.lng); + const lat = Number(p.lat); + return !isNaN(lng) && !isNaN(lat) && Math.abs(lng) < 180 && Math.abs(lat) < 90 && lng !== 0 && lat !== 0; + }); + + if (validPoints.length === 0) { + if (followCarEntityRef.current) { + viewer.entities.remove(followCarEntityRef.current); + followCarEntityRef.current = null; + } + return; + } + + const positions = validPoints.map(point => + Cesium.Cartesian3.fromDegrees(Number(point.lng), Number(point.lat)) + ); + + // 更新轨迹线 + if (navLineRef.current) { + navLineRef.current.polyline.positions = positions; + } else { + navLineRef.current = viewer.entities.add({ + polyline: { + positions: positions, + width: 2, + material: Cesium.Color.BLUE.withAlpha(0.9), + clampToGround: true, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + } + + // 计算小车朝向 + let heading = 0; + const lastIdx = positions.length - 1; + if (lastIdx > 0) { + const prevCart = positions[lastIdx - 1]; + const currCart = positions[lastIdx]; + const prevCartographic = Cesium.Cartographic.fromCartesian(prevCart); + const currCartographic = Cesium.Cartographic.fromCartesian(currCart); + + const dLon = currCartographic.longitude - prevCartographic.longitude; + const dLat = currCartographic.latitude - prevCartographic.latitude; + heading = Math.atan2(dLat, dLon); + } + + // 直接传 Cartesian3,无需二次转换 + //updateFollowCar(positions[lastIdx], heading); + + viewer.scene.requestRender(); + }; + // 清空规划航线 + useEffect(() => { + if (ifClearPlanLine) { + const viewer = viewerRef.current; + if (viewer) { + if (planLineRef.current) { + viewer.entities.remove(planLineRef.current); + planLineRef.current = null; + } + viewer.scene.requestRender(); + } + } + }, [ifClearPlanLine]); + + // 清空实时轨迹 + useEffect(() => { + if (ifClearNavLine) { + updateTraceLine(true); + } + }, [ifClearNavLine]); + + // 兼容旧 ifClear:同时清空两类 + useEffect(() => { + if (ifClear) { + const viewer = viewerRef.current; + if (viewer) { + if (planLineRef.current) { + viewer.entities.remove(planLineRef.current); + planLineRef.current = null; + } + updateTraceLine(true); + } + } + }, [ifClear]) + useEffect(() => { const viewer = viewerRef.current; @@ -1173,6 +1377,11 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType viewer.scene.requestRender(); + // ============================= + // 判断是否是无人机模式 + // ============================= + const isDroneMode = realtimeType === 'plane' || realtimeType === 'drone' || devices.some(d => d.type === 'plane' || d.type === 'drone'); + // ============================= // 判断实时数据是否合法 // ============================= @@ -1195,6 +1404,7 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType realtimeCarEntityRef.current = null; } + // 移除实时轨迹线 if (realtimeLineEntityRef.current) { viewer.entities.remove(realtimeLineEntityRef.current); realtimeLineEntityRef.current = null; @@ -1222,15 +1432,6 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType return; } - if (!drawRealTime) { - if (realtimeLineEntityRef.current) { - viewer.entities.remove(realtimeLineEntityRef.current); - realtimeLineEntityRef.current = null; - } - // 轨迹点数组也清空 - realtimeCartesianRef.current = []; - } - // ==================================== // 情况2:有实时数据 -> 隐藏 focusEntity // ==================================== @@ -1258,48 +1459,147 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType const position = Cesium.Cartesian3.fromDegrees(lon, lat, 1); // ==================================== - // 轨迹点去抖动(防止重复点) + // 无人机模式:保持原来的逻辑 // ==================================== + if (isDroneMode) { + // 轨迹点去抖动(防止重复点) + const last = realtimeLastPointRef.current; + let shouldAdd = true; - const last = realtimeLastPointRef.current; - - let shouldAdd = true; - - if (last) { - - const dx = last.lon - lon; - const dy = last.lat - lat; - - const dist = Math.sqrt(dx * dx + dy * dy); - - if (dist < 0.0000001) { - shouldAdd = false; + if (last) { + const dx = last.lon - lon; + const dy = last.lat - lat; + const dist = Math.sqrt(dx * dx + dy * dy); + if (dist < 0.0000001) { + shouldAdd = false; + } } - } + if (shouldAdd && drawRealTime) { + realtimeLastPointRef.current = { lon, lat }; + realtimeCartesianRef.current.push( + Cesium.Cartesian3.fromDegrees(lon, lat) + ); + } - if (shouldAdd) { + // 第一次进入 realtime -> 隐藏所有设备 + if (!realtimeHiddenRef.current) { + realtimeHiddenRef.current = true; - realtimeLastPointRef.current = { lon, lat }; + entityMapRef.current.forEach(e => { + if (e.billboard) e.billboard.show = false; + }); - realtimeCartesianRef.current.push( - Cesium.Cartesian3.fromDegrees(lon, lat) - ); + alarmMapRef.current.forEach(e => { + if (e.billboard) e.billboard.show = false; + }); + iotMapRef.current.forEach(e => { + if (e.billboard) e.billboard.show = false; + }); + } + + // 无人机图标 + const img = planeImg; + const imgWidth = 70; + const imgHeight = 70; + + // 如果有航向角,设置旋转 + let rotation = 0; + if (realtimePosition?.heading !== undefined && !isNaN(Number(realtimePosition.heading))) { + let headingDeg = Number(realtimePosition.heading); + rotation = Cesium.Math.toRadians(headingDeg); + } + + if (!realtimeCarEntityRef.current) { + realtimeCarEntityRef.current = viewer.entities.add({ + position: position, + billboard: { + image: img, + width: imgWidth, + height: imgHeight, + verticalOrigin: Cesium.VerticalOrigin.CENTER, + rotation: rotation, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + } + }); + } else { + realtimeCarEntityRef.current.position = position; + realtimeCarEntityRef.current.billboard.image = img; + realtimeCarEntityRef.current.billboard.width = imgWidth; + realtimeCarEntityRef.current.billboard.height = imgHeight; + realtimeCarEntityRef.current.billboard.rotation = rotation; + } + + // 无人机模式的实时轨迹线 + if (drawRealTime) { + if (realtimeLineEntityRef.current) { + // 已存在,CallbackProperty 会自动更新 + } else { + const callbackPositions = new Cesium.CallbackProperty(() => { + return realtimeCartesianRef.current; + }, false); + + realtimeLineEntityRef.current = viewer.entities.add({ + polyline: { + positions: callbackPositions, + width: 5, + material: new Cesium.PolylineGlowMaterialProperty({ + glowPower: 0.25, + color: Cesium?.Color.LIME + }), + clampToGround: true, + disableDepthTestDistance: Number.POSITIVE_INFINITY + } + }); + } + } else { + // 不绘制实时轨迹,移除线 + if (realtimeLineEntityRef.current) { + viewer.entities.remove(realtimeLineEntityRef.current); + realtimeLineEntityRef.current = null; + } + realtimeCartesianRef.current = []; + } + + // 无人机模式不需要完成点逻辑,直接返回 + if (!hasFlownRef.current) { + hasFlownRef.current = true; + if (getCameraMode() !== "realtime") return; + + viewer.camera.flyTo({ + destination: Cesium.Cartesian3.fromDegrees(lon, lat, 30), + orientation: { + heading: 0, + pitch: Cesium.Math.toRadians(-90), + roll: 0 + }, + duration: 1.2 + }); + } + + viewer.scene.requestRender(); + return; } // ==================================== - // 限制轨迹长度(防止内存爆) + // 机器人模式:使用 TracePoint 逻辑 // ==================================== + const point = { lng: lon, lat: lat }; - //if (realtimeCartesianRef.current.length > 2000) { - // realtimeCartesianRef.current.shift(); - //} + // 如果是定位模式且 drawRealTime 为 false,保持定位模式 + if (!drawRealTime) { + tracePointRef.current.setMode(TPMode.LOCATION); + isNavigationModeRef.current = false; + } + + // 更新当前点 + tracePointRef.current.upsert(point, TPAction.UPDATE); + + // 更新轨迹绘制 + updateTraceLine(); - // ==================================== // 第一次进入 realtime -> 隐藏所有设备 - // ==================================== - if (!realtimeHiddenRef.current) { realtimeHiddenRef.current = true; @@ -1318,23 +1618,14 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType } - // ==================================== - // 创建实时设备图标(只创建一次) - // ==================================== - - // 判断应该用什么图标(飞机优先) - const isPlane = realtimeType === 'plane' || realtimeType === 'drone' || devices.some(d => d.type === 'plane' || d.type === 'drone'); - const img = isPlane ? planeImg : carImg; - const imgWidth = isPlane ? 70 : 60; - const imgHeight = isPlane ? 70 : 60; + // 机器人图标 + const img = carImg; + const imgWidth = 60; + const imgHeight = 60; // 如果有航向角,设置旋转 let rotation = 0; if (realtimePosition?.heading !== undefined && !isNaN(Number(realtimePosition.heading))) { - // 航向通常是地理坐标系(0=北, 90=东, 顺时针) - // Cesium billboard 的 rotation 是0=右(东),顺时针为正 - // 需要将地理航向转换为 Cesium rotation - // 地理 0° 北 → Cesium 需要 -90° 或者 270°(因为 Cesium 0° 是右/东) let headingDeg = Number(realtimePosition.heading); rotation = Cesium.Math.toRadians(headingDeg); } @@ -1352,7 +1643,6 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType } }); } else { - // 更新位置、图标和旋转 realtimeCarEntityRef.current.position = position; realtimeCarEntityRef.current.billboard.image = img; realtimeCarEntityRef.current.billboard.width = imgWidth; @@ -1360,42 +1650,57 @@ export default function CesiumMap({ drawRealTime, realtimePosition, realtimeType realtimeCarEntityRef.current.billboard.rotation = rotation; } - // ==================================== - // 创建轨迹线(只创建一次) - // ==================================== + // 机器人模式只在导航模式下显示额外的实时轨迹线 + if (drawRealTime && isNavigationModeRef.current) { + // 轨迹点去抖动(防止重复点) + const last = realtimeLastPointRef.current; + let shouldAdd = true; - if (!realtimeLineEntityRef.current) { + if (last) { + const dx = last.lon - lon; + const dy = last.lat - lat; + const dist = Math.sqrt(dx * dx + dy * dy); + //if (dist < 0.0000001) { + // shouldAdd = false; + //} + } - const callbackPositions = new Cesium.CallbackProperty(() => { - return realtimeCartesianRef.current; - }, false); - if (!drawRealTime) return; + //if (shouldAdd) { + // realtimeLastPointRef.current = { lon, lat }; + // realtimeCartesianRef.current.push( + // Cesium.Cartesian3.fromDegrees(lon, lat) + // ); + //} - realtimeLineEntityRef.current = viewer.entities.add({ - - polyline: { - - positions: callbackPositions, - - width: 5, - - material: new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.25, - color: Cesium?.Color.LIME - }), - - clampToGround: true, - - disableDepthTestDistance: Number.POSITIVE_INFINITY - - } - - }); + //if (realtimeLineEntityRef.current) { + // // 已存在,CallbackProperty 会自动更新 + //} else { + // const callbackPositions = new Cesium.CallbackProperty(() => { + // return realtimeCartesianRef.current; + // }, false); + // realtimeLineEntityRef.current = viewer.entities.add({ + // polyline: { + // positions: callbackPositions, + // width: 5, + // material: new Cesium.PolylineGlowMaterialProperty({ + // glowPower: 0.25, + // color: Cesium?.Color.LIME + // }), + // clampToGround: true, + // disableDepthTestDistance: Number.POSITIVE_INFINITY + // } + // }); + //} + } else { + // 移除实时轨迹线 + if (realtimeLineEntityRef.current) { + viewer.entities.remove(realtimeLineEntityRef.current); + realtimeLineEntityRef.current = null; + } + realtimeCartesianRef.current = []; } - - if (!hasFlownRef.current) { hasFlownRef.current = true; diff --git a/src/components/devices/DeviceStatusPage.tsx b/src/components/devices/DeviceStatusPage.tsx index b6afcda..b30bdfa 100644 --- a/src/components/devices/DeviceStatusPage.tsx +++ b/src/components/devices/DeviceStatusPage.tsx @@ -31,6 +31,7 @@ import { CameraOutlined, ThunderboltOutlined, EnvironmentOutlined, + DeleteOutlined, } from '@ant-design/icons'; import { @@ -299,6 +300,8 @@ export default function DeviceStatusPage({ const [mowerView, setMowerView] = useState('front'); const [uavState, setUavState] = useState(null); const [points, setPoints] = useState([]); + const [clearNavLine, setClearNavLine] = useState(0); + const [clearPlanLine, setClearPlanLine] = useState(0); const timerRef = useRef(null); const runningStatus = useMemo(() => { @@ -606,6 +609,19 @@ export default function DeviceStatusPage({ 实时视频监控 } + //extra={ + // + //} bordered={false} style={{ borderRadius: 12, marginBottom: 8 }} bodyStyle={{ padding: 12 }} @@ -729,6 +745,31 @@ export default function DeviceStatusPage({ 位置态势图 } + extra={ + + + + + } bordered={false} style={{ borderRadius: 12 }} bodyStyle={{ @@ -742,6 +783,8 @@ export default function DeviceStatusPage({ realtimePosition={realtimePosition} realtimeType={realtimeType} drawRealTime={true} + ifClearNavLine={clearNavLine} + ifClearPlanLine={clearPlanLine} /> diff --git a/src/components/devices/RobotTaskPage.tsx b/src/components/devices/RobotTaskPage.tsx index f4c1f48..1e86960 100644 --- a/src/components/devices/RobotTaskPage.tsx +++ b/src/components/devices/RobotTaskPage.tsx @@ -51,6 +51,7 @@ export default function RobotTaskPage() { const [robotRealtimePosition, setRobotRealtimePosition] = useState(null); const [execute, setExecute] = useState(false); // 是否执行任务 const [taskList, setTaskList] = useState([]); + const [arrivedPoint, setArrivedPoint] = useState(null);//完成点 // 设备数据 @@ -59,6 +60,8 @@ export default function RobotTaskPage() { const [focusLocation, setFocusLocation] = useState(null); const [points, setPoints] = useState([]); + const [clearNavLine, setClearNavLine] = useState(0); + const [clearPlanLine, setClearPlanLine] = useState(0); const [routeSearch, setRouteSearch] = useState(''); const [routeList, setRouteList] = useState([]); @@ -115,12 +118,18 @@ export default function RobotTaskPage() { if (controllerRef.current) { controllerRef.current.destroy?.(); } - controllerRef.current = null; setSelectedRobotForExecute(null); setSelectedRouteForExecute(null); + fetchTaskList(); + fetchTaskHistoryList(); + fetchTaskPoolList(); } + const handleFinishEdPoint = (point) => { + console.log('到达完成点11111111111', point); + setArrivedPoint(point); + } useEffect(() => { @@ -128,6 +137,7 @@ export default function RobotTaskPage() { controller.onDeviceInfoUpdate = setRobotRealtimePosition; controller.onIsFinished = handleFinish; + controller.handleArrivedPoint = handleFinishEdPoint; controller.init(); @@ -154,7 +164,7 @@ export default function RobotTaskPage() { if (robotRealtimePosition && execute) { let warningMsg = ''; - if (robotRealtimePosition?.controlMode != "3") { + if (robotRealtimePosition?.controlMode == "1") { warningMsg = `请切换到远程模式 ${robotRealtimePosition?.controlMode}`; } else if (robotRealtimePosition?.qual != "4") { warningMsg = '定位未固定'; @@ -316,7 +326,7 @@ export default function RobotTaskPage() { message.error('请选择执行设备'); return; } - + try { const params = { @@ -438,7 +448,6 @@ export default function RobotTaskPage() { if (controllerRef.current) { controllerRef.current.destroy?.(); } - controllerRef.current = null; setSelectedRobotForExecute(null); setSelectedRouteForExecute(null); } else { @@ -888,10 +897,10 @@ export default function RobotTaskPage() { {/* 控制模式 */} 控制模式:{robotRealtimePosition?.controlMode} - {robotRealtimePosition?.controlMode == '3' ? ( - 远程 + {robotRealtimePosition?.controlMode == '1' ? ( + 本地 ) : ( - 本地 + 远程 )} @@ -918,14 +927,7 @@ export default function RobotTaskPage() { )} } size="small" - extra={ - - - - - + @@ -864,7 +891,7 @@ export default function WayLinePage({ onRefresh }) { >
+ points={points} focusLocation={focusLocation} from="device-control" realtimeType='plane' ifClearNavLine={clearNavLine} ifClearPlanLine={clearPlanLine} />
无人机航线
diff --git a/src/components/devices/deviceController.js b/src/components/devices/deviceController.js index c497c35..eac33d9 100644 --- a/src/components/devices/deviceController.js +++ b/src/components/devices/deviceController.js @@ -37,6 +37,7 @@ export default class DeviceController { this.onRequestControlStatusChange = null; this.onPermissionRequest = null; this.onIsFinished = null; + this.handleArrivedPoint = null; this.handleWsMessage = this.handleWsMessage.bind(this); this.handleWsStatus = this.handleWsStatus.bind(this); @@ -128,7 +129,7 @@ export default class DeviceController { this.unSubStatus?.(); this.release(); - wsManager.close(); + //wsManager.close(); this.connectedDeviceSn = null; } @@ -157,7 +158,7 @@ export default class DeviceController { this.isControlled = false; this.onControlStatusChange?.(false); - wsManager.close(); + //wsManager.close(); try { const res = await getControlRight({ @@ -270,7 +271,6 @@ export default class DeviceController { } case 'switchResult': { - console.log('🔌 控制结果111111111111111:', msg); this.clearControlTimeout(); this.isRequestControl = false; @@ -288,13 +288,22 @@ export default class DeviceController { break; } case "device_task_change": { + if (msg.deviceId != this.connectedDeviceSn) return; this.onIsFinished?.(true); console.log('🔌 控制结果任务变更,', msg); } + //完成点 + case "device_task_arrive_point": { + if (msg.deviceId != this.connectedDeviceSn) return; + + this.handleArrivedPoint?.(msg.entity); + console.log('🔌 到达完成点,', msg); + + } + case 'switchPermission': { - console.log('🔌 控制结果111111111111111222222222:', msg); const platform = (msg.platform || '').toLowerCase(); if (!platform || platform === 'null') return; diff --git a/src/lib/TracePoint/tracePoint.js b/src/lib/TracePoint/tracePoint.js index 4ba625e..0b9873d 100644 --- a/src/lib/TracePoint/tracePoint.js +++ b/src/lib/TracePoint/tracePoint.js @@ -12,8 +12,8 @@ * 轨迹模式: 实时绘制历史轨迹 */ const TPMode = Object.freeze({ - NAVIGATION: Symbol('NAVIGATION'), - LOCATION: Symbol('LOCATION'), + NAVIGATION: Symbol('NAVIGATION'), + LOCATION: Symbol('LOCATION'), TRACK: Symbol('TRACK'), }); @@ -24,17 +24,10 @@ const TPMode = Object.freeze({ * ADD : 添加 */ const TPAction = Object.freeze({ - UPDATE: Symbol('UPDATE'), - ADD: Symbol('ADD'), + UPDATE: Symbol('UPDATE'), + ADD: Symbol('ADD'), }); -/** - * 仅测试用 - * linux 运行 TEST_LOCK=true node testTrace.js - * windows 运行 $env:TEST_LOCK="true"; node .\testTrace.js - */ -// const TEST_LOCK = process.env.TEST_LOCK === 'true'; - /*============================================================================================================== * * tracePoint 类 @@ -68,8 +61,7 @@ const TPAction = Object.freeze({ * 4. 添加或更新点调用 upsert * *=============================================================================================================*/ -class TracePoint -{ +class TracePoint { /* 成员变量(私有) */ #queue; /* 循环队列, 用于存放等待处理的点 */ #tracePoint; /* 轨迹点数组, 存放已完成点 + 当前点 */ @@ -80,12 +72,10 @@ class TracePoint /* ======================== * TEST ONLY: BEGIN * ========================*/ - tryLock() - { + tryLock() { return this.#lock.tryLock(); } - release() - { + release() { this.#lock.release(); } /* ======================== @@ -93,11 +83,10 @@ class TracePoint * ========================*/ /* 构造函数 */ - constructor() - { - this.#queue = new CircQueue(5, { + constructor() { + this.#queue = new CircQueue(100, { deepCopy: true, - maxMemoryBytes: 1024*1024, /* 1MB 限制 */ + maxMemoryBytes: 1024 * 1024, /* 1MB 限制 */ }); @@ -108,12 +97,11 @@ class TracePoint } /* 复位 */ - reset() - { + reset() { /* 重置轨迹点 */ -// let len = this.#queue.getDepth(); -// this.#queue.discard(len); - this.#queue.clear(); /* 清空队列 */ + // let len = this.#queue.getDepth(); + // this.#queue.discard(len); + this.#queue.clear(); /* 清空队列 */ this.#tracePoint = []; /* 清空轨迹点数组 */ this.#completePointIndex = 0; /* 重置完成点索引 */ this.#lock.release(); /* 释放锁 */ @@ -123,80 +111,69 @@ class TracePoint * mode: 模式选择器, 见枚举 TPMode * 说明: * 导航模式: 绘制规划已完成路径和当前路径 - * 定位模式: 绘制当前点 - * 轨迹模式: 实时绘制历史轨迹 + * 定位模式: 绘制当前点 + * 轨迹模式: 实时绘制历史轨迹 */ - setMode(mode) - { + setMode(mode) { this.reset(); this.#mode = mode; } + getMode() { + return this.#mode; + } /** * point : 需要添加或更细的点 * act : 仅导航模式下有效, 缺省为 TPAction.UPDATE , 具体如下: * 1. 添加完成点时调用: upsert(point, TPAction.ADD) - * 2. 更新当前点时调用: upsert(point) + * 2. 更新当前点时调用: upsert(point) */ - upsert(point, act = TPAction.UPDATE) - { - if(this.#mode === TPMode.NAVIGATION) - { - (act === TPAction.UPDATE) + upsert(point, act = TPAction.UPDATE) { + if (this.#mode === TPMode.NAVIGATION) { + (act === TPAction.UPDATE) ? this.#updateCurrentPoint(point) : this.#addCompletePoint(point); } - else if(this.#mode === TPMode.LOCATION) - { + else if (this.#mode === TPMode.LOCATION) { this.#updateCurrentPoint(point); } - else if(this.#mode === TPMode.TRACK) - { + else if (this.#mode === TPMode.TRACK) { this.#addCompletePoint(point); } } /* 获取轨迹 */ - getTracePoint() - { + getTracePoint() { /* 尝试锁定, 防止多线程同时更新 */ - if( this.#lock.tryLock() ) - { + if (this.#lock.tryLock()) { const trace = this.#tracePoint.slice(); /* 深拷贝, 避免外部修改导致内部出错 */ this.#lock.release(); /* 解锁 */ return trace; } - else - { + else { console.warn('getTracePoint: lock!!!'); return null; /* 锁定中, 返回空 */ } } /* 更新当前点 */ - #updateCurrentPoint(point) - { - if (!point) - { + #updateCurrentPoint(point) { + if (!point) { console.error('updateCurrentPoint: point is NULL'); return; } /* 尝试锁定, 防止多线程同时更新 */ - if( this.#lock.tryLock() ) - { + if (this.#lock.tryLock()) { /** * 导航模式: 当前点只插在尾部,若轨迹数组尚未插入完成点, 则丢弃 * 定位模式: 轨迹数组只有一个点 */ - if(this.#mode === TPMode.NAVIGATION) - { - if (this.#tracePoint.length === 0) - { + if (this.#mode === TPMode.NAVIGATION) { + if (this.#tracePoint.length === 0) { console.log('updateCurrentPoint: tracePoint is empty , wait first completed point, discard current point:', point); } - else - { + else { /* 只保留完成点部分, 再插入新的当前点 */ this.#tracePoint = this.#tracePoint.slice(0, this.#completePointIndex); this.#tracePoint.push(point); @@ -205,38 +182,31 @@ class TracePoint // emit } } - else if(this.#mode === TPMode.LOCATION) - { + else if (this.#mode === TPMode.LOCATION) { this.#tracePoint[0] = point; /* JS 支持自动扩展数组 */ } this.#lock.release(); /* 解锁 */ } /* 如果轨迹数组正在操作, 先存放至队列中 */ - else - { + else { console.warn('updateCurrentPoint: lock!!!, discard current point:', point); } } /* 添加完成点 */ - #addCompletePoint(point) - { - if (!point) - { + #addCompletePoint(point) { + if (!point) { console.error('addCompletePoint: point is NULL'); return; } /* 尝试锁定, 防止多线程同时更新 */ - if( this.#lock.tryLock() ) - { - try - { + if (this.#lock.tryLock()) { + try { /* 先处理队列中积压的点 */ - while (this.#queue.isEmpty() === false) - { + while (this.#queue.isEmpty() === false) { /* 如果队列不为空, 取出队列中的点 */ const point = this.#queue.out(); this.#addPoint(point); @@ -248,31 +218,26 @@ class TracePoint /* 触发事件 newCompletePoint, 驱动外部更新 */ // emit } - catch (error) - { + catch (error) { /* 错误处理, js 可以输出到 .err 文件? */ /* 打印 */ console.error('addCompletePoint failure:', error); } - finally - { + finally { this.#lock.release(); /* 无论成功失败都解锁, 避免无法使用 */ } } /* 如果轨迹数组正在操作, 先存放至队列中 */ - else - { + else { this.#queue.enter(point); console.warn('addCompletePoint: lock!!!, enter queue, wait disposing:', point); return; } } - #addPoint(point) - { - if (!point) - { + #addPoint(point) { + if (!point) { console.error('point NULL:'); return; } @@ -280,15 +245,13 @@ class TracePoint /* 若当前点存在,说明当前数组末尾已插入一个当前点, 截断轨迹数组到当前点,将新完成点插入在当前点之前 */ const hasCurrentPoint = (this.#tracePoint.length > 0 && this.#completePointIndex < this.#tracePoint.length); - if (hasCurrentPoint) - { + if (hasCurrentPoint) { /* 截断避免多添加了无效点, 然后再当前点之前插入完成点 */ this.#tracePoint = this.#tracePoint.slice(0, this.#completePointIndex); this.#tracePoint.splice(this.#completePointIndex, 0, point); } /* 首次添加轨迹点需要先尾插 */ - else - { + else { this.#tracePoint.push(point); } @@ -297,8 +260,7 @@ class TracePoint } } -class CircQueue -{ +class CircQueue { /** * 构造函数 * capacity :队列可容纳的最大项目数 @@ -307,8 +269,7 @@ class CircQueue * maxMemoryBytes :队列的最大内存限制 (单位:字节),默认 Infinity, 不限制内存 * 若传 1024 * 1024 代表限制 1 M ,超出则队满, 队列会拒绝入队 */ - constructor(capacity, options = {}) - { + constructor(capacity, options = {}) { this.capacity = capacity; /* 队列容量 (最多存储项目数) */ this.buffer = new Array(capacity); /* 队列存储区,使用数组存任意对象 */ this.head = 0; /* 队头索引 */ @@ -320,50 +281,41 @@ class CircQueue this.currentMemoryBytes = 0; /* 当前已使用内存大小 (单位:字节) */ } - /* 清空队列 */ - clear() - { - this.tail = this.head; - this.isFull = false; - } + /* 清空队列 */ + clear() { + this.tail = this.head; + this.isFull = false; + } /* 判断队列是否为空 */ - isEmpty() - { + isEmpty() { return this.head === this.tail && !this.isFull; } /* 判断队列是否已满 */ - isFullFn() - { + isFullFn() { return this.isFull; } /* 估算对象大小 (以 JSON 字符串的 UTF-8 编码长度作为近似值) */ - _estimateSize(obj) - { - try - { - return Buffer.byteLength(JSON.stringify(obj), 'utf8'); /* Node.js 中用于计算字节长度 */ + _estimateSize(obj) { + try { + return new Blob([JSON.stringify(obj)]).size; } - catch - { + catch { return 0; /* 若对象不可序列化,返回 0 (避免出错) */ } } /* 深拷贝对象 (基于 JSON 的方式,仅支持可序列化对象) */ - _deepClone(obj) - { + _deepClone(obj) { return this.deepCopy ? JSON.parse(JSON.stringify(obj)) : obj; } /* 入队操作:将对象放入队尾 */ - enter(item) - { + enter(item) { const itemSize = this._estimateSize(item); /* 估算项目内存大小 */ - if (this.isFullFn() || (this.currentMemoryBytes + itemSize > this.maxMemoryBytes)) - { + if (this.isFullFn() || (this.currentMemoryBytes + itemSize > this.maxMemoryBytes)) { return false; /* 若队满或超过内存限制则入队失败 */ } @@ -377,8 +329,7 @@ class CircQueue } /* 出队操作:从队头取出一个对象, 返回深拷贝 */ - out() - { + out() { if (this.isEmpty()) return null; /* 队空返回 null */ const item = this.buffer[this.head]; /* 读取队头项目 */ @@ -389,10 +340,8 @@ class CircQueue } /* 丢弃数据:从队尾向前丢弃 len 项 (反向移动 tail) */ - discard(len) - { - for (let i = 0; i < len; i++) - { + discard(len) { + for (let i = 0; i < len; i++) { if (this.isEmpty()) return false; /* 队空则不能继续丢弃 */ /* 定位最后一项 */ @@ -405,8 +354,7 @@ class CircQueue } /* 获取当前队列中元素个数 */ - getDepth() - { + getDepth() { return this.isFull ? this.capacity : (this.tail + this.capacity - this.head) % this.capacity; @@ -417,13 +365,11 @@ class CircQueue * buf : 需要发送的数据 * timeoutMs : 超时时间 */ - async send(item, timeoutMs = 0) - { + async send(item, timeoutMs = 0) { const start = Date.now(); /* 循环直到成功入队或超时 */ - while (!this.enter(item)) - { + while (!this.enter(item)) { if (Date.now() - start >= timeoutMs) return false; /* 超时退出 */ await new Promise(resolve => setTimeout(resolve, 1)); /* 异步轮询, 自旋加 sleep 挂起 1ms */ } @@ -436,11 +382,9 @@ class CircQueue * timeoutMs : 超时时间 * 返回值:成功取出一个对象(深拷贝)或 null (超时) */ - async recv(timeoutMs = 0) - { + async recv(timeoutMs = 0) { const start = Date.now(); - while (true) - { + while (true) { const item = this.out(); if (item !== null) return item; /* 成功取出则返回 */ if (Date.now() - start >= timeoutMs) return null; /* 超时退出 */ @@ -449,33 +393,27 @@ class CircQueue } /* JSON 序列化接口,用于 JSON.stringify(queue) */ - toJSON() - { + toJSON() { const result = []; let i = this.head; let count = this.getDepth(); - while (count-- > 0) - { + while (count-- > 0) { result.push(this._deepClone(this.buffer[i])); /* 复制每个元素 */ i = (i + 1) % this.capacity; /* 移动到下一个元素 */ } return result; } } -class TryLock -{ - constructor() - { +class TryLock { + constructor() { this._locked = false; } /** * 尝试获取锁 * true: 获取成功, false: 已被锁定 */ - tryLock() - { - if (this._locked) - { + tryLock() { + if (this._locked) { return false; } this._locked = true; @@ -483,14 +421,8 @@ class TryLock } /* 释放锁资源 */ - release() - { + release() { this._locked = false; } } -// export { TracePoint, TPAction, TPMode }; -// module.exports = { -// TracePoint, -// TPAction, -// TPMode, -// }; \ No newline at end of file +export { TracePoint, TPAction, TPMode };