From 3e2fa95a30bd657cd22c418972e8df29a49662d8 Mon Sep 17 00:00:00 2001 From: mmc <1556375442@qq.com> Date: Wed, 28 Oct 2026 17:13:03 +0800 Subject: [PATCH] =?UTF-8?q?map=E4=B8=AD=20=E5=A2=9E=E5=8A=A0=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E9=9A=9C=E7=A2=8D=E7=89=A9=E4=BB=A3=E7=A0=81=20?= =?UTF-8?q?=E6=9C=AA=E6=B5=8B=E8=AF=95=EF=BC=8C=E4=BC=98=E5=8C=96=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E5=AE=9E=E6=97=B6=E8=B7=AF=E5=BE=84=EF=BC=8C=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E8=BF=94=E8=88=AA=E7=82=B9=E3=80=81=E5=88=86=E5=8C=BA?= =?UTF-8?q?=E7=9A=84=E7=BB=98=E5=88=B6=E6=98=BE=E7=A4=BA=20=20=E9=9A=9C?= =?UTF-8?q?=E7=A2=8D=E7=89=A9=20=E6=94=AF=E6=8C=81=E6=8B=96=E5=8A=A8?= =?UTF-8?q?=E5=8D=8A=E5=BE=84=E6=98=BE=E7=A4=BA=20=E5=9C=B0=E5=9B=BE?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=9B=BE=E4=BE=8B=EF=BC=8C=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E6=9C=BA=E5=99=A8=E4=BA=BA=E4=BB=BB=E5=8A=A1=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E7=9A=84=E9=80=BB=E8=BE=91=20=E6=97=A0=E9=9C=80=E6=94=B6?= =?UTF-8?q?=E5=88=B0=E5=88=B7=E6=96=B0=E6=8E=A5=E5=8F=A3=EF=BC=8C=E6=A0=B9?= =?UTF-8?q?=E6=8D=AE=E4=BC=A0=E8=BE=93=E4=BB=BB=E5=8A=A1=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E6=83=85=E5=86=B5=20=E8=B0=83=E7=94=A8=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=EF=BC=8C=E5=B7=B2=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Map.jsx | 1133 +++++++++++++---- src/components/devices/DeviceStatusPage.tsx | 6 +- .../devices/RobotFeatureButtons.tsx | 2 +- src/components/devices/RobotTaskPage.tsx | 55 +- src/components/devices/Steerbutton.tsx | 1 - src/components/devices/deviceController.js | 78 +- src/components/recharts.jsx | 3 +- src/locales/en/index.ts | 6 +- src/locales/zh/index.ts | 4 +- 9 files changed, 993 insertions(+), 295 deletions(-) diff --git a/src/components/Map.jsx b/src/components/Map.jsx index af753a5..f53c81b 100644 --- a/src/components/Map.jsx +++ b/src/components/Map.jsx @@ -29,7 +29,7 @@ const CYAN_GLOW_COLOR = new window.Cesium.Color( ); window.Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNjk0NjI1MC0wZGYyLTQ1YzItYjJmZi0wY2M5ODEwODllYzIiLCJpZCI6Mzk3MTQxLCJpYXQiOjE3NzI1MjkwMjV9.U6qmakhDgXJVXwLFyWzSxAUOFZRrDkIsRUPP6CCdnKg"; -const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], markedPoints = [], onPathChange, from, onClearDraw, onMarkPoint, routeMode = '', polyPoints, mapLayer, activeType, overlayRefreshKey = 0, focusOverlay = null }, ref) => { +const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], markedPoints = [], onPathChange, from, onClearDraw, onMarkPoint, routeMode = '', polyPoints, mapLayer, activeType, overlayRefreshKey = 0, focusOverlay = null, onObstacleRadiusChange }, ref) => { const containerRef = useRef(null); const viewerRef = useRef(null); const tooltipRef = useRef(null); @@ -42,6 +42,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, const polygonRef = useRef(null); // coverage 区域多边形 const navLineRef = useRef(null); // 完成点实时轨迹 const markedPointsRef = useRef([]); // 标记点实体 + const obstacleCirclesRef = useRef([]); // 障碍物点圆形实体 const markedLineRef = useRef(null); // 标记点连线实体 const lastMarkedPointsRef = useRef([]); // 上次渲染的标记点数据,用于增量更新 const onMarkPointRef = useRef(onMarkPoint); // 总是指向最新的 onMarkPoint,避免闭包滞后 @@ -50,7 +51,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, // 场站已配置的返航点 / 分区叠加显示 const stationId = useSelector((state) => state?.station?.stationId || state?.station?.currentStation?.id); - const [stationOverlay, setStationOverlay] = useState({ returnPoints: [], regions: [] }); + const [stationOverlay, setStationOverlay] = useState({ returnPoints: [], regions: [], tempObstaclePoints: [] }); const stationOverlayIdsRef = useRef([]); const returnPointPinUrlRef = useRef(null); // 被点击聚焦的返航点 id / 图例高亮类型 @@ -73,20 +74,41 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, const isCameraFlyingRef = useRef(false); const lastFlightPromiseRef = useRef(null); + const draggingObstacleRef = useRef(null) + const [isDraggingObstacle, setIsDraggingObstacle] = useState(false); + // ============================== // 飞行优先级调度:优先级高的可打断低的;同级不重复起飞 // realtime(100) > focus(90) > devices(80) > track(70) > layer(10) // ============================== const lastFlightPriorityRef = useRef(-1); - const FLIGHT_PRIORITY = { realtime: 100, focus: 90, devices: 80, track: 70, layer: 10 }; - const flyToView = (viewer, priority, config) => { - if (!viewer) return; - if (priority <= lastFlightPriorityRef.current) return; // 同级或更低不重复/覆盖;更高优先级才打断 - lastFlightPriorityRef.current = priority; - try { viewer.camera.cancelFlight(); } catch (e) { /* 忽略取消异常 */ } - viewer.camera.flyTo(config); - }; + //const FLIGHT_PRIORITY = { realtime: 100, focus: 90, devices: 80, track: 70, layer: 10 }; + //const flyToView = (viewer, priority, config) => { + // if (!viewer) return; + // if (priority <= lastFlightPriorityRef.current) return; // 同级或更低不重复/覆盖;更高优先级才打断 + // lastFlightPriorityRef.current = priority; + // try { viewer.camera.cancelFlight(); } catch (e) { /* 忽略取消异常 */ } + // viewer.camera.flyTo(config); + //}; const resetFlightPriority = () => { lastFlightPriorityRef.current = -1; }; + const getObstacleHandlePosition = ( + Cesium, + lon, + lat, + radius + ) => { + const center = Cesium.Cartesian3.fromDegrees(lon, lat, 0); + + // 建立以圆心为原点的东-北-天坐标系 + const enu = Cesium.Transforms.eastNorthUpToFixedFrame(center); + + // 手柄放在圆周的东侧 + return Cesium.Matrix4.multiplyByPoint( + enu, + new Cesium.Cartesian3(radius, 0, 0), + new Cesium.Cartesian3() + ); + }; const [drawPoints, setDrawPoints] = useState([]); const drawLineRef = useRef(null); @@ -124,6 +146,184 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, [] ); + const liveObstacleEntities = new Map(); + + // ============================== + // 统一相机飞行调度器 + // ============================== + const FLIGHT_PRIORITY = { + layer: 10, + track: 30, + devices: 40, + focus: 60, + realtime: 70, + manual: 100, + }; + + const flightStateRef = useRef({ + priority: -1, + key: null, + token: 0, + flying: false, + }); + + const flyToView = (viewer, priority, config, key = '') => { + if (!viewer || viewer.isDestroyed()) return false; + + const state = flightStateRef.current; + const now = Date.now(); + + // 相同目标正在飞行,忽略重复请求 + if ( + state.flying && + state.priority === priority && + state.key === key && + now - (state.startedAt || 0) < 3000 + ) { + return false; + } + + // 仅在当前飞行尚未结束时执行优先级比较 + if (state.flying && priority < state.priority) { + return false; + } + + const token = ++state.token; + + state.priority = priority; + state.key = key; + state.startedAt = now; + state.flying = true; + + try { + viewer.camera.cancelFlight(); + + viewer.camera.flyTo({ + ...config, + + complete: () => { + // 旧飞行的回调不能清除新飞行状态 + if (flightStateRef.current.token !== token) return; + + flightStateRef.current.flying = false; + flightStateRef.current.priority = -1; + flightStateRef.current.key = null; + + config.complete?.(); + }, + + cancel: () => { + if (flightStateRef.current.token !== token) return; + + flightStateRef.current.flying = false; + flightStateRef.current.priority = -1; + flightStateRef.current.key = null; + + config.cancel?.(); + }, + }); + + return true; + } catch (error) { + if (flightStateRef.current.token === token) { + flightStateRef.current.flying = false; + flightStateRef.current.priority = -1; + flightStateRef.current.key = null; + } + + console.error('地图飞行失败:', error); + return false; + } + }; + + function updateLiveObstacleBoxes( + viewer, + message, + ) { + const payload = message.data ?? message; + const objects = payload.objects ?? []; + + objects.forEach((obj, index) => { + const lat = Number(obj.latitude); + const lon = Number(obj.longitude); + const sx = Number(obj.size_x); + const sy = Number(obj.size_y); + const sz = Number(obj.size_z); + + if ( + !Number.isFinite(lat) || + !Number.isFinite(lon) || + !Number.isFinite(sx) || + !Number.isFinite(sy) || + !Number.isFinite(sz) || + sx <= 0 || + sy <= 0 || + sz <= 0 + ) { + return; + } + + const id = `live-obstacle-${obj.track_id ?? index}`; + + // size_x、size_y、size_z 作为长、宽、高,单位按米处理 + const position = Cesium.Cartesian3.fromDegrees( + lon, + lat, + sz / 2, + ); + + const orientation = Cesium.Transforms.headingPitchRollQuaternion( + position, + new Cesium.HeadingPitchRoll( + Cesium.Math.toRadians(Number(obj.angle ?? 0)), + 0, + 0, + ), + ); + + const labelText = + `${obj.class_name ?? '障碍物'} #${obj.track_id ?? index}`; + + let entity = viewer.entities.getById(id); + + if (!entity) { + entity = viewer.entities.add({ + id, + position, + orientation, + box: { + dimensions: new Cesium.Cartesian3(sx, sy, sz), + material: Cesium.Color.RED.withAlpha(0.18), + outline: true, + outlineColor: Cesium.Color.RED, + }, + label: { + text: labelText, + font: '14px sans-serif', + fillColor: Cesium.Color.WHITE, + showBackground: true, + backgroundColor: Cesium.Color.RED.withAlpha(0.85), + pixelOffset: new Cesium.Cartesian2(0, -20), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + } else { + entity.position = position; + entity.orientation = orientation; + + if (entity.box) { + entity.box.dimensions = new Cesium.Cartesian3(sx, sy, sz); + } + + if (entity.label) { + entity.label.text = labelText; + } + } + + liveObstacleEntities.set(id, entity); + }); + } + const clearDrawingPath = () => { const viewer = viewerRef.current; if (!viewer) return; @@ -142,56 +342,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, onPathChange && onPathChange([]); }; - const updateDrawPath = (newPoints) => { - const viewer = viewerRef.current; - if (!viewer) return; - pointEntitiesRef.current.forEach(id => { - viewer.entities.removeById(id); - }); - pointEntitiesRef.current = []; - - newPoints.forEach((p, i) => { - const id = `draw-point-${i}`; - viewer.entities.add({ - id, - position: window.Cesium.Cartesian3.fromDegrees(p.lon, p.lat), - point: { - color: window.Cesium?.Color.SKYBLUE, - pixelSize: 10, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - label: { - text: `${i + 1}`, - font: '12px sans-serif', - pixelOffset: new window.Cesium.Cartesian2(0, -15), - fillColor: window.Cesium?.Color.WHITE - } - }); - pointEntitiesRef.current.push(id); - }); - - if (drawLineRef.current) { - viewer.entities.remove(drawLineRef.current); - } - if (newPoints.length >= 2) { - const positions = newPoints.map(p => { - return window.Cesium.Cartesian3.fromDegrees(p.lon, p.lat); - }); - - drawLineRef.current = viewer.entities.add({ - polyline: { - positions: positions, - width: 4, - material: window.Cesium?.Color.SKYBLUE, - clampToGround: true, - } - }); - } - console.log(newPoints, "newPoints") - - onPathChange && onPathChange(newPoints); - }; // ========== 替换原有 createDeviceHaloEntity 完整函数 ========== // 改动说明:弃用 ellipse 静态椭圆,改用 billboard + createGlowBlinkColor 实现闪烁光圈 // ============================================================ @@ -501,7 +652,8 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, 800 ), duration: 1.2 - }); + }, `track:${minLon},${minLat},${maxLon},${maxLat}` + ); viewer.scene.requestRender(); } else { @@ -698,12 +850,26 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, const newPoints = points || []; const prevPoints = lastMarkedPointsRef.current || []; + const isObstacle = activeType === 'obstaclePoint'; const nextIds = new Set(newPoints.map((p, i) => `marked-point-${p.id ?? i}`)); + const nextObstacleCircleIds = new Set(newPoints.map((p, i) => `marked-obstacle-circle-${p.id ?? i}`)); // 1) 删除不在新列表中的旧 entity markedPointsRef.current = markedPointsRef.current.filter(id => { if (!nextIds.has(id)) { + viewer.entities.removeById(id); + // 同时删除对应的 obstacle circle + const circleId = `marked-obstacle-circle-${id ?? i}`; + viewer.entities.removeById(circleId); + return false; + } + return true; + }); + + // 清理不在列表中的 obstacle circle + obstacleCirclesRef.current = obstacleCirclesRef.current.filter(id => { + if (!nextObstacleCircleIds.has(id)) { viewer.entities.removeById(id); return false; } @@ -713,20 +879,24 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, // 2) 新增或更新标记点 entity newPoints.forEach((p, i) => { const id = `marked-point-${p.id ?? i}`; + + const circleId = `marked-obstacle-circle-${p.id ?? i}`; const entity = viewer.entities.getById(id); const position = window.Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat)); const labelText = `${i + 1}`; if (entity) { - // 只更新位置和 label,避免销毁重建 entity.position = position; if (entity.label) entity.label.text = labelText; } else { + const pointColor = isObstacle + ? window.Cesium.Color.fromCssColorString('#ff4d4f') + : window.Cesium.Color.GREEN; viewer.entities.add({ id, position, point: { - color: window.Cesium.Color.GREEN, + color: pointColor, pixelSize: 15, disableDepthTestDistance: Number.POSITIVE_INFINITY, }, @@ -742,6 +912,32 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, }); markedPointsRef.current.push(id); } + + // 障碍物点:创建/更新圆形区域(EllipseGraphics,单位是米) + //if (isObstacle) { + // const radius = Math.max(0.5, Number(p.radius) || 2.0); + // const circleEntity = viewer.entities.getById(circleId); + // if (circleEntity) { + // circleEntity.position = position; + // circleEntity.ellipse.semiMajorAxis = radius; + // circleEntity.ellipse.semiMinorAxis = radius; + // } else { + // viewer.entities.add({ + // id: circleId, + // position, + // ellipse: { + // semiMajorAxis: radius, + // semiMinorAxis: radius, + // material: new window.Cesium.Color(1.0, 0.3, 0.3, 0.25), + // outline: true, + // outlineColor: window.Cesium.Color.RED, + // outlineWidth: 2, + // height: 0, + // }, + // }); + // obstacleCirclesRef.current.push(circleId); + // } + //} }); // 3) 连线:只有坐标/数量真正变化时才重建 @@ -776,8 +972,6 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, } lastMarkedPointsRef.current = newPoints.map(p => ({ ...p })); - - // 强制 Cesium 立即渲染(requestRenderMode=true 时必须手动触发) viewer.scene.requestRender(); }; @@ -800,32 +994,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, return window.Cesium.Color.fromCssColorString('#52c41a'); } - function showRobotTooltip(tooltip, robot, position, t) { - const statusMap = { - 1: { text: t('common.working'), color: "#10b981" }, - 2: { text: t('devices.idle'), color: "#f59e0b" }, - 3: { text: t('devices.offline'), color: "#f87171" } - }; - let status = statusMap[robot.feStatus] || statusMap[1]; - tooltip.style.display = "block"; - tooltip.style.left = position.x + 12 + "px"; - tooltip.style.top = position.y + 12 + "px"; - - let deviceValuesHTML = ''; - if (robot.devicevalue && robot.devicevalue.length > 0) { - deviceValuesHTML = robot.devicevalue.map((device) => ` -
${device.name}: ${device.value}${device.unit}
- `).join(''); - } - - tooltip.innerHTML = ` -
🤖 ${robot.deviceAlias || robot.serialNumber || robot.name}
- ${deviceValuesHTML ? `
${t('devices.deviceData')}:${deviceValuesHTML}
` : ''} -
${t('systemSetting.longitude')}:${Number(robot?.locationMessage?.longitude || robot?.lastRunningStatus?.longitude).toFixed(6)}
-
${t('systemSetting.latitude')}:${Number(robot?.locationMessage?.latitude || robot?.lastRunningStatus?.latitude).toFixed(6)}
- `; - } const getCursorLngLat = (viewer, screenPos) => { const cartesian = viewer.camera.pickEllipsoid(screenPos, viewer.scene.globe.ellipsoid); @@ -853,16 +1022,17 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, 2: { text: t('devices.idle'), color: "#12c60e" }, 3: { text: t('devices.offline'), color: "#f01212" } }; + console.log(robot, "9999999999999") const status = statusMap[robot.feStatus] || statusMap[1]; let deviceValuesHTML = ''; if (robot.devicevalue && robot.devicevalue.length > 0) { deviceValuesHTML = robot.devicevalue.map((device) => ` -
${device.name}: ${device.value}${device.unit}
- `).join(''); +
${device.name}: ${device.value}${device.unit}
+ `).join(''); } tooltip.innerHTML = ` -
🤖 ${robot.deviceAlias || robot.serialNumber || robot.name}
- ${deviceValuesHTML ? `
${t('devices.deviceData')}:${deviceValuesHTML}
` : ''} +
🤖 ${robot.deviceAlias || robot.serialNumber || robot.name}
+ ${deviceValuesHTML ? `
${t('devices.deviceData')}:${deviceValuesHTML}
` : ''}
${t('systemSetting.longitude')}:${lonStr}
${t('systemSetting.latitude')}:${latStr}
${t('systemSetting.status')}: @@ -871,9 +1041,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
`; } else { tooltip.innerHTML = ` -
📍 ${t('systemSetting.longitude')}:${lonStr}
-
${t('systemSetting.latitude')}:${latStr}
- `; + < div style = "font-weight:600;margin-bottom:4px;" >📍 ${t('systemSetting.longitude')}:${lonStr} +
${t('systemSetting.latitude')}:${latStr}
+ `; } } @@ -891,9 +1061,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, : t('devices.mapEditor.unbound'); tooltip.innerHTML = ` -
📍 ${point.alias || '-'}
+ < div style = "font-weight:600;margin-bottom:4px;" >📍 ${point.alias || '-'}
🤖 ${deviceLabel}
- `; + `; } function fetchPublishedLayers() { @@ -1130,7 +1300,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, } } - function flyToLayer(layerIdentifier, baseUrl, flyHeight = 100) { + function flyToLayer(layerIdentifier, baseUrl, flyHeight = 400) { //console.log('开始获取图层范围', layerIdentifier); const url = `${baseUrl}/wms?service=WMS&version=1.1.1&request=GetCapabilities`; @@ -1335,13 +1505,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, !isNaN(Number(realtimePosition.lat)); if (!mapLayer || !viewerRef.current || hasRealtime) return; resetFlightPriority(); - flyToLayer(mapLayer, envConfig.geoserver_url, 100); + flyToLayer(mapLayer, envConfig.geoserver_url, 400); }, [mapLayer]); // 拉取当前场站已配置的返航点与分区 useEffect(() => { if (!stationId) { - setStationOverlay({ returnPoints: [], regions: [] }); + setStationOverlay({ returnPoints: [], regions: [], tempObstaclePoints: [] }); return; } let cancelled = false; @@ -1349,7 +1519,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, .then((res) => { if (cancelled) return; const pts = res?.code === 200 ? (res?.data?.restPoints || []) : []; - setStationOverlay(prev => ({ ...prev, returnPoints: Array.isArray(pts) ? pts : [] })); + setStationOverlay(prev => ({ ...prev, tempObstaclePoints: res?.data?.tempObstaclePoints || [], returnPoints: Array.isArray(pts) ? pts : [] })); }) .catch(() => { }); getStationRegions({ siteId: stationId }) @@ -1455,10 +1625,373 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, }); stationOverlayIdsRef.current.push(id); }); + // 障碍物点:圆心 + 半径红色圆圈 + (stationOverlay.tempObstaclePoints || []).forEach((obstacle, idx) => { + const lon = Number( + obstacle?.position?.lng ?? obstacle?.position?.lon + ); + const lat = Number(obstacle?.position?.lat); + const radius = Number(obstacle?.radius ?? 2); + + if ( + !Number.isFinite(lon) || + !Number.isFinite(lat) || + lon === 0 || + lat === 0 || + !Number.isFinite(radius) || + radius <= 0 + ) { + return; + } + + // 每个障碍物使用稳定的实体 ID + const id = `station-obstacle-point-${idx}`; + + // 判断当前障碍物是否被选中 + const isHighlighted = + focusOverlay?.type === 'obstaclePoint' && + ( + String(focusOverlay.id) === String(obstacle.id) || + String(focusOverlay.index) === String(idx) + ); + + const redColor = Cesium.Color.fromCssColorString( + isHighlighted ? '#FF1F1F' : '#F5222D' + ); + + // 圆心位置 + const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0); + + viewer.entities.add({ + id, + + // 保存障碍物信息,方便后续识别 + obstaclePointData: { + alias: obstacle?.alias || `障碍物点-${idx + 1}`, + radius, + index: idx, + }, + + position, + + // 以经纬度位置为圆心,radius 单位为米 + ellipse: { + semiMajorAxis: new Cesium.ConstantProperty(radius), + semiMinorAxis: new Cesium.ConstantProperty(radius), + height: 0, + + material: redColor.withAlpha(isHighlighted ? 0.3 : 0.18), + + // 红色圆圈轮廓 + outline: true, + outlineColor: redColor, + outlineWidth: isHighlighted ? 4 : 2, + + heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, + }, + + // 圆心标记 + point: { + pixelSize: isHighlighted ? 12 : 9, + color: redColor, + outlineColor: Cesium.Color.WHITE, + outlineWidth: 2, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + + // 名称与半径标签 + label: { + text: `${obstacle?.alias || `障碍物点-${idx + 1}`} (${radius}m)`, + font: isHighlighted ? 'bold 14px sans-serif' : '12px sans-serif', + fillColor: Cesium.Color.WHITE, + showBackground: true, + backgroundColor: redColor.withAlpha(0.85), + pixelOffset: new Cesium.Cartesian2(0, -18), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + distanceDisplayCondition: new Cesium.DistanceDisplayCondition( + 0, + 100000 + ), + }, + }); + + stationOverlayIdsRef.current.push(id); + + const handleId = `station-obstacle-handle-${idx}`; + + viewer.entities.add({ + id: handleId, + + // 给鼠标事件识别手柄用 + obstacleHandleData: { + index: idx, + obstacleId: obstacle?.id, + }, + + position: getObstacleHandlePosition( + Cesium, + lon, + lat, + radius + ), + + point: { + pixelSize: isHighlighted ? 16 : 13, + color: Cesium.Color.WHITE, + outlineColor: Cesium.Color.RED, + outlineWidth: 3, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + + label: { + text: '↔', + font: 'bold 12px sans-serif', + fillColor: Cesium.Color.RED, + pixelOffset: new Cesium.Cartesian2(0, -1), + disableDepthTestDistance: Number.POSITIVE_INFINITY, + }, + }); + + stationOverlayIdsRef.current.push(handleId); + }); + + viewer.scene.requestRender(); }, [stationOverlay, highlightReturnPointId]); + + useEffect(() => { + const viewer = viewerRef.current; + const Cesium = window.Cesium; + + if (!viewer || !Cesium || from != "mapEditor") return; + + const handler = new Cesium.ScreenSpaceEventHandler( + viewer.scene.canvas + ); + + const getGroundPosition = (position) => { + const ray = viewer.camera.getPickRay(position); + if (!ray) return null; + + return viewer.scene.globe.pick(ray, viewer.scene); + }; + + const getDistance = (center, target) => { + return Cesium.Cartesian3.distance(center, target); + }; + + // 鼠标按下:判断是否点中障碍物圆圈边缘 + handler.setInputAction((event) => { + const viewer = viewerRef.current; + const Cesium = window.Cesium; + + if (!viewer || !Cesium) return; + + const picked = viewer.scene.pick(event.position); + const entity = picked?.id; + const handleData = entity?.obstacleHandleData?.getValue + ? entity.obstacleHandleData.getValue() + : entity?.obstacleHandleData; + + // 没点中手柄,不启动半径拖动 + if (!handleData) return; + + const index = Number(handleData.index); + const obstacles = stationOverlay.tempObstaclePoints || []; + const obstacle = obstacles[index]; + + if (!obstacle) return; + + const lon = Number( + obstacle.position?.lng ?? obstacle.position?.lon + ); + const lat = Number(obstacle.position?.lat); + const radius = Number(obstacle.radius ?? 2); + + if ( + !Number.isFinite(lon) || + !Number.isFinite(lat) || + !Number.isFinite(radius) + ) { + return; + } + + draggingObstacleRef.current = { + index, + entityId: `station-obstacle-point-${index}`, + handleId: `station-obstacle-handle-${index}`, + center: Cesium.Cartesian3.fromDegrees(lon, lat, 0), + lon, + lat, + radius, + }; + + setIsDraggingObstacle(true); + + // 拖动时禁用相机旋转,避免地图跟着转 + viewer.scene.screenSpaceCameraController.enableRotate = false; + }, Cesium.ScreenSpaceEventType.LEFT_DOWN); + + // 鼠标移动:实时更新圆圈半径 + //handler.setInputAction((event) => { + // const viewer = viewerRef.current; + // const Cesium = window.Cesium; + // const dragging = draggingObstacleRef.current; + + // if (!viewer || !Cesium || !dragging) return; + + // const camera = viewer.camera; + // const ray = camera.getPickRay(event.endPosition); + + // if (!ray) return; + + // // 取鼠标在地球表面的交点 + // const mousePosition = viewer.scene.globe.pick( + // ray, + // viewer.scene + // ); + + // if (!mousePosition) return; + + // // 鼠标到圆心的地表近似距离(米) + // const nextRadius = Math.max( + // 0.5, + // Cesium.Cartesian3.distance( + // dragging.center, + // mousePosition + // ) + // ); + + // dragging.radius = nextRadius; + + // const circleEntity = viewer.entities.getById( + // dragging.entityId + // ); + + // const handleEntity = viewer.entities.getById( + // dragging.handleId + // ); + + // if (circleEntity?.ellipse) { + // circleEntity.ellipse.semiMajorAxis = nextRadius; + // circleEntity.ellipse.semiMinorAxis = nextRadius; + // } + + // if (handleEntity) { + // handleEntity.position = getObstacleHandlePosition( + // Cesium, + // dragging.lon, + // dragging.lat, + // nextRadius + // ); + // } + + // // 如需同步更新标签 + // if (circleEntity?.label) { + // const obstacle = + // (stationOverlay.tempObstaclePoints || [])[dragging.index]; + + // circleEntity.label.text = + // `${obstacle?.alias || `障碍物点-${dragging.index + 1}`} (${nextRadius.toFixed(2)}m)`; + // } + + // viewer.scene.requestRender(); + //}, Cesium.ScreenSpaceEventType.MOUSE_MOVE); + + handler.setInputAction((event) => { + const viewer = viewerRef.current; + const Cesium = window.Cesium; + const dragging = draggingObstacleRef.current; + + if (!viewer || !Cesium || !dragging) return; + + const ray = viewer.camera.getPickRay(event.endPosition); + if (!ray) return; + + const mousePosition = viewer.scene.globe.pick( + ray, + viewer.scene + ); + if (!mousePosition) return; + + // 计算鼠标到圆心的距离,单位米 + const nextRadius = Math.max( + 0.5, + Cesium.Cartesian3.distance( + dragging.center, + mousePosition + ) + ); + + dragging.radius = nextRadius; + + const circle = viewer.entities.getById(dragging.entityId); + const handle = viewer.entities.getById(dragging.handleId); + + // 同步更新圆圈半径 + if (circle?.ellipse) { + circle.ellipse.semiMajorAxis.setValue(nextRadius); + circle.ellipse.semiMinorAxis.setValue(nextRadius); + } + + // 同步更新手柄位置 + if (handle) { + handle.position = new Cesium.ConstantPositionProperty( + getObstacleHandlePosition( + Cesium, + dragging.lon, + dragging.lat, + nextRadius + ) + ); + } + + // 同步更新圆圈标签 + if (circle?.label) { + const obstacle = + stationOverlay.tempObstaclePoints?.[dragging.index]; + + circle.label.text.setValue( + `${obstacle?.alias || `障碍物点-${dragging.index + 1}`} (${nextRadius.toFixed(2)}m)` + ); + } + + viewer.scene.requestRender(); + }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); + + // 鼠标松开:更新数据并保存 + handler.setInputAction(() => { + const viewer = viewerRef.current; + const dragging = draggingObstacleRef.current; + + if (!dragging) return; + + // 保存最终半径 + const { index, radius } = dragging; + + draggingObstacleRef.current = null; + setIsDraggingObstacle(false); + + if (viewer) { + viewer.scene.screenSpaceCameraController.enableRotate = true; + } + console.log('radius', radius, index); + // 通知父组件更新列表 + + // 通知父组件更新列表 + onObstacleRadiusChange?.(index, radius); + }, Cesium.ScreenSpaceEventType.LEFT_UP); + + return () => { + handler.destroy(); + + viewer.scene.screenSpaceCameraController.enableRotate = true; + viewer.scene.screenSpaceCameraController.enableTranslate = true; + }; + }, [stationOverlay]); + // 点击已配置列表:定位到对应返航点/分区;返航点额外高亮 useEffect(() => { const viewer = viewerRef.current; @@ -1504,6 +2037,48 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, ), duration: 0.8, }); + } else { + const obstaclePoints = stationOverlay.tempObstaclePoints || []; + + // 优先根据 index 查找;如果没有 index,再尝试根据 id 查找 + const obstacleIndex = Number.isInteger(focusOverlay.index) + ? focusOverlay.index + : obstaclePoints.findIndex( + (item) => + String(item.id) === String(focusOverlay.id) + ); + + const obstacle = obstaclePoints[obstacleIndex]; + + if (!obstacle) return; + + const lon = Number( + obstacle?.position?.lng ?? obstacle?.position?.lon + ); + const lat = Number(obstacle?.position?.lat); + const radius = Number(obstacle?.radius ?? 2); + + if ( + !Number.isFinite(lon) || + !Number.isFinite(lat) || + lon === 0 || + lat === 0 + ) { + return; + } + + setLegendHighlight('obstaclePoint'); + setHighlightReturnPointId(''); + + // 飞到障碍物圆心附近,并根据半径调整视角 + viewer.camera.flyTo({ + destination: Cesium.Cartesian3.fromDegrees( + lon, + lat, + Math.max(50, Number.isFinite(radius) ? radius * 5 : 50) + ), + duration: 0.8, + }); } }, [focusOverlay, stationOverlay]); @@ -1559,15 +2134,29 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, // 点击设备后仅做地图相机定位:不隐藏其他设备图标、不创建额外的 focusEntity // 所有设备图标与光圈保持原样显示,由侧边抽屉展示详情 - flyToView(viewer, FLIGHT_PRIORITY.focus, { - destination: Cesium.Cartesian3.fromDegrees(Number(focusLocation.lon), Number(focusLocation.lat), focusLocation.height || 800), - orientation: { - heading: Cesium.Math.toRadians(0.0), - pitch: Cesium.Math.toRadians(-90.0), - roll: 0.0, - }, - duration: 1.5 - }); + const lon = Number(focusLocation.lon); + const lat = Number(focusLocation.lat); + + if (isValidCoordinate(lon, lat)) { + flyToView( + viewer, + FLIGHT_PRIORITY.focus, + { + destination: Cesium.Cartesian3.fromDegrees( + lon, + lat, + 800 + ), + orientation: { + heading: 0, + pitch: Cesium.Math.toRadians(-90), + roll: 0, + }, + duration: 1.2, + }, + `focus:${focusLocation.id ?? `${lon},${lat}`}` + ); + } }, [focusLocation]); function flyToRobots(viewer, robots) { @@ -1610,7 +2199,6 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, ctx.fill(); return canvas.toDataURL(); } - const yellowCircleImg = useMemo(() => createYellowCircleDataUrl(30), []); // 监听 drawRealTime 变化,每次开始执行任务时重置为定位模式 useEffect(() => { @@ -1642,33 +2230,33 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, }, [drawRealTime]); // 处理完成点 - 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; - } + //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; + // } - const point = { lng: finishPoint.lng, lat: finishPoint.lat }; + // const point = { lng: finishPoint.lng, lat: finishPoint.lat }; - // 如果是定位模式且还没有导航模式,则切换到导航模式 - if (!isNavigationModeRef.current && drawRealTime) { - tracePointRef.current.setMode(TPMode.NAVIGATION); - isNavigationModeRef.current = true; - } + // // 如果是定位模式且还没有导航模式,则切换到导航模式 + // if (!isNavigationModeRef.current && drawRealTime) { + // tracePointRef.current.setMode(TPMode.NAVIGATION); + // isNavigationModeRef.current = true; + // } - tracePointRef.current.upsert(point, TPAction.ADD); - lastFinishPointRef.current = finishPoint; + // tracePointRef.current.upsert(point, TPAction.ADD); + // lastFinishPointRef.current = finishPoint; - // 更新轨迹绘制 - updateTraceLine(); + // // 更新轨迹绘制 + // updateTraceLine(); - // 更新或添加跟随小车 - }, [finishPoint, drawRealTime]); + // // 更新或添加跟随小车 + //}, [finishPoint, drawRealTime]); // 更新跟随小车 const updateFollowCar = (cartesianPos, heading = 0) => { @@ -1842,6 +2430,20 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, } } }, [ifClear]) + function isValidCoordinate(lon, lat) { + const longitude = Number(lon); + const latitude = Number(lat); + + return ( + lon != null && + lat != null && + Number.isFinite(longitude) && + Number.isFinite(latitude) && + Math.abs(longitude) <= 180 && + Math.abs(latitude) <= 90 && + !(longitude === 0 && latitude === 0) + ); + } useEffect(() => { @@ -2074,55 +2676,60 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, // ============================== // 自动 flyTo // ============================== - - if (!isRealtimeMode && validPositions.length > 0) { - - let minLon = 180, - maxLon = -180, - minLat = 90, - maxLat = -90; - - validPositions.forEach(p => { - - minLon = Math.min(minLon, p.lon); - maxLon = Math.max(maxLon, p.lon); - minLat = Math.min(minLat, p.lat); - maxLat = Math.max(maxLat, p.lat); - - }); - if (getCameraMode() !== "devices") return; + //const hasRealtime = isValidCoordinate( + // realtimePosition?.lon, + // realtimePosition?.lat + //); - if (validPositions.length === 1) { + //if (!hasRealtime && validPositions.length > 0) { - const p = validPositions[0]; + // let minLon = 180, + // maxLon = -180, + // minLat = 90, + // maxLat = -90; - flyToView(viewer, FLIGHT_PRIORITY.devices, { - destination: Cesium.Cartesian3.fromDegrees( - p.lon, - p.lat, - 800 - ), - duration: 1.2 - }); + // validPositions.forEach(p => { - } else { + // minLon = Math.min(minLon, p.lon); + // maxLon = Math.max(maxLon, p.lon); + // minLat = Math.min(minLat, p.lat); + // maxLat = Math.max(maxLat, p.lat); - const rectangle = Cesium.Rectangle.fromDegrees( - minLon, - minLat, - maxLon, - maxLat - ); + // }); + // if (getCameraMode() !== "devices") return; - flyToView(viewer, FLIGHT_PRIORITY.devices, { - destination: rectangle, - duration: 1.2 - }); - } + // if (validPositions.length === 1) { - } + // const p = validPositions[0]; + + // flyToView(viewer, FLIGHT_PRIORITY.devices, { + // destination: Cesium.Cartesian3.fromDegrees( + // p.lon, + // p.lat, + // 800 + // ), + // duration: 1.2 + // }); + + // } else { + + // const rectangle = Cesium.Rectangle.fromDegrees( + // minLon, + // minLat, + // maxLon, + // maxLat + // ); + + // flyToView(viewer, FLIGHT_PRIORITY.devices, { + // destination: rectangle, + // duration: 1.2 + // }); + + // } + + //} }, [devices, realtimePosition]); @@ -2219,28 +2826,28 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, const picked = viewer.scene.pick(movement.position); let robot = null; - if (window.Cesium.defined(picked) && picked.id) { - const robotProp = picked.id.properties?.robot; - robot = robotProp ? (typeof robotProp.getValue === "function" ? robotProp.getValue() : robotProp) : (picked.id.robotData || null); - if (!robot) { - const pickedCarto = viewer.scene.globe.pick(movement.position, viewer.scene); - if (window.Cesium.defined(pickedCarto)) { - const clon = window.Cesium.Math.toDegrees(pickedCarto.longitude); - const clat = window.Cesium.Math.toDegrees(pickedCarto.latitude); - let best = null; - let bestDist = 0.002; - devices.forEach(d => { - const raw = d?.locationMessage || d?.lastRunningStatus || {}; - const dlon = Number(raw.longitude); - const dlat = Number(raw.latitude); - if (!isFinite(dlon) || !isFinite(dlat)) return; - const dist = Math.hypot(dlon - clon, dlat - clat); - if (dist < bestDist) { bestDist = dist; best = d; } - }); - robot = best; - } - } - } + //if (window.Cesium.defined(picked) && picked.id) { + // const robotProp = picked.id.properties?.robot; + // robot = robotProp ? (typeof robotProp.getValue === "function" ? robotProp.getValue() : robotProp) : (picked.id.robotData || null); + // if (!robot) { + // const pickedCarto = viewer.scene.globe.pick(movement.position, viewer.scene); + // if (window.Cesium.defined(pickedCarto)) { + // const clon = window.Cesium.Math.toDegrees(pickedCarto.longitude); + // const clat = window.Cesium.Math.toDegrees(pickedCarto.latitude); + // let best = null; + // let bestDist = 0.002; + // devices.forEach(d => { + // const raw = d?.locationMessage || d?.lastRunningStatus || {}; + // const dlon = Number(raw.longitude); + // const dlat = Number(raw.latitude); + // if (!isFinite(dlon) || !isFinite(dlat)) return; + // const dist = Math.hypot(dlon - clon, dlat - clat); + // if (dist < bestDist) { bestDist = dist; best = d; } + // }); + // robot = best; + // } + // } + //} if (robot) { onCameraClickRef.current?.(robot); } @@ -2432,8 +3039,26 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, if (entity.label) entity.label.show = false; // ✅ 隐藏 label }); - const lon = Number(realtimePosition.lon || finishPoint.lng); - const lat = Number(realtimePosition.lat || finishPoint.lat); + const rawLon = realtimePosition?.lon; + const rawLat = realtimePosition?.lat; + + const lon = Number(rawLon); + const lat = Number(rawLat); + + // 实时坐标缺失或无效时,不绘制、不追加轨迹点 + if ( + rawLon == null || + rawLat == null || + !Number.isFinite(lon) || + !Number.isFinite(lat) || + lon < -180 || + lon > 180 || + lat < -90 || + lat > 90 || + (lon === 0 && lat === 0) + ) { + return; + } const position = Cesium.Cartesian3.fromDegrees(lon, lat, 1); @@ -2445,26 +3070,48 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, // ==================================== if (isDroneMode || from == "deviceStatus" || from == "devicesTask") { // 轨迹点去抖动(防止重复点) + // 实时轨迹过滤:重复点不添加,异常跳点不连接 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; - //} + const toRad = (deg) => (deg * Math.PI) / 180; + const R = 6371000; // 地球半径,米 + + const dLat = toRad(lat - last.lat); + const dLon = toRad(lon - last.lon); + const lat1 = toRad(last.lat); + const lat2 = toRad(lat); + + const a = + Math.sin(dLat / 2) ** 2 + + Math.cos(lat1) * + Math.cos(lat2) * + Math.sin(dLon / 2) ** 2; + + const distance = 2 * R * Math.atan2( + Math.sqrt(a), + Math.sqrt(1 - a) + ); + + // 重复点不添加 + if (distance < 0.001) { + shouldAdd = false; + } + + // 单次位置跳变超过 2 米,视为异常点,不连线 + if (distance > 2) { + shouldAdd = false; + } } if (shouldAdd && drawRealTime) { realtimeLastPointRef.current = { lon, lat }; + realtimeCartesianRef.current.push( - // ✅ 统一 1 米高度,和机器图标 z 值完全一致,放大后不再偏移 Cesium.Cartesian3.fromDegrees(lon, lat, 1) ); } - // 第一次进入 realtime -> 隐藏所有设备 if (!realtimeHiddenRef.current) { realtimeHiddenRef.current = true; @@ -2747,31 +3394,33 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, realtimeCartesianRef.current = []; } - if (!hasFlownRef.current) { - - hasFlownRef.current = true; - if (getCameraMode() !== "realtime") return; - - flyToView(viewer, FLIGHT_PRIORITY.realtime, { - - destination: Cesium.Cartesian3.fromDegrees( - lon, - lat, - 30 - ), - - orientation: { - heading: 0, - pitch: Cesium.Math.toRadians(-90), - roll: 0 + if ( + !hasFlownRef.current && + getCameraMode() === 'realtime' + ) { + const started = flyToView( + viewer, + FLIGHT_PRIORITY.realtime, + { + destination: Cesium.Cartesian3.fromDegrees( + lon, + lat, + 30 + ), + orientation: { + heading: 0, + pitch: Cesium.Math.toRadians(-90), + roll: 0, + }, + duration: 1.2, }, + `realtime:${lon.toFixed(6)},${lat.toFixed(6)}` + ); - duration: 1.2 - - }); - + if (started) { + hasFlownRef.current = true; + } } - viewer.scene.requestRender(); }, [realtimePosition]); @@ -2838,7 +3487,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, }} /> {/* 图例:返航点 / 分区 */} - {(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0) && ( + {(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0 || stationOverlay.tempObstaclePoints.length > 0) && (
{t('devices.mapEditor.restArea')}
+ + +
+ + {t('devices.mapEditor.obstacle')} +
)} diff --git a/src/components/devices/DeviceStatusPage.tsx b/src/components/devices/DeviceStatusPage.tsx index 902d03a..cdb0353 100644 --- a/src/components/devices/DeviceStatusPage.tsx +++ b/src/components/devices/DeviceStatusPage.tsx @@ -2796,7 +2796,7 @@ export default function DeviceStatusPage() { -
+
{isVideoPlaying && ( @@ -3114,11 +3114,11 @@ export default function DeviceStatusPage() { {t('devices.features.title')}} - bodyStyle={{ padding: 10, display: 'flex', }} + bodyStyle={{ padding: 10, display: 'flex', flex: "auto" }} > diff --git a/src/components/devices/RobotFeatureButtons.tsx b/src/components/devices/RobotFeatureButtons.tsx index de55a10..98952e5 100644 --- a/src/components/devices/RobotFeatureButtons.tsx +++ b/src/components/devices/RobotFeatureButtons.tsx @@ -90,7 +90,7 @@ const RobotFeatureButtons: React.FC = ({ }; return ( -
+
{list.map((f) => { const isActive = active.has(f.key); return ( diff --git a/src/components/devices/RobotTaskPage.tsx b/src/components/devices/RobotTaskPage.tsx index b84fba2..9f284c1 100644 --- a/src/components/devices/RobotTaskPage.tsx +++ b/src/components/devices/RobotTaskPage.tsx @@ -70,7 +70,6 @@ export default function RobotTaskPage() { const [realtimeMap, setRealtimeMap] = useState({}); const [execute, setExecute] = useState(false); // 是否执行任务 const [taskList, setTaskList] = useState([]); - const [arrivedPoint, setArrivedPoint] = useState(null);//完成点 const { modal } = App.useApp(); const [polyPoints, setPolyPoints] = useState([]); @@ -183,10 +182,19 @@ export default function RobotTaskPage() { } - const handleFinishEdPoint = (point) => { - setArrivedPoint(point); + const fetchAllData = async () => { + if (!stationId) return; + + try { + const deviceRes = await getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1, orgId: currentStation?.orgId }); + const devData = deviceRes?.code === 200 ? (deviceRes.rows || []) : []; + setDevices(devData); + } catch (err) { + console.error('数据请求失败', err); + } }; + // 根据任务ID获取路径并显示在地图上 const loadTaskPath = async (taskId) => { //return; @@ -287,6 +295,9 @@ export default function RobotTaskPage() { console.log('收到 route_post 消息:', msg); setProPoints(msg); }; + controller.deviceStatusChangedMsg = () => { + fetchAllData(); + } @@ -459,17 +470,6 @@ export default function RobotTaskPage() { // 获取数据 - const fetchAllData = async () => { - if (!stationId) return; - - try { - const deviceRes = await getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1, orgId: currentStation?.orgId }); - const devData = deviceRes?.code === 200 ? (deviceRes.rows || []) : []; - setDevices(devData); - } catch (err) { - console.error('数据请求失败', err); - } - }; useEffect(() => { fetchAllData(); @@ -1112,17 +1112,17 @@ export default function RobotTaskPage() { {/*//)}*/} - {/*{record.taskStaus === 'EXECUTING' && (*/} - handlePauseTask(record)} - okText={t('common.ok')} cancelText={t('common.cancel')} - > - - - {/*)}/*/} + {record.taskStaus === 'EXECUTING' && ( + handlePauseTask(record)} + okText={t('common.ok')} cancelText={t('common.cancel')} + > + + + )} {record.taskStaus === 'PAUSE' && ( - + {/* setIsTaskModalOpen(true)} /> - + */} } diff --git a/src/components/devices/Steerbutton.tsx b/src/components/devices/Steerbutton.tsx index 8448e97..019309c 100644 --- a/src/components/devices/Steerbutton.tsx +++ b/src/components/devices/Steerbutton.tsx @@ -128,7 +128,6 @@ const SteerButton = ({ minHeight: 46, padding: '6px 4px', borderRadius: 8, - background: pressed ? `${color}30` : '#1e293b', border: `1px solid ${pressed ? color : `${color}55`}`, color, cursor: 'pointer', diff --git a/src/components/devices/deviceController.js b/src/components/devices/deviceController.js index 822d3fc..ce1137b 100644 --- a/src/components/devices/deviceController.js +++ b/src/components/devices/deviceController.js @@ -43,6 +43,7 @@ export default class DeviceController { this.onRequestControlStatusChange = null; this.onPermissionRequest = null; this.onRoutePost = null; + this.deviceStatusChangedMsg = null; this.onIsFinished = null; this.onIsExecuting = null; this.handleArrivedPoint = null; @@ -118,34 +119,46 @@ export default class DeviceController { try { msg = JSON.parse(event.data); } catch (e) { return; } console.log('[DeviceController] 收到全量设备状态 初始状态', msg); - if (msg?.type !== 'mapPush') return; - const list = Array.isArray(msg?.data) && msg.data.length - ? msg.data - : []; - if (!list.length) return; + if (msg?.type == 'mapPush') { + const list = Array.isArray(msg?.data) && msg.data.length + ? msg.data + : []; + if (!list.length) return; + + const next = {}; + list.forEach((it) => { + const key = String(it?.id ?? ''); + if (!key) return; + next[key] = { + id: key, + lng: String(it?.lng ?? it?.lon ?? it?.longitude), + lat: String(it?.lat ?? it?.latitude), + yaw: it?.y, + fix: it?.f !== undefined ? String(it.f) : undefined, + fixStatus: it?.f !== undefined ? String(it.f) : undefined, + altitude: it?.a !== undefined ? String(it.a) : undefined, + status: it?.s ?? it?.status, + taskId: it?.t ?? it?.taskId ?? null, + battery: it?.b !== undefined ? Number(it.b) : (it?.batteryLevel !== undefined ? Number(it.batteryLevel) : undefined), + hasAlarm: !!it?.ha || !!it?.hasAlarm, + updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), + controlMode: it?.cm ?? it?.controlMode, + }; + }); + console.log('[DeviceController] 收到全量设备状态', next); + this.onMapPush?.(next); + } + if (msg?.type == 'device_task_change') { + if (msg.status == "FINISH") { + console.log('task finish'); + this.onIsFinished?.(true); + } + if (msg.status == "EXECUTING" || msg.status == "CANCELLED" || msg.status == "FAILED") { + this.onIsExecuting?.(true); + } + + } - const next = {}; - list.forEach((it) => { - const key = String(it?.id ?? ''); - if (!key) return; - next[key] = { - id: key, - lng: String(it?.lng ?? it?.lon ?? it?.longitude), - lat: String(it?.lat ?? it?.latitude), - yaw: it?.y, - fix: it?.f !== undefined ? String(it.f) : undefined, - fixStatus: it?.f !== undefined ? String(it.f) : undefined, - altitude: it?.a !== undefined ? String(it.a) : undefined, - status: it?.s ?? it?.status, - taskId: it?.t ?? it?.taskId ?? null, - battery: it?.b !== undefined ? Number(it.b) : (it?.batteryLevel !== undefined ? Number(it.batteryLevel) : undefined), - hasAlarm: !!it?.ha || !!it?.hasAlarm, - updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), - controlMode: it?.cm ?? it?.controlMode, - }; - }); - console.log('[DeviceController] 收到全量设备状态', next); - this.onMapPush?.(next); }; ws.onerror = () => { @@ -447,10 +460,10 @@ export default class DeviceController { break; } case "device_task_change": { - if (msg.deviceId != this.connectedDeviceSn) return; console.log('task change:', msg); if (msg.status == "FINISH") { + console.log('task finish'); this.onIsFinished?.(true); } if (msg.status == "EXECUTING") { @@ -479,7 +492,6 @@ export default class DeviceController { } case 'detectionReport': - if (msg.data?.deviceId !== this.connectedDeviceSn) return; const { isSecure, obstacle } = msg.data; if (isSecure) return; const type = obstacle?.type; @@ -500,6 +512,14 @@ export default class DeviceController { break; + case 'device_status_changed': + this.deviceStatusChangedMsg?.(msg); + break; + + case 'remoteControl': + + break; + default: break; } diff --git a/src/components/recharts.jsx b/src/components/recharts.jsx index 86e8136..a2d309e 100644 --- a/src/components/recharts.jsx +++ b/src/components/recharts.jsx @@ -160,7 +160,7 @@ export const UniversalLineChart = ({ boxSizing: 'border-box', background: backgroundColor, borderRadius: 12, - padding: 12, + padding: 4, overflow: 'hidden', ...style, }} @@ -334,7 +334,6 @@ export const UniversalPieChart = ({ boxSizing: 'border-box', background: backgroundColor, borderRadius: 12, - padding: 12, overflow: 'hidden', ...style, }} diff --git a/src/locales/en/index.ts b/src/locales/en/index.ts index a33c73d..10aae78 100644 --- a/src/locales/en/index.ts +++ b/src/locales/en/index.ts @@ -906,6 +906,9 @@ mapEditor: { returnPoint: 'Return Point', + noConfiguredReturnPoints: 'noConfiguredReturnPoints', + noConfiguredRegions: 'noConfiguredRegions', + noConfiguredObstaclePoints: "noConfiguredObstaclePoints", legend: 'Legend', unbound: 'Unbound', duplicateBindDevice: 'Duplicate Bind Device', @@ -945,6 +948,8 @@ mapEditorTitle: 'Map Editor', fillName: 'Please enter route name', needAtLeast2Points: 'At least 2 points required', + obstacle: 'Obstacle', + }, turnSpeed: 'Turn Speed', realtimeVideoMonitor: 'Realtime Video Monitor', rechargeBtn: 'Recharge Btn', @@ -2811,7 +2816,6 @@ operationLog: 'Operation Log', errorLog: 'Error Log', systemLog: 'System Log', - operator: 'Operator', operationContent: 'Operation Content', operationTime: 'Operation Time', ipAddress: 'IP Address', diff --git a/src/locales/zh/index.ts b/src/locales/zh/index.ts index 11d2eeb..ba5d5c6 100644 --- a/src/locales/zh/index.ts +++ b/src/locales/zh/index.ts @@ -1559,7 +1559,7 @@ const zh = { pointEmptyHint: '暂无标记点,请在地图上点击添加', routeEmptyHint: '暂无路径点,请在地图上依次点击打点', duplicateBindDevice: '重复绑定设备', - bindUpdateSuccess: '绑定设备已更新', + bindUpdateSuccess: '绑定设备已更新', save: '保存', saveSuccess: '保存成功', @@ -1571,6 +1571,8 @@ const zh = { configuredRegions: '已配置分区', noConfiguredReturnPoints: '暂无已配置返航点', noConfiguredRegions: '暂无已配置分区', + obstacle: '障碍点', + noConfiguredObstaclePoints: "暂无已配置障碍点", unnamed: '未命名', regionCode: '分区编码', scopeCount: '范围点数',