优化声网视频 几分钟停止订阅的bug,地图上给每个机器加上背景光圈,显示工作状态,光圈支持实时根据定位走,优化实时路线和机器的中心不在同一点的问题

This commit is contained in:
mmc
2026-09-15 16:28:28 +08:00
parent f852174fde
commit 9017cf9c87
8 changed files with 542 additions and 89 deletions

View File

@@ -1,47 +1,92 @@
import React, { useEffect, useRef, useState } from "react";
import AgoraRTC, { IAgoraRTCClient, IRemoteVideoTrack } from "agora-rtc-sdk-ng";
import { Badge, message } from "antd";
AgoraRTC.setLogLevel(2); // 2=只输出warning/error,屏蔽debug日志
const APP_ID = "7887b4db6033410d9ac3264b40ca9c1a";
const TOKEN = "007eJxTYKjmeKazOKdUZ5qMsU389u45l6ruuuQlze8o+OZWHdBUHK3AYG5hYZ5kkpJkZmBsbGJokGKZmGxsZGaSZGKQnGiZbJh4dsuSrIZARoYFWw4zMTJAIIjPxWBiqFuSkVqUm5jDwAAA1JUhaw==";
export default function AgrtcRoomRobot({ CHANNEL }) {
const TOKEN = "007eJxTYDhxaLPL8617mtfHFi2tfJhQNSXh5vNJnqvu8b/3PenKKdumwGBuYWGeZJKSZGZgbGxiaJBimZhsbGRmkmRikJxomWyYuHHFiqyGQEaGB6+fMDEyQCCIz81gYqhbklGUmphrYMTAAAAyfSTX";
export default function AgrtcRoomRobot({ CHANNEL }: { CHANNEL: string }) {
const [uid] = useState(() => Number(Math.floor(Math.random() * 100000)));
const [connected, setConnected] = useState(false);
const [joined, setJoined] = useState(false);
// 标记是否存在远端视频流
const [hasRemoteVideo, setHasRemoteVideo] = useState(false);
const remoteVideoRef = useRef<HTMLDivElement>(null);
const clientRef = useRef<IAgoraRTCClient | null>(null);
const remoteVideoTrackRef = useRef<IRemoteVideoTrack | null>(null);
const joiningRef = useRef(false);
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
const subscribedUidRef = useRef<number | null>(null);
useEffect(() => {
const client = AgoraRTC.createClient({
mode: "live",
mode: "rtc",
codec: "h264",
});
clientRef.current = client;
client.setClientRole("audience");
let isUnmounted = false;
// ========= 删掉了 setParameters,Web NG不支持!========
let isUnmounted = false;
let videoWatchDogTimer: NodeJS.Timeout | null = null;
let unpublishTimer: NodeJS.Timeout | null = null;
// 停止并清空远端视频
const clearRemoteVideo = () => {
if (remoteVideoTrackRef.current) {
try {
remoteVideoTrackRef.current.stop();
} catch (e) { /* */ }
} catch (e) {
console.warn("stop track error", e);
}
remoteVideoTrackRef.current = null;
}
if (remoteVideoRef.current) {
remoteVideoRef.current.innerHTML = "";
}
subscribedUidRef.current = null;
setHasRemoteVideo(false);
if (videoWatchDogTimer) clearInterval(videoWatchDogTimer);
};
const startVideoWatchDog = () => {
if (videoWatchDogTimer) clearInterval(videoWatchDogTimer);
videoWatchDogTimer = setInterval(async () => {
const track = remoteVideoTrackRef.current;
const dom = remoteVideoRef.current;
if (!track || !dom) return;
const videoEl = dom.querySelector("video") as HTMLVideoElement;
if (!videoEl) return;
if (videoEl.readyState < 2) {
console.warn("看门狗检测视频无画面,尝试重新play");
try {
await track.play(dom);
} catch (e) {
console.warn("看门狗play异常", e);
}
}
}, 3000);
};
const playRemoteTrack = async (track: IRemoteVideoTrack) => {
const dom = remoteVideoRef.current;
if (!dom || !track) return;
try {
await track.play(dom);
console.log("远端视频播放成功");
setHasRemoteVideo(true);
startVideoWatchDog();
} catch (err: any) {
if (err.name === "AbortError") {
console.warn("播放请求被中断 AbortError,忽略", err);
return;
}
console.error("视频播放失败", err);
message.error("视频播放失败");
}
};
// 重连逻辑
const doReconnect = async () => {
if (isUnmounted || joiningRef.current) return;
console.log("执行RTC重连");
console.log("执行RTC重连(信令断开)");
clearRemoteVideo();
setJoined(false);
try {
@@ -50,14 +95,13 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
if (isUnmounted) return;
setJoined(true);
message.info("RTC重连成功");
// 重连成功后重新订阅已经在线的上位机
for (const remoteUser of client.remoteUsers) {
if (isUnmounted) break;
if (remoteUser.hasVideo) {
if (remoteUser.hasVideo && subscribedUidRef.current !== remoteUser.uid) {
await client.subscribe(remoteUser, "video");
remoteVideoTrackRef.current = remoteUser.videoTrack;
remoteUser.videoTrack?.play(remoteVideoRef.current!);
setHasRemoteVideo(true);
subscribedUidRef.current = remoteUser.uid;
await playRemoteTrack(remoteUser.videoTrack!);
}
}
} catch (err: any) {
@@ -69,12 +113,10 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
}
};
// 连接状态变化
const onConnStateChange = (curState: string, prevState: string) => {
if (isUnmounted) return;
console.log("连接状态变更", prevState, "→", curState);
setConnected(curState === "CONNECTED");
// 信令断开,延迟重连
if (curState === "DISCONNECTED") {
clearRemoteVideo();
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
@@ -84,48 +126,53 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
}
};
// 远端用户发布流
const onUserPublished = async (user: any, mediaType: "video" | "audio") => {
if (isUnmounted) return;
console.log("user-published", user.uid, mediaType);
await client.subscribe(user, mediaType);
if (mediaType === "video" && remoteVideoRef.current) {
clearRemoteVideo();
remoteVideoTrackRef.current = user.videoTrack;
user.videoTrack?.play(remoteVideoRef.current);
setHasRemoteVideo(true);
if (mediaType !== "video") return;
if (subscribedUidRef.current === user.uid) {
console.log("该用户已订阅,跳过");
return;
}
// 取消待执行的清空定时器
if (unpublishTimer) clearTimeout(unpublishTimer);
await client.subscribe(user, mediaType);
remoteVideoTrackRef.current = user.videoTrack;
subscribedUidRef.current = user.uid;
await playRemoteTrack(user.videoTrack);
};
// 远端停止发布流(上位机停止推流)
const onUserUnpublished = (user: any, mediaType: "video" | "audio") => {
if (isUnmounted) return;
console.log("user-unpublished", user.uid, mediaType);
if (mediaType === "video") {
if (mediaType === "video" && subscribedUidRef.current === user.uid) {
if (unpublishTimer) clearTimeout(unpublishTimer);
// 延迟2s清空,短闪断自动恢复不黑屏
unpublishTimer = setTimeout(() => {
clearRemoteVideo();
}, 2000);
}
};
const onUserLeft = (user: any) => {
if (isUnmounted) return;
console.log("user-left", user.uid);
if (subscribedUidRef.current === user.uid) {
if (unpublishTimer) clearTimeout(unpublishTimer);
clearRemoteVideo();
}
};
// 远端用户离开频道
const onUserLeft = (user: any) => {
if (isUnmounted) return;
console.log("user-left", user.uid);
clearRemoteVideo();
};
// 远端用户进入
const onUserJoined = (user: any) => {
if (!isUnmounted) console.log("远端用户进入频道:", user.uid);
};
// Token即将过期提醒(测试Token有效期有限)
const onTokenWillExpire = () => {
console.warn("token即将过期,请更新token");
message.warning("Token即将过期,视频可能很快断开");
// 正式环境:请求后端拿新token client.renewToken(newToken)
};
// 注册事件,保存回调引用用于off解绑
client.on("connection-state-change", onConnStateChange);
client.on("user-published", onUserPublished);
client.on("user-unpublished", onUserUnpublished);
@@ -145,20 +192,19 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
console.log("加入频道成功");
setJoined(true);
message.success("RTC已加入频道");
// 上位机已经提前推流,手动订阅
for (const remoteUser of client.remoteUsers) {
if (isUnmounted) break;
console.log("发现已有远端用户:", remoteUser.uid);
if (remoteUser.hasVideo) {
if (remoteUser.hasVideo && subscribedUidRef.current !== remoteUser.uid) {
await client.subscribe(remoteUser, "video");
remoteVideoTrackRef.current = remoteUser.videoTrack;
remoteUser.videoTrack?.play(remoteVideoRef.current!);
setHasRemoteVideo(true);
subscribedUidRef.current = remoteUser.uid;
await playRemoteTrack(remoteUser.videoTrack!);
}
}
} catch (err: any) {
if (err?.code === "OPERATION_ABORTED") {
console.log("join操作被取消(StrictMode/组件卸载),忽略");
console.log("join操作被取消,忽略");
return;
}
console.error("加入频道失败:", err);
@@ -172,10 +218,11 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
init();
// 组件卸载清理
return () => {
isUnmounted = true;
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
if (unpublishTimer) clearTimeout(unpublishTimer);
if (videoWatchDogTimer) clearInterval(videoWatchDogTimer);
clearRemoteVideo();
const c = clientRef.current;
if (!c) return;
@@ -188,10 +235,10 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
c.leave();
clientRef.current = null;
};
}, [uid, CHANNEL]);
}, [CHANNEL]);
return (
<div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", borderRadius: 8, overflow: "hidden", background: "#000" }}>
<div style={{ width: "100%", height: "95%", display: "flex", flexDirection: "column", borderRadius: 8, overflow: "hidden", background: "#000" }}>
<div style={{ display: "flex", justifyContent: "end", alignItems: "center", gap: 12, padding: "4px 8px", background: "rgba(255,255,255,0.08)", flexShrink: 0 }}>
<Badge
color={connected ? "green" : "red"}
@@ -206,7 +253,6 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
<span style={{ fontSize: 11, color: "#888" }}>频道:{CHANNEL}</span>
</div>
<div style={{ flex: 1, width: "100%", minHeight: 0, position: "relative" }}>
{/* 无视频时显示加载占位 */}
{!hasRemoteVideo && (
<div style={{
position: "absolute",
@@ -216,15 +262,18 @@ export default function AgrtcRoomRobot({ CHANNEL }) {
justifyContent: "center",
color: "#aaa",
fontSize: 14,
background: "#000"
background: "#000",
zIndex: 2
}}>
视频加载中,等待远端推流...
</div>
)}
{/* Agora 视频容器,内部会被SDK填充video dom */}
<div ref={remoteVideoRef} style={{
position: "absolute",
inset: 0
inset: 0,
width: "100%",
height: "100%",
zIndex: 1
}} />
</div>
</div >

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback } from 'react';
import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback } from 'react';
import carImg from '../assets/images/carplane.png';
import inspectImg from "../assets/images/inspectCar.png"
import planeImg from '../assets/images/planeicon.png';
@@ -49,6 +49,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const realtimeEntityRef = useRef(null);
const realtimeLineRef = useRef(null);
const realtimeTrackRef = useRef([]);
const realtimeHaloControllerRef = useRef(null); // 实时模式光圈 controller
const realtimeHaloRingsRef = useRef([]); // 实时模式光圈 3 个 ring
const realtimeLabelCarNameRef = useRef(''); // 实时模式机器名称缓存
const tracePointRef = useRef(new TracePoint());
const lastFinishPointRef = useRef(null);
@@ -176,6 +179,204 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
onPathChange && onPathChange(newPoints);
};
// ========== 替换原有 createDeviceHaloEntity 完整函数 ==========
// 改动说明:弃用 ellipse 静态椭圆,改用 billboard + createGlowBlinkColor 实现闪烁光圈
// ============================================================
// 设备状态扩散光圈
// 工作中:蓝色
// 空闲:绿色
// 离线:红色
//
// 特点:
// 1. 多层圆环同时向外扩散
// 2. 每一圈都有独立生命周期
// 3. 自动淡出
// 4. 光圈大小随距离变化
// 5. 不修改设备主体 Entity
// ============================================================
// ============================================================
// 设备状态扩散光圈
// ============================================================
// ============================================================
// 设备状态扩散光圈
// 固定屏幕像素大小,不随地图缩放
// 光圈中心与机器图标中心完全对齐
// ============================================================
function createDeviceHaloEntity(
viewer,
id,
position,
haloColor,
size = 100
) {
const Cesium = window.Cesium;
if (!viewer || !position || !id) {
return null;
}
const haloId = `${id}_halo`;
const existingController = viewer.entities.getById(haloId);
const existingRing0 = viewer.entities.getById(`${haloId}_0`);
const existingRing1 = viewer.entities.getById(`${haloId}_1`);
const existingRing2 = viewer.entities.getById(`${haloId}_2`);
// 判断:四个实体【全部存在】→ 只更新位置,不重建
const allExist = existingController && existingRing0 && existingRing1 && existingRing2;
if (allExist) {
existingController.position = position;
existingRing0.position = position;
existingRing1.position = position;
existingRing2.position = position;
return existingController;
}
// 只要任意一个实体缺失:清空旧实体,重新创建整套光圈
[haloId, `${haloId}_0`, `${haloId}_1`, `${haloId}_2`].forEach(eid => {
const old = viewer.entities.getById(eid);
if (old) viewer.entities.remove(old);
});
// ----------------------------------------------------------
// 参数
// ----------------------------------------------------------
const RING_COUNT = 3;
const MIN_SIZE = 100;
const MAX_SIZE = size;
const DURATION = 1600;
const DELAY = 530;
// ----------------------------------------------------------
// 创建控制 Entity
// ----------------------------------------------------------
const controller = viewer.entities.add({
id: haloId,
position: position,
show: true
});
// ----------------------------------------------------------
// 创建扩散圈
// ----------------------------------------------------------
for (let ringIndex = 0; ringIndex < RING_COUNT; ringIndex++) {
const startTime = Date.now() - ringIndex * DELAY;
const getProgress = () => {
const elapsed = (Date.now() - startTime) % DURATION;
return elapsed / DURATION;
};
const ringSize = new Cesium.CallbackProperty(() => {
const progress = getProgress();
const eased = 1 - Math.pow(1 - progress, 2);
return MIN_SIZE + (MAX_SIZE - MIN_SIZE) * eased;
}, false);
const ringColor = new Cesium.CallbackProperty(() => {
const progress = getProgress();
const alpha = 0.42 * Math.pow(1 - progress, 1.5);
return haloColor.withAlpha(alpha);
}, false);
//viewer.entities.add({
// id: `${haloId}_${ringIndex}`,
// position: position,
// billboard: {
// image: createGlowCircleCanvas(64),
// width: ringSize,
// height: ringSize,
// horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
// verticalOrigin: Cesium.VerticalOrigin.CENTER,
// pixelOffset: new Cesium.Cartesian2(0, 0),
// color: ringColor,
// disableDepthTestDistance: Number.POSITIVE_INFINITY,
// heightReference: Cesium.HeightReference.NONE
// }
//});
}
return controller;
}
// ============================================================
// 实时光圈创建 / 更新(给 realtimeCarEntity 配套使用)
// 特点:与 createDeviceHaloEntity 同样的扩散动画效果,独立一套 id
// ============================================================
function ensureRealtimeHalo(viewer, position, color, size = 100, haloId = 'realtime_car_halo') {
const Cesium = window.Cesium;
const haloBaseId = haloId;
const RING_COUNT = 3;
const MIN_SIZE = 100;
const MAX_SIZE = size;
const DURATION = 1600;
const DELAY = 530;
// 1) controller 是否存在
let controller = viewer.entities.getById(haloBaseId);
if (!controller) {
controller = viewer.entities.add({ id: haloBaseId, position, show: true });
} else {
controller.position = position;
}
realtimeHaloControllerRef.current = controller;
// 2) 三个 ring 是否存在(首次创建用,之后只更新 position)
if (realtimeHaloRingsRef.current.length !== RING_COUNT) {
realtimeHaloRingsRef.current = new Array(RING_COUNT).fill(null);
}
for (let ringIndex = 0; ringIndex < RING_COUNT; ringIndex++) {
const ringId = `${haloBaseId}_${ringIndex}`;
let ring = viewer.entities.getById(ringId);
const startTime = Date.now() - ringIndex * DELAY;
const getProgress = () => ((Date.now() - startTime) % DURATION) / DURATION;
if (!ring) {
const ringSize = new Cesium.CallbackProperty(() => {
const progress = getProgress();
const eased = 1 - Math.pow(1 - progress, 2);
return MIN_SIZE + (MAX_SIZE - MIN_SIZE) * eased;
}, false);
const ringColor = new Cesium.CallbackProperty(() => {
const progress = getProgress();
const alpha = 0.42 * Math.pow(1 - progress, 1.5);
return color.withAlpha(alpha);
}, false);
ring = viewer.entities.add({
id: ringId,
position: position,
billboard: {
image: createGlowCircleCanvas(64),
width: ringSize,
height: ringSize,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
pixelOffset: new Cesium.Cartesian2(0, 0),
color: ringColor,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
heightReference: Cesium.HeightReference.NONE,
},
});
realtimeHaloRingsRef.current[ringIndex] = ring;
} else {
ring.position = position;
}
}
}
// ============================================================
// 清理实时光圈(hasRealtime 为 false 时调用)
// ============================================================
function removeRealtimeHalo(viewer) {
const haloBaseId = 'realtime_car_halo';
[haloBaseId, `${haloBaseId}_0`, `${haloBaseId}_1`, `${haloBaseId}_2`].forEach(eid => {
const entity = viewer.entities.getById(eid);
if (entity) viewer.entities.remove(entity);
});
realtimeHaloControllerRef.current = null;
realtimeHaloRingsRef.current = [];
}
const calculateDirection = (point1, point2) => {
const lon1 = point1.lon;
@@ -542,6 +743,19 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
}, [markedPoints]);
// 光圈颜色:工作中蓝(#1677ff)/ 空闲绿(#52c41a)/ 离线红(#ff4d4f)
function getDeviceHaloColor(device) {
const fs = String(device?.feStatus ?? '').toUpperCase();
if (fs == 1) {
return window.Cesium.Color.fromCssColorString('#1677ff');
}
if (fs == 3) {
return window.Cesium.Color.fromCssColorString('#ff4d4f');
}
return window.Cesium.Color.fromCssColorString('#52c41a');
}
function showRobotTooltip(tooltip, robot, position, t) {
const statusMap = {
1: { text: t('common.working'), color: "#10b981" },
@@ -580,6 +794,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
};
function showCoordinateTooltip(tooltip, position, t, lon, lat, robot) {
console.log('showCoordinateTooltip', position, lon, lat, robot);
tooltip.style.display = "block";
tooltip.style.left = position.x + 12 + "px";
tooltip.style.top = position.y + 12 + "px";
@@ -588,11 +803,12 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const lonStr = Number.isFinite(lon) ? lon.toFixed(6) : "--";
const latStr = Number.isFinite(lat) ? lat.toFixed(6) : "--";
if (robot) {
const statusMap = {
1: { text: t('common.working'), color: "#10b981" },
2: { text: t('devices.idle'), color: "#f59e0b" },
3: { text: t('devices.offline'), color: "#f87171" }
1: { text: t('common.working'), color: "#0a40df" },
2: { text: t('devices.idle'), color: "#12c60e" },
3: { text: t('devices.offline'), color: "#f01212" }
};
const status = statusMap[robot.feStatus] || statusMap[1];
let deviceValuesHTML = '';
@@ -606,7 +822,10 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
${deviceValuesHTML ? `<div style="margin-top:8px;"><strong>${t('devices.deviceData')}:</strong>${deviceValuesHTML}</div>` : ''}
<div>${t('systemSetting.longitude')}:${lonStr}</div>
<div>${t('systemSetting.latitude')}:${latStr}</div>
`;
<div>${t('systemSetting.status')}:
<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${status.color};margin-right:4px;"></span>
<span style="color:${status.color};font-weight:bold">${status.text}</span>
</div> `;
} else {
tooltip.innerHTML = `
<div style="font-weight:600;margin-bottom:4px;">📍 ${t('systemSetting.longitude')}:${lonStr}</div>
@@ -872,7 +1091,6 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const maxx = parseFloat(bboxElement.getAttribute('maxx'));
const maxy = parseFloat(bboxElement.getAttribute('maxy'));
targetBbox = [minx, miny, maxx, maxy];
console.log('读取到图层bbox', targetBbox);
}
break;
}
@@ -928,19 +1146,22 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
return canvas;
}
// ========== 修改 createGlowBlinkColor,增加baseColor入参 ==========
function createGlowBlinkColor({
minAlpha = 0.2,
maxAlpha = 0.9,
speed = 1.2
speed = 1.2,
baseColor
} = {}) {
const start = Date.now();
return new window.Cesium.CallbackProperty(() => {
const t = (Date.now() - start) / 1000;
const alpha = minAlpha + (maxAlpha - minAlpha) * (0.5 + 0.5 * Math.sin(t * speed * Math.PI * 2));
return CYAN_GLOW_COLOR.withAlpha(alpha);
return baseColor.withAlpha(alpha);
}, false);
}
function createRobotEntity(viewer, robot, index) {
const raw = robot?.lastRunningStatus || {};
const parsed = parseLngLat(raw.longitude, raw.latitude);
@@ -1040,7 +1261,12 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// 不再用可能滞后的 devices 判断(避免用上一场站的机器决策);
// 若场站有机器,由 devices 效果按更高优先级接管飞向机器
useEffect(() => {
if (!mapLayer || !viewerRef.current) return;
const hasRealtime =
realtimePosition?.lon &&
realtimePosition?.lat &&
!isNaN(Number(realtimePosition.lon)) &&
!isNaN(Number(realtimePosition.lat));
if (!mapLayer || !viewerRef.current || hasRealtime) return;
resetFlightPriority();
flyToLayer(mapLayer, envConfig.geoserver_url, 100);
}, [mapLayer]);
@@ -1480,16 +1706,16 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// entity 获取 / 创建
// ==============================
// 光圈颜色:工作中蓝 / 空闲绿 / 离线红
const haloColor = getDeviceHaloColor(device);
let entity = entityMapRef.current.get(id);
if (!entity) {
entity = viewer.entities.add({
id,
position,
billboard: {
image,
width,
@@ -1497,43 +1723,93 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
show: !isIOT,
//rotation: headingRotation,
},
//point: {
// pixelSize: 12,
// color: createGlowBlinkColor("", "", "", window.Cesium.Color.BLACK), // 绑定到颜色
// outlineColor: Cesium.Color.WHITE,
// outlineWidth: 2
//},
label: {
text: device.name || "",
font: "12px sans-serif",
pixelOffset: new Cesium.Cartesian2(0, -40),
fillColor: Cesium?.Color.WHITE,
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium?.Color.BLACK.withAlpha(0.6)
backgroundColor: Cesium.Color.BLACK.withAlpha(0.6),
},
properties: {
robot: device
}
robot: device,
},
});
// ==============================
// 设备底部状态光晕:比机器稍大一点
// ==============================
const haloId = `${id}_halo`;
const haloColor = getDeviceHaloColor(device);
// 尺寸可根据设备类型微调:车辆类稍大,IOT/相机类稍小
let haloSize = 0.8;
if (isIOT) {
haloSize = device?.type === "camera" ? 0.8 : 0.8;
} else if (
device?.type === "plane" ||
device?.type === "drone" ||
device?.type === "drone-inspect"
) {
haloSize = 0.1;
} else {
haloSize = 0.8;
}
createDeviceHaloEntity(viewer, haloId, position, haloColor, 100);
entityMapRef.current.set(id, entity);
} else {
// ==============================
// 更新 entity
// ==============================
entity.position = position;
entity.billboard.image = image;
entity.billboard.width = width;
entity.billboard.height = height;
//entity.billboard.rotation = headingRotation;
entity.label.text = device.name || "";
entity.properties.robot = device;
// 同步更新底部光晕位置与颜色
const haloId = `${id}_halo`;
const haloColor = getDeviceHaloColor(device);
if (isRealtimeMode) {
// 一机一光圈:实时模式下移除设备光圈,避免原位置残留
viewer.entities.removeById(haloId);
for (let hi = 0; hi < 3; hi++) {
viewer.entities.removeById(`${haloId}_${hi}`);
}
} else {
let haloSize = 40;
if (isIOT) {
haloSize = device?.type === "camera" ? 35 : 28;
} else if (
device?.type === "plane" ||
device?.type === "drone" ||
device?.type === "drone-inspect"
) {
haloSize = 42;
} else {
haloSize = 38;
}
ensureRealtimeHalo(viewer, position, haloColor, haloSize, haloId);
//ensureRealtimeHalo·entity(viewer, haloId, position, haloColor, haloSize);
//createDeviceHaloEntity(viewer, haloId, position, haloColor, haloSize);
}
}
});
@@ -1543,17 +1819,18 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// ==============================
entityMapRef.current.forEach((entity, id) => {
if (!nextIds.has(id)) {
viewer.entities.remove(entity);
entityMapRef.current.delete(id);
viewer.entities.removeById(`${id}_halo`);
for (let ri = 0; ri < 3; ri++) {
viewer.entities.removeById(`${id}_halo_${ri}`);
}
}
});
// ==============================
// 请求渲染
// ==============================
@@ -1645,6 +1922,18 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const lat = p1.lat + (p2.lat - p1.lat) * step;
const newPos = window.Cesium.Cartesian3.fromDegrees(lon, lat, 1);
targetEntity.position = newPos;
// 背景光圈跟随机器一起移动
const movingHaloId = `${targetEntity.id}_halo`;
const movingHalo = viewer.entities.getById(movingHaloId);
if (movingHalo) {
movingHalo.position = newPos;
for (let hi = 0; hi < 3; hi++) {
const mRing = viewer.entities.getById(`${movingHaloId}_${hi}`);
if (mRing) mRing.position = newPos;
}
}
const heading = Math.atan2(p2.lat - p1.lat, p2.lon - p1.lon);
targetEntity.orientation = window.Cesium.Transforms.headingPitchRollQuaternion(
newPos,
@@ -1820,16 +2109,41 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// 恢复所有设备显示
entityMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = true;
if (e.point) e.point.show = true;
if (e.label) e.label.show = true; // ✅ 恢复 label
});
entityMapRef.current.forEach((entity, id) => {
const haloId = `${id}_halo`;
const haloEntity = viewer.entities.getById(haloId);
if (haloEntity) {
haloEntity.show = true;
for (let i = 0; i < 3; i++) {
const ring = viewer.entities.getById(
`${haloId}_${i}`
);
if (ring) {
ring.show = true;
}
}
}
});
alarmMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = true;
if (e.point) e.point.show = true;
if (e.label) e.label.show = true; // ✅ 恢复 label
});
iotMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = true;
if (e.point) e.point.show = true;
if (e.label) e.label.show = true; // ✅ 恢复 label
});
removeRealtimeHalo(viewer);
viewer.scene.requestRender();
return;
}
@@ -1845,14 +2159,40 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// ====================================
// 解析实时坐标
// ====================================
entityMapRef.current.forEach((entity) => {
if (entity.billboard) entity.billboard.show = false;
entityMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = false;
if (e.point) e.point.show = false;
if (e.label) e.label.show = false; // ✅ 同时隐藏 label,避免残留
});
// 隐藏设备底部光晕
entityMapRef.current.forEach((entity, id) => {
const haloId = `${id}_halo`;
const haloEntity = viewer.entities.getById(haloId);
if (haloEntity) {
haloEntity.show = false;
for (let i = 0; i < 3; i++) {
const ring = viewer.entities.getById(
`${haloId}_${i}`
);
if (ring) {
ring.show = false;
}
}
}
});
alarmMapRef.current.forEach((entity) => {
if (entity.billboard) entity.billboard.show = false;
if (entity.point) entity.point.show = false;
if (entity.label) entity.label.show = false; // ✅ 隐藏 label
});
iotMapRef.current.forEach((entity) => {
if (entity.billboard) entity.billboard.show = false;
if (entity.point) entity.point.show = false;
if (entity.label) entity.label.show = false; // ✅ 隐藏 label
});
const lon = Number(realtimePosition.lon || finishPoint.lng);
@@ -1860,6 +2200,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 1);
// 实时光圈颜色:优先取设备状态色,缺省蓝色(工作)
const rtHaloColor = devices?.[0] ? getDeviceHaloColor(devices[0]) : Cesium.Color.fromCssColorString('#1677ff');
// ====================================
// 无人机模式:保持原来的逻辑
// ====================================
@@ -1880,7 +2223,8 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
if (shouldAdd && drawRealTime) {
realtimeLastPointRef.current = { lon, lat };
realtimeCartesianRef.current.push(
Cesium.Cartesian3.fromDegrees(lon, lat)
// ✅ 统一 1 米高度,和机器图标 z 值完全一致,放大后不再偏移
Cesium.Cartesian3.fromDegrees(lon, lat, 1)
);
}
@@ -1890,14 +2234,38 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
entityMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = false;
if (e.point) e.point.show = false;
if (e.point) e.point.show = false;
});
// 隐藏设备底部光晕
entityMapRef.current.forEach((entity, id) => {
const haloId = `${id}_halo`;
const haloEntity = viewer.entities.getById(haloId);
if (haloEntity) {
haloEntity.show = false;
for (let i = 0; i < 3; i++) {
const ring = viewer.entities.getById(
`${haloId}_${i}`
);
if (ring) {
ring.show = false;
}
}
}
});
alarmMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = false;
if (e.point) e.point.show = false;
if (e.point) e.point.show = false;
});
iotMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = false;
if (e.point) e.point.show = false;
if (e.point) e.point.show = false;
});
}
@@ -1939,6 +2307,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
realtimeCarEntityRef.current.billboard.width = imgWidth;
realtimeCarEntityRef.current.billboard.height = imgHeight;
realtimeCarEntityRef.current.billboard.rotation = rotation;
// 实时光圈跟随机器移动,原光随动不残留
ensureRealtimeHalo(viewer, position, rtHaloColor, 38);
}
// 无人机模式的实时轨迹线
@@ -1958,7 +2329,8 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
glowPower: 0.25,
color: Cesium?.Color.LIME
}),
clampToGround: true,
// ✅ 取消贴地,和机器图标保持 1 米同高度,放大后轨迹中心与机器中心完全重合
clampToGround: false,
disableDepthTestDistance: Number.POSITIVE_INFINITY
}
});
@@ -2016,14 +2388,37 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
entityMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = false;
if (e.point) e.point.show = false;
});
// 隐藏设备底部光晕
entityMapRef.current.forEach((entity, id) => {
const haloId = `${id}_halo`;
const haloEntity = viewer.entities.getById(haloId);
if (haloEntity) {
haloEntity.show = false;
for (let i = 0; i < 3; i++) {
const ring = viewer.entities.getById(
`${haloId}_${i}`
);
if (ring) {
ring.show = false;
}
}
}
});
alarmMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = false;
if (e.point) e.point.show = false;
});
iotMapRef.current.forEach(e => {
if (e.billboard) e.billboard.show = false;
if (e.point) e.point.show = false;
});
}
@@ -2059,6 +2454,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
realtimeCarEntityRef.current.billboard.width = imgWidth;
realtimeCarEntityRef.current.billboard.height = imgHeight;
realtimeCarEntityRef.current.billboard.rotation = rotation;
// 实时光圈跟随机器移动,原光随动不残留
ensureRealtimeHalo(viewer, position, rtHaloColor, 38);
}
// 机器人模式只在导航模式下显示额外的实时轨迹线

View File

@@ -60,6 +60,8 @@ export default function DroneManagement({
const [droneParams, setDroneParams] = useState({
pageNum: 1,
pageSize: 20,
orgId: userInfo?.orgId || '',
sn: '',
status: ''
});
@@ -139,7 +141,7 @@ export default function DroneManagement({
useEffect(() => {
fetchDroneList();
}, [droneParams]);
}, [droneParams, stationId]);
const openBindModal = async () => {
if (!selectedDroneKeys.length) {

View File

@@ -68,6 +68,7 @@ export default function SmartDeviceManagement({
const [smartParams, setSmartParams] = useState({
pageNum: 1,
pageSize: 20,
orgId: userInfo?.orgId || '',
serialNumber: '',
});
const [smartTotal, setSmartTotal] = useState(0);
@@ -156,7 +157,7 @@ export default function SmartDeviceManagement({
useEffect(() => {
fetchSmartList();
}, [smartParams]);
}, [smartParams, stationId]);
const openEditSmartModal = (record) => {
setCurrentEditSmart(record);

View File

@@ -1236,7 +1236,7 @@ export default function DeviceStatusPage() {
) : mowerView === 'front' ? (
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
{/*<AgrtcRoomRobot CHANNEL={device?.serialNumber || ''} />*/}
<AgrtcRoomRobot CHANNEL={"41-thermal"} />
<AgrtcRoomRobot CHANNEL={"41-thream02"} />
</div>
) : (