Compare commits

...

6 Commits

31 changed files with 3428 additions and 1108 deletions

View File

@@ -0,0 +1,45 @@
## 软著用户手册扩充(2026-11-16)
- 基于源文件 `C:/Users/15563/Desktop/软著/软著-机器人智慧服务系统/软著/用户操作手册-机器人智慧服务系统-完整版.docx` 扩充为 18 页软著格式手册
- 新文件(未改源文件):同目录 `用户操作手册-机器人智慧服务系统-完整版-扩充版V1.1.docx`
- 做法与要点:
- editor_sdk 的 doc 编辑/转图在中文路径下不可用("document is not open"、COS 上传找不到 python),改用 python-docx 生成 + Word COM 统计页数/导 PDF + PyMuPDF 渲染校验
- 格式:A4、页眉"机器人智慧服务系统 V1.0 用户操作手册"(带下框线)、页脚"第 X 页"(PAGE 域)、正文宋体小四 1.5 倍行距首行缩进 2 字符、标题黑体(H1 16pt/H2 14pt)、表格 Table Grid+蓝灰表头、图题表题五号居中
- 章节:原框架基础上重排为连续六章(一概述/二运行环境与登录/三装备总览/四任务规划/五告警中心/六日常建议与常见问题),修复原 3.1-3.7 编号断档、重复 4.7 等问题;不新增功能
- 保留并重排原 6 张截图(登录、装备总览、机器人任务、路径生成、返航点规划、告警中心),统一图号 图2-1~图5-1
- 通过缩小插图至 13.8cm 把 19 页调到精确 18 页
## 软著格式优化(2026-11-16 晚)
- 用户提供了经纬软著申报材料的两个模板:计算机软件著作权登记-源代码.doc、软件著作权产品说明书模版.doc(各1页,仅格式示例)
- 生成两个新文件(原文件未动):
- `软著/机器人智慧服务系统-产品说明书-格式优化版.docx`(15页):按说明书模板——页眉"机器人智慧服务系统 V1.0 + X/Y页码"、封面"软件名 V1.0 / 产品说明书"华文中宋16pt居中、正文华文中宋12pt固定20磅行距首行缩进2字符、结构=软件介绍(名称/版本/类别/著作权人)→软件特色→系统需求→安装和运行方法→软件功能(含6张截图);著作权人为占位符待用户填
- `软著/机器人智慧服务系统V1.0-源代码-格式优化版.docx`(94页):按源代码模板——A4、左右2.0cm上下1.0cm边距、页眉"机器人智慧服务系统V1.0+页码"、正文沿用原7.5pt/12磅行距(5042行,约54行/页≥50行要求)、内容逐行不变
- 踩坑:docx 固定行距(exact 20pt)会把内嵌图片裁剪成细条 → 图片段落必须单独设单倍行距;.doc 转 .docx 用 Word COM(SaveAs 16)
- 模板规则提醒:源代码超60页时申报只需前30页+后30页(第30页断开),已在回复中告知用户
## 四页面用户使用手册(2026-11-16 夜)
- 完成此前中断的任务:为 devices/overview、devices/status、devices/robotTask、alerts/all 四个页面生成面向用户与营销的详细使用手册
- 产出:`D:/code/机器人智慧服务系统/机器人智慧服务系统-用户使用手册-核心页面详解V1.0.docx`(22页,7章,9张截图)
- 流程与要点:
- Explore 代理逐行核对源码输出功能报告(i18n 文案取自 src/locales/zh/index.ts;告警中心实际只挂载 AlarmOverview,其余 Alarm* 子组件未启用)
- 截图:npm run dev(3001)+ agent-browser(npm i -g agent-browser && agent-browser install)登录 admin/admin123(RuoYi 默认,见 2026-08-11 日志);`agent-browser set viewport 1920 1080` 提高清晰度;截图存 shots/manual/
- 踩坑:robotTask 页 Cesium 较重,守护进程会 EOF 超时,需重开浏览器重登录(登录态随会话丢失);截图务必用绝对路径(相对路径曾出现文件"消失"假象);页面 window 不滚动(内部容器滚动),整页 1920 一图即可覆盖
- 文档生成:python-docx(venv),页眉+PAGE 域页脚、宋体正文/黑体标题、Table Grid+蓝灰表头;脚本内中文文本的英文引号会破坏 Python 字符串,用"两侧CJK/一侧CJK一侧英数"规则批量替换为中文引号
- 校验:Word COM 转 PDF(22页)+ PyMuPDF 渲染抽查
## 产品说明书丰富版(2026-11-16 深夜)
- 用户要求在《机器人智慧服务系统-产品说明书-格式优化版.docx》基础上补充 7 类内容:软件结构图/功能流程图/逻辑框图/总体设计/接口设计/模块名称功能/函数名称功能,重新生成
- 产出:`软著/机器人智慧服务系统-产品说明书-丰富版V1.1.docx`(23页,原格式优化版未动)
- 做法要点:
- 复用 build_manual_v2.py 生成脚本,改输出名 + 图号顺延(替换顺序必须从大到小:5-1→6-1、4-x→5-x、3-1→4-1)+ 在"安装和运行方法"与"软件功能"之间插入 H1"软件设计说明"章节(7 个 H2 小节)
- 三张设计图用 matplotlib(Agg)+ 微软雅黑字体(C:/Windows/Fonts/msyh.ttc,FontProperties fname 方式避免注册字体)绘制:结构图=五层分层框图;流程图=纵向主干+正常/异常菱形分支;逻辑框图=四页面→通信服务层→支撑组件→设备网关
- 接口表:从 src/api/*.ts|js grep url+method 逐条核对请求方式(GET/POST),勿凭猜测
- 模块表/函数表:从路由 routes.tsx 与组件/控制器源码提取真实名称(useMqtt、wsManager、emergencyStopControl 系列等)
- 校验:Word COM 统计 23 页 + PyMuPDF 渲染抽查 + 正则提取全部"图 x-y"标题确认编号连续
- 踩坑:matplotlib 未装需 pip 到 venv;流程图第一版布局重叠(泳道+斜线连接太乱),改纵向主干+分支后清晰
## 丰富版图示修改(2026-11-16 深夜 2)
- 按用户要求修改三张设计图:结构图去无人机(设备层=割草/清洁机器人)、流程图去工单分支(异常分支改为 产生告警→查看→处置/归档→闭环归档)、逻辑框图去机器人控制页面与无人机(三页面+四支撑组件)
- 同步改章节文字:流程图段落"转工单闭环"→"处置后归档,形成处理闭环";逻辑框图"四个业务页面"→"装备总览、任务规划、告警中心三个业务页面";设备层 bullet 去无人机
- 接口表/模块表/函数表中的工单条目保留(软件实际有该功能,用户只要求改图)
- 注意:丰富版V1.1.docx 被用户打开占用导致 PermissionError,改存 `丰富版V1.2.docx`(23页)

View File

@@ -0,0 +1,10 @@
# 2026-11-17
## 软著登记申请表填写(2026-11-17)
- 用户要求根据产品说明书V1.2填写空白申请表模板(软著/提交/软件著作权登记申请表-空白模板.doc),不动模板与说明书
- 关键信息来源:父目录《采集表-已完善.doc》——软件全称"机器人光伏运维智慧服务系统"、简称"机器人智慧服务系统"、V1.0、完成/发表日期 2026-11-06、源程序量 78700 行、开发环境、领域等;著作权人名称在采集表中也是空白
- 产出(提交目录):`软件著作权登记申请表-机器人光伏运维智慧服务系统V1.0.docx` + 同名 `.doc`(6页)
- 填写方式:.doc→.docx(Word COM SaveAs 16)→ python-docx 按嵌套表格路径 set_cell(保留原 run 格式但强制黑色、多段依次 addnext 保持顺序)→ Word COM 校验页数/导 .doc/导 PDF → PyMuPDF 渲染抽查
- 主要功能 933 字(500-1300 达标,按说明书 V1.2 口径写五大功能,含告警转工单;未突出无人机);技术特点 99 字、开发目的 93 字(均 ≤100)
- 未填待用户补:著作权人(姓名/类别/证件号/省份)、分类号、首次发表地点、联系人信息(申请方式默认⊙由代理人申请,代理人为南京经纬 谭安琪,模板自带)
- 踩坑:①python-docx 多段落用 p0.addnext 逐个插入会逆序,须用 anchor 逐段后移;②set_cell 继承占位符红色字体,提交前须把 w:color 改 000000;③模板 doc 打开时有 ~$ 锁文件,操作临时副本即可

View File

@@ -540,6 +540,17 @@ export function modeChage(params) {
})
}
///iot/host/eStopChange
export function eStopChange(params) {
return request({
url: '/iot/host/eStopChange',
method: 'get',
params,
})
}

View File

@@ -1,281 +1,346 @@
import React, { useEffect, useRef, useState } from "react";
import AgoraRTC, { IAgoraRTCClient, IRemoteVideoTrack } from "agora-rtc-sdk-ng";
import { Badge, message } from "antd";
import React, { useEffect, useMemo, 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日志
// 日志等级:2=仅 warning/error,屏蔽 debug 噪点
AgoraRTC.setLogLevel(2);
const APP_ID = "7887b4db6033410d9ac3264b40ca9c1a";
const TOKEN = "007eJxTYPh6QSj59sUzD3mPNm64dK9n/n1PP64UzrhzdwUeqMUKv1BVYDC3sDBPMklJMjMwNjYxNEixTEw2NjIzSTIxSE60TDZMlOdYldUQyMiQXKbEwAiFID43g4mhbklGUWpiroExAwMAjGAhHQ==";
const APP_ID = '5afc6f096ddf433aa690df6f251274a4';
const TOKEN =
'007eJxTYHj/XqzNYP1utbUqvUkLly0/ypRz8liNgdKBqBeqqzX3+WgqMJgmpiWbpRlYmqWkpJkYGycmmlkapKSZpRmZGhqZmySaRH37ndUQyMjgu3k5KyMDBIL47AzJiblGuobmDAwA6vwg4g==';
export default function AgrtcRoomRobot({ CHANNEL }: { CHANNEL: string }) {
const [uid] = useState(() => Number(Math.floor(Math.random() * 100000)));
/**
* 每路摄像头在 Agora 频道内用固定 UID 区分:
* 101 = cam0 (GMSL A) = 前视
* 102 = cam1 (GMSL B) = 左视
* 103 = cam2 (GMSL C) = 后视
* 104 = cam3 (GMSL D) = 右视
*/
/** 按摄像头路数选默认 UID:2 路时优先前+后 */
export const DEFAULT_UIDS_BY_COUNT: Record<number, number[]> = {
1: [101],
2: [101, 103],
3: [101, 102, 103],
4: [101, 102, 103, 104],
};
export const DEFAULT_CAMERA_UIDS = [101, 102, 103, 104];
export const CAMERA_UID_LABEL: Record<number, string> = {
101: '前视',
102: '左视',
103: '后视',
104: '右视',
};
interface AgrtcRoomRobotProps {
/** 机器人 SN → 一个 Agora 频道 */
channel?: string;
/** 向后兼容:channel 的别名 */
CHANNEL?: string;
/** 当前机器人有几路摄像头(从 deviceRunParamSelectByDeviceId 的 cameraNum 字段取),1-4 */
cameraCount?: number;
/**
* 显式指定本次只订阅哪些 UID(单路视图模式:front/back/left/right 各传一个 UID;all/grid 不传则按 cameraCount 取前 N 个默认 UID)
* 留空时取 DEFAULT_CAMERA_UIDS.slice(0, cameraCount)
*/
slotUids?: number[];
}
interface SlotRuntime {
uid: number;
containerRef: React.RefObject<HTMLDivElement>;
track: IRemoteVideoTrack | null;
subscribedUid: number | null;
hasVideo: boolean;
unpublishTimer: NodeJS.Timeout | null;
}
export default function AgrtcRoomRobot(props: AgrtcRoomRobotProps) {
const channel = "cam2-17" || props.channel || props.CHANNEL || '';
const cameraCount = Math.max(1, Math.min(4, Number(props.cameraCount) || 1));
// 订阅 UID 列表:外部显式 slotUids > 默认按 cameraCount 截断
const slotUids = useMemo(() => {
if (Array.isArray(props.slotUids) && props.slotUids.length > 0) {
return props.slotUids.filter((n) => Number.isFinite(n) && n >= 1);
}
return DEFAULT_UIDS_BY_COUNT[cameraCount] || [101];
}, [props.slotUids, cameraCount]);
const [mountKey, setMountKey] = useState(0);
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",
codec: "h264",
});
clientRef.current = client;
client.setClientRole("audience");
// ========= 删掉了 setParameters,Web NG不支持!========
setMountKey((k) => k + 1);
}, [channel, slotUids.join(',')]);
let isUnmounted = false;
let videoWatchDogTimer: NodeJS.Timeout | null = null;
let unpublishTimer: NodeJS.Timeout | null = null;
if (!channel) {
return (
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#aaa', background: '#000', borderRadius: 8 }}>
无可订阅频道
</div>
);
}
const clearRemoteVideo = () => {
if (remoteVideoTrackRef.current) {
return (
<AgrtcSingleChannel
key={mountKey}
channel={channel}
slotUids={slotUids}
onConnect={setConnected}
onJoin={setJoined}
>
{(renderProps) => {
const gridStyle = pickGridStyle(slotUids.length);
return (
<div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', borderRadius: 8, overflow: 'hidden', background: '#000' }}>
<div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 12, padding: '4px 8px', background: 'rgba(255,255,255,0.08)', flexShrink: 0, flexWrap: 'wrap' }}>
<Badge
color={connected ? 'green' : 'red'}
text={connected ? 'RTC已连接' : 'RTC未连接'}
style={{ content: { color: '#ffffff' } }}
className={'badge-rtc-connected'}
/>
<Badge
color={joined ? 'green' : 'orange'}
text={joined ? '已加入频道' : '未加入频道'}
styles={{ content: { color: '#ffffff' } }}
className={'badge-rtc-connected'}
/>
<span style={{ fontSize: 11, color: '#888' }}>共 {slotUids.length} 路</span>
</div>
<div style={{ flex: 1, width: '100%', minHeight: 0, position: 'relative', padding: 4 }}>
<div style={{ width: '100%', height: '100%', ...gridStyle }}>
{slotUids.map((uid) => {
const slot = renderProps.slotsByUid.get(uid);
const hasVideo = slot?.hasVideo || false;
const label = CAMERA_UID_LABEL[uid] || `UID ${uid}`;
return (
<div key={uid} style={{ position: 'relative', width: '100%', height: '100%', background: '#000', borderRadius: 6, overflow: 'hidden' }}>
<div style={{ position: 'absolute', top: 4, left: 6, zIndex: 3, fontSize: 11, color: '#fff', background: 'rgba(0,0,0,0.5)', padding: '2px 6px', borderRadius: 4, maxWidth: '80%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{label}
</div>
<div ref={slot?.containerRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', zIndex: 1 }} />
{!hasVideo && (
<div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#aaa', fontSize: 12, background: '#000', zIndex: 2 }}>
等待推流 (UID {uid})…
</div>
)}
</div>
);
})}
</div>
</div>
</div>
);
}}
</AgrtcSingleChannel>
);
}
function pickGridStyle(count: number): React.CSSProperties {
if (count <= 1) return { display: 'grid', gridTemplateColumns: '1fr', gridTemplateRows: '1fr', gap: 4 };
if (count === 2) return { display: 'grid', gridTemplateColumns: '1fr', gridTemplateRows: '1fr 1fr', gap: 4 };
return { display: 'grid', gridTemplateColumns: '1fr 1fr', gridTemplateRows: '1fr 1fr', gap: 4 };
}
interface AgrtcSingleChannelProps {
channel: string;
slotUids: number[];
onConnect: (c: boolean) => void;
onJoin: (j: boolean) => void;
children: (renderProps: { slotsByUid: Map<number, SlotRuntime> }) => React.ReactNode;
}
function AgrtcSingleChannel({ channel, slotUids, onConnect, onJoin, children }: AgrtcSingleChannelProps) {
// 用 Map 做按 UID 索引的 slot,避免 React 重建循环引用
const slotsRef = useRef<Map<number, SlotRuntime>>(new Map());
const [, forceTick] = useState(0);
useEffect(() => {
const slotsByUid = new Map<number, SlotRuntime>();
const containerKeyByUid = new Map<number, React.RefObject<HTMLDivElement>>();
for (const uid of slotUids) {
containerKeyByUid.set(uid, React.createRef<HTMLDivElement>());
slotsByUid.set(uid, {
uid,
containerRef: containerKeyByUid.get(uid)!,
track: null,
subscribedUid: null,
hasVideo: false,
unpublishTimer: null,
});
}
slotsRef.current = slotsByUid;
forceTick((v) => v + 1);
const client: IAgoraRTCClient = AgoraRTC.createClient({ mode: 'live', codec: 'h264' });
console.log('[AGRTC] init channel=' + channel + ', slotUids=' + JSON.stringify(slotUids));
client.setClientRole('audience');
const localUid = Number(Math.floor(Math.random() * 100000) + 1);
let unmounted = false;
const clearSlotTrack = (uid: number) => {
const slot = slotsRef.current.get(uid);
if (!slot) return;
if (slot.track) {
try {
remoteVideoTrackRef.current.stop();
} catch (e) {
console.warn("stop track error", e);
}
remoteVideoTrackRef.current = null;
slot.track.stop();
} catch { }
slot.track = null;
}
subscribedUidRef.current = null;
setHasRemoteVideo(false);
if (videoWatchDogTimer) clearInterval(videoWatchDogTimer);
slot.subscribedUid = null;
slot.hasVideo = false;
if (slot.unpublishTimer) {
clearTimeout(slot.unpublishTimer);
slot.unpublishTimer = null;
}
forceTick((v) => v + 1);
};
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;
const playIntoSlot = async (uid: number, track: IRemoteVideoTrack) => {
const slot = slotsRef.current.get(uid);
if (!slot || !slot.containerRef.current) return;
try {
await track.play(dom);
console.log("远端视频播放成功");
setHasRemoteVideo(true);
startVideoWatchDog();
await track.play(slot.containerRef.current);
slot.track = track;
slot.hasVideo = true;
forceTick((v) => v + 1);
} catch (err: any) {
if (err.name === "AbortError") {
console.warn("播放请求被中断 AbortError,忽略", err);
return;
}
console.error("视频播放失败", err);
message.error("视频播放失败");
if (err?.name === 'AbortError') return;
console.error('[AGRTC] play failed', channel, uid, err);
}
};
const doReconnect = async () => {
if (isUnmounted || joiningRef.current) return;
console.log("执行RTC重连(信令断开)");
clearRemoteVideo();
setJoined(false);
const onUserPublished = async (user: any, mediaType: 'video' | 'audio') => {
if (unmounted || mediaType !== 'video') return;
const uid = Number(user.uid);
if (!slotUids.includes(uid)) return; // 只关心我们订阅的摄像头 UID
const slot = slotsRef.current.get(uid);
if (!slot || slot.subscribedUid === user.uid) return;
if (slot.unpublishTimer) {
clearTimeout(slot.unpublishTimer);
slot.unpublishTimer = null;
}
try {
joiningRef.current = true;
await client.join(APP_ID, CHANNEL, TOKEN, uid);
if (isUnmounted) return;
setJoined(true);
message.info("RTC重连成功");
for (const remoteUser of client.remoteUsers) {
if (isUnmounted) break;
if (remoteUser.hasVideo && subscribedUidRef.current !== remoteUser.uid) {
await client.subscribe(remoteUser, "video");
remoteVideoTrackRef.current = remoteUser.videoTrack;
subscribedUidRef.current = remoteUser.uid;
await playRemoteTrack(remoteUser.videoTrack!);
}
await client.subscribe(user, 'video');
slot.subscribedUid = user.uid;
if (user.videoTrack) {
await playIntoSlot(uid, user.videoTrack);
}
} catch (err: any) {
if (err?.code !== "OPERATION_ABORTED") {
console.error("重连失败", err);
}
} finally {
joiningRef.current = false;
} catch (e) {
console.error('[AGRTC] subscribe failed', channel, uid, e);
}
};
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);
reconnectTimerRef.current = setTimeout(() => {
doReconnect();
}, 2000);
}
};
const onUserPublished = async (user: any, mediaType: "video" | "audio") => {
if (isUnmounted) return;
console.log("user-published", user.uid, mediaType);
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, subscribedUidRef.current);
if (mediaType === "video" && subscribedUidRef.current === user.uid) {
if (unpublishTimer) clearTimeout(unpublishTimer);
// 延迟2s清空,短闪断自动恢复不黑屏
unpublishTimer = setTimeout(() => {
clearRemoteVideo();
}, 2000);
}
const onUserUnpublished = (user: any, mediaType: 'video' | 'audio') => {
if (unmounted || mediaType !== 'video') return;
const uid = Number(user.uid);
if (!slotUids.includes(uid)) return;
const slot = slotsRef.current.get(uid);
if (!slot || slot.subscribedUid !== user.uid) return;
if (slot.unpublishTimer) clearTimeout(slot.unpublishTimer);
slot.unpublishTimer = setTimeout(() => clearSlotTrack(uid), 2000);
};
const onUserLeft = (user: any) => {
if (isUnmounted) return;
console.log("user-left", user.uid);
if (subscribedUidRef.current === user.uid) {
if (unpublishTimer) clearTimeout(unpublishTimer);
clearRemoteVideo();
if (unmounted) return;
const uid = Number(user.uid);
if (!slotUids.includes(uid)) return;
const slot = slotsRef.current.get(uid);
if (!slot || slot.subscribedUid !== user.uid) return;
clearSlotTrack(uid);
};
const onConnStateChange = (cur: string, prev: string) => {
if (unmounted) return;
onConnect(cur === 'CONNECTED');
if (cur === 'CONNECTED') onJoin(true);
else if (cur === 'DISCONNECTED') {
onJoin(false);
// 断线时清空所有槽位,重连成功后 onUserPublished 会重新走一遍
for (const uid of slotUids) clearSlotTrack(uid);
}
};
const onUserJoined = (user: any) => {
if (!isUnmounted) console.log("远端用户进入频道:", user.uid);
};
client.on('connection-state-change', onConnStateChange);
client.on('user-published', onUserPublished);
client.on('user-unpublished', onUserUnpublished);
client.on('user-left', onUserLeft);
const onTokenWillExpire = () => {
console.warn("token即将过期,请更新token");
message.warning("Token即将过期,视频可能很快断开");
};
client.on("connection-state-change", onConnStateChange);
client.on("user-published", onUserPublished);
client.on("user-unpublished", onUserUnpublished);
client.on("user-left", onUserLeft);
client.on("user-joined", onUserJoined);
client.on("token-privilege-will-expire", onTokenWillExpire);
const init = async () => {
if (joiningRef.current) return;
joiningRef.current = true;
const doJoin = async () => {
try {
await client.join(APP_ID, CHANNEL, TOKEN, uid);
if (isUnmounted) {
console.log("组件已卸载,丢弃join结果");
return;
}
console.log("加入频道成功");
setJoined(true);
message.success("RTC已加入频道");
for (const remoteUser of client.remoteUsers) {
if (isUnmounted) break;
console.log("发现已有远端用户:", remoteUser.uid);
if (remoteUser.hasVideo && subscribedUidRef.current !== remoteUser.uid) {
await client.subscribe(remoteUser, "video");
remoteVideoTrackRef.current = remoteUser.videoTrack;
subscribedUidRef.current = remoteUser.uid;
await playRemoteTrack(remoteUser.videoTrack!);
}
console.log('[AGRTC] joining channel=' + channel + ', localUid=' + localUid + ', appId=' + APP_ID);
console.log('[AGRTC] joined ' + channel + ', remoteUsers=', (client.remoteUsers || []).map(u => u.uid));
await client.join(APP_ID, channel, TOKEN, localUid);
if (unmounted) return;
onJoin(true);
// 加入后立刻把已在频道内的远端摄像头扫一遍,避免错过 onUserPublished
for (const remote of client.remoteUsers) {
if (unmounted) break;
if (!remote.hasVideo) continue;
const uid = Number(remote.uid);
if (!slotUids.includes(uid)) continue;
const slot = slotsRef.current.get(uid);
if (!slot || slot.subscribedUid === remote.uid) continue;
try {
await client.subscribe(remote, 'video');
slot.subscribedUid = remote.uid;
if (remote.videoTrack) await playIntoSlot(uid, remote.videoTrack);
} catch { /* ignore */ }
}
} catch (err: any) {
if (err?.code === "OPERATION_ABORTED") {
console.log("join操作被取消,忽略");
return;
if (err?.code !== 'OPERATION_ABORTED') {
console.error('[AGRTC] join failed', channel, err);
message.error(`加入 ${channel} 失败`);
}
console.error("加入频道失败:", err);
if (!isUnmounted) {
message.error("加入频道失败,请检查appid/token/channel");
}
} finally {
joiningRef.current = false;
}
};
doJoin();
init();
// Watchdog:每 3s 检查每个 video 元素,readyState 未到 HAVE_CURRENT_DATA 时重新 .play()
const watchdog = setInterval(() => {
if (unmounted) return;
for (const [uid, slot] of slotsRef.current.entries()) {
if (!slot.track || !slot.containerRef.current) continue;
const videoEl = slot.containerRef.current.querySelector('video') as HTMLVideoElement | null;
if (!videoEl) continue;
if (videoEl.readyState < 2) {
try {
slot.track.play(slot.containerRef.current);
} catch (e) {
console.warn('[AGRTC] watchdog replay error', channel, uid, e);
}
}
}
}, 3000);
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;
c.off("connection-state-change", onConnStateChange);
c.off("user-published", onUserPublished);
c.off("user-unpublished", onUserUnpublished);
c.off("user-left", onUserLeft);
c.off("user-joined", onUserJoined);
c.off("token-privilege-will-expire", onTokenWillExpire);
c.leave();
clientRef.current = null;
unmounted = true;
clearInterval(watchdog);
for (const slot of slotsRef.current.values()) {
if (slot.unpublishTimer) clearTimeout(slot.unpublishTimer);
if (slot.track) {
try { slot.track.stop(); } catch { }
}
}
try {
client.off('connection-state-change');
client.off('user-published');
client.off('user-unpublished');
client.off('user-left');
client.leave();
} catch { }
slotsRef.current.clear();
onConnect(false);
onJoin(false);
};
}, [CHANNEL]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [channel, slotUids.join(',')]);
return (
<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"}
text={connected ? "RTC已连接" : "RTC未连接"}
styles={{ content: { color: '#888' } }}
/>
<Badge
color={joined ? "green" : "orange"}
text={joined ? "已加入频道" : "未加入频道"}
styles={{ content: { color: '#888' } }}
/>
<span style={{ fontSize: 11, color: "#888" }}>频道:{CHANNEL}</span>
</div>
<div style={{ flex: 1, width: "100%", minHeight: 0, position: "relative" }}>
{!hasRemoteVideo && (
<div style={{
position: "absolute",
inset: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
color: "#aaa",
fontSize: 14,
background: "#000",
zIndex: 2
}}>
视频加载中,等待远端推流...
</div>
)}
<div ref={remoteVideoRef} style={{
position: "absolute",
inset: 0,
width: "100%",
height: "100%",
zIndex: 1
}} />
</div>
</div >
);
return <>{children({ slotsByUid: slotsRef.current })}</>;
}

View File

@@ -172,6 +172,31 @@ export default function AppLayout() {
return () => clearInterval(timer);
}, [userInfo, timezone, dateFormat]);
// 当前账号没有默认首页(/ 或 /overview)权限时,自动跳转到第一个有权限的菜单页面
useEffect(() => {
if (!Array.isArray(menuList) || menuList.length === 0) return;
const pathname = location.pathname;
if (pathname !== '/' && pathname !== '/overview') return;
const leafPaths: string[] = [];
const collect = (items: any[]) => {
items.forEach(item => {
if (item.children && item.children.length > 0) {
collect(item.children);
} else if (typeof item.key === 'string' && item.key.startsWith('/') && !item.key.startsWith('/menu/')) {
leafPaths.push(item.key);
}
});
};
collect(menuList);
const hasHomePermission = leafPaths.includes('/') || leafPaths.includes('/overview');
const firstPath = leafPaths[0];
if (!hasHomePermission && firstPath && firstPath !== pathname) {
navigate(firstPath, { replace: true });
}
}, [menuList, location.pathname, navigate]);
useEffect(() => {
setTime(nowInTz(timezone, dateFormat));
}, [timezone, dateFormat]);

View File

@@ -79,10 +79,9 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const tiandituLayersRef = useRef(null);
const esriFallbackLayerRef = useRef(null);
const [baseMapType, setBaseMapType] = useState('satellite');
// 天地图不可用标记:瓦片连续加载失败后降级为 Esri 影像,并隐藏底图切换
// 天地图不可用标记:只要有一个瓦片加载成功即判定可用(不统计失败次数)
const [tiandituUnavailable, setTiandituUnavailable] = useState(false);
const tiandituUnavailableRef = useRef(false);
const tiandituErrorCountRef = useRef(0);
// 场站已配置的返航点 / 分区叠加显示
const stationId = useSelector((state) => state?.station?.stationId || state?.station?.currentStation?.id);
@@ -256,6 +255,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
);
const liveObstacleEntities = new Map();
const liveObstacleLastTsRef = useRef(0);
// ==============================
// 统一相机飞行调度器
@@ -322,26 +322,16 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
esriFallbackLayer.show = true;
esriFallbackLayerRef.current = esriFallbackLayer;
// 天地图瓦片加载失败累计超过阈值后判定不可用,后续只显示 Esri 影像
const handleTiandituError = () => {
if (tiandituUnavailableRef.current) return;
tiandituErrorCountRef.current += 1;
if (tiandituErrorCountRef.current >= 6) {
tiandituUnavailableRef.current = true;
setTiandituUnavailable(true);
}
// 天地图可用性检测:只要任意一个瓦片加载成功,即判定天地图可用(不判断失败次数)
const handleTiandituLoad = () => {
if (!tiandituUnavailableRef.current) return;
tiandituUnavailableRef.current = false;
setTiandituUnavailable(false);
viewerRef.current?.scene?.requestRender?.();
};
Object.values(tdtLayers).forEach((layer) => {
layer.imageryProvider?.errorEvent?.addEventListener(handleTiandituError);
layer.imageryProvider?.loadEvent?.addEventListener(handleTiandituLoad);
});
// 主动探测天地图服务可达性:请求 0 级瓦片,失败即判定不可用
const probeImg = new Image();
probeImg.onerror = () => {
tiandituUnavailableRef.current = true;
setTiandituUnavailable(true);
};
probeImg.src = `https://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX=0&TILEROW=0&TILECOL=0&tk=${TIANDITU_TK}`;
viewer.scene.globe.baseColor = Cesium.Color.BLACK;
viewer.scene.globe.depthTestAgainstTerrain = false;
viewer.scene.requestRenderMode = true; // 👈 加这个(只在需要时渲染)
@@ -363,7 +353,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
return () => {
if (lastFlightPromiseRef.current) viewer.camera.cancelFlight();
Object.values(tdtLayers).forEach((layer) => {
layer.imageryProvider?.errorEvent?.removeEventListener(handleTiandituError);
layer.imageryProvider?.loadEvent?.removeEventListener(handleTiandituLoad);
});
};
}, []);
@@ -396,39 +386,118 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}, [baseMapType, tiandituUnavailable]);
const computeDistanceScale = () => {
const viewer = viewerRef.current;
const MIN_SCALE = 0.35;
const MAX_SCALE = 2.5;
const REF_HEIGHT = 50; // 相机高度 50m 时 scale = 1(基准尺寸)
const h = viewer.camera.positionCartographic?.height ?? REF_HEIGHT;
let s = REF_HEIGHT / Math.max(h, 1); // 反比
if (s < MIN_SCALE) s = MIN_SCALE;
if (s > MAX_SCALE) s = MAX_SCALE;
return s;
};
function updateLiveObstacleBoxes(
message,
) {
const viewer = viewerRef.current;
//for (const [, entity] of liveObstacleEntities) {
// viewer.entities.remove(entity);
//}
//liveObstacleEntities.clear();
// 让 billboard / label 图标随相机高度(地图远近)动态缩放
// 经验映射:相机越高(地图越远)scale 越小,相机越低(地图越近)scale 越大
// 相机高度 20m → scale 1.5;50m → 1.0;200m → 0.5;上限/下限 clamp
if (!viewer || !Cesium) return;
console.log(message, "障碍物信息")
const payload = message;
const objects = Array.isArray(payload) ? payload : (payload?.objects ?? []);
const objects = Array.isArray(payload)
? payload
: Array.isArray(payload?.objects)
? payload.objects
: [];
console.log(objects, "障碍物信息")
// 全量替换:先把地图上所有 live-obstacle 实体按 id 前缀全部移除
// 不依赖 liveObstacleEntities Map(避免历史孤儿实体残留)
const toRemove = [];
viewer.entities.values.forEach((ent) => {
if (ent && ent.id && String(ent.id).startsWith('live-obstacle-')) {
toRemove.push(ent);
}
});
toRemove.forEach((ent) => viewer.entities.remove(ent));
liveObstacleEntities.clear();
if (objects.length === 0) return;
if (objects.length === 0) {
console.log("没有障碍物")
viewer.scene.requestRender();
return;
}
// 记录第一个有效障碍物的位置,用于视角跳转
let firstPos = null;
objects.forEach((obj, index) => {
console.log(obj, "障碍物信息1111")
const lat = Number(obj.latitude ?? obj.lat);
const lon = Number(obj.longitude ?? obj.lng ?? obj.lon);
const dis = obj?.distance;
// 根据类型设置默认尺寸和颜色
const type = (obj.class_name ?? obj.name ?? '').toLowerCase();
const isPerson = type.includes('person') || type.includes('行人') || type.includes('人');
const isVehicle = type.includes('car') || type.includes('车辆') || type.includes('车') || type.includes('truck');
const isFence = type.includes('fence') || type.includes('围挡') || type.includes('障碍');
// 优先按 class_id 判定类型;未提供时再 fallback 到 class_name 字符串
const CLASS_ID_MAP = {
0: 'bus',
1: 'car',
2: 'motorcycle',
3: 'person',
4: 'truck',
};
const classIdRaw = obj.class_id ?? obj.classId ?? obj.class;
const parsedClassId = Number(classIdRaw);
const kindByClassId = Number.isInteger(parsedClassId) && CLASS_ID_MAP[parsedClassId]
? CLASS_ID_MAP[parsedClassId]
: null;
const rawName = (obj.class_name ?? obj.name ?? '').toLowerCase();
const kindByName = rawName.includes('person') || rawName.includes('行人') || rawName.includes('人') ? 'person'
: rawName.includes('motorcycle') || rawName.includes('摩托车') || rawName.includes('电驴') ? 'motorcycle'
: rawName.includes('bus') || rawName.includes('公交') || rawName.includes('大巴') ? 'bus'
: rawName.includes('truck') || rawName.includes('货车') || rawName.includes('卡车') ? 'truck'
: rawName.includes('car') || rawName.includes('车辆') || rawName.includes('车') ? 'car'
: rawName.includes('fence') || rawName.includes('围挡') || rawName.includes('障碍') ? 'fence'
: 'unknown';
const sx = Number(obj.size_x ?? obj.sizeX ?? (isPerson ? 0.6 : isVehicle ? 1.8 : 1.2));
const sy = Number(obj.size_y ?? obj.sizeY ?? (isPerson ? 0.6 : isVehicle ? 4.2 : 1.2));
const sz = Number(obj.size_z ?? obj.sizeZ ?? (isPerson ? 1.7 : isVehicle ? 1.5 : 1.5));
const obstacleKind = kindByClassId || kindByName;
const isPerson = obstacleKind === 'person';
const isVehicle = ['car', 'truck', 'bus', 'motorcycle'].includes(obstacleKind);
const isFence = obstacleKind === 'fence';
// 尺寸兜底:过滤 NaN / 负数 / 0,避免 Cesium BoxOutlineGeometry 抛 DeveloperError
const safeSize = (val, fallback) => {
const n = Number(val);
return Number.isFinite(n) && n > 0 ? n : fallback;
};
// 不同类别的默认尺寸(长 x 宽 x 高,单位米)
const KIND_DEFAULT_SIZE = {
person: { sx: 0.6, sy: 0.6, sz: 1.7 },
motorcycle: { sx: 0.8, sy: 2.2, sz: 1.6 },
car: { sx: 1.8, sy: 4.5, sz: 1.5 },
truck: { sx: 2.5, sy: 7.0, sz: 3.0 },
bus: { sx: 2.6, sy: 10.0, sz: 3.2 },
fence: { sx: 1.2, sy: 1.2, sz: 1.5 },
unknown: { sx: 1.2, sy: 1.2, sz: 1.5 },
};
const defaults = KIND_DEFAULT_SIZE[obstacleKind] || KIND_DEFAULT_SIZE.unknown;
const sx = safeSize(obj.size_x ?? obj.sizeX, defaults.sx);
const sy = safeSize(obj.size_y ?? obj.sizeY, defaults.sy);
const sz = safeSize(obj.size_z ?? obj.sizeZ, defaults.sz);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;
const id = `live-obstacle-${obj.track_id ?? obj.id ?? index}`;
const id = `live-obstacle-${index}`;
const position = Cesium.Cartesian3.fromDegrees(lon, lat, sz / 2);
if (!firstPos) firstPos = { lon, lat };
@@ -438,21 +507,21 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(Number(obj.angle ?? obj.yaw ?? 0)), 0, 0)
);
// 设置视觉差异
let boxColor = Cesium.Color.RED;
let typeEmoji = '⚠️';
let iconImage = null; // 用于存储图标
if (isPerson) {
boxColor = Cesium.Color.YELLOW;
typeEmoji = '🚶';
iconImage = 'https://img.icons8.com/color/96/walking--v1.png'; // 行人图标
} else if (isVehicle) {
boxColor = Cesium.Color.CYAN;
typeEmoji = '🚗';
iconImage = 'https://img.icons8.com/color/96/car--v1.png'; // 车辆图标
}
const labelText = `${typeEmoji} ${obj.class_name ?? '障碍物'} #${obj.track_id ?? obj.id ?? index} (${sx.toFixed(1)}x${sy.toFixed(1)}m)`;
// 不同类别的颜色、图标和文字
const KIND_STYLE = {
person: { color: Cesium.Color.YELLOW, emoji: '🚶', label: '行人', icon: 'https://img.icons8.com/color/96/walking--v1.png', width: 24 },
motorcycle: { color: Cesium.Color.ORANGE, emoji: '🛵', label: '摩托车', icon: 'https://img.icons8.com/color/96/motorcycle--v1.png', width: 28 },
car: { color: Cesium.Color.CYAN, emoji: '🚗', label: '小车', icon: 'https://img.icons8.com/color/96/car--v1.png', width: 32 },
truck: { color: Cesium.Color.LIME, emoji: '🚚', label: '货车', icon: 'https://img.icons8.com/color/96/delivery-truck--v1.png', width: 36 },
bus: { color: Cesium.Color.VIOLET, emoji: '🚌', label: '公交', icon: 'https://img.icons8.com/color/96/bus--v1.png', width: 36 },
unknown: { color: Cesium.Color.RED, emoji: '⚠️', label: '障碍物', icon: null, width: 32 },
};
const style = KIND_STYLE[obstacleKind] || KIND_STYLE.unknown;
const boxColor = style.color;
const typeEmoji = style.emoji;
const iconImage = style.icon;
const labelText = `${typeEmoji} ${style.label} (${sx.toFixed(1)}x${sy.toFixed(1)}m) ${dis ? `\n距离: ${dis.toFixed(1)}m` : ''}`;
const billboardSize = style.width;
let entity = viewer.entities.getById(id);
@@ -462,30 +531,32 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
position,
orientation,
// 外部包围盒,显示物理占用空间
box: {
dimensions: new Cesium.Cartesian3(sx, sy, sz),
material: boxColor.withAlpha(0.2),
outline: true,
outlineColor: boxColor,
outlineWidth: 1,
},
//box: {
// dimensions: new Cesium.Cartesian3(sx, sy, sz),
// material: boxColor.withAlpha(0.2),
// outline: true,
// outlineColor: boxColor,
// outlineWidth: 1,
//},
// 内部图标,直观显示物体类型
billboard: iconImage ? {
image: iconImage,
width: isPerson ? 24 : 32,
height: isPerson ? 24 : 32,
width: billboardSize,
height: billboardSize,
heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scale: new Cesium.CallbackProperty(computeDistanceScale, false),
} : undefined,
label: {
text: labelText,
font: 'bold 14px sans-serif',
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: boxColor.withAlpha(0.85),
pixelOffset: new Cesium.Cartesian2(0, -40),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
//label: {
// text: labelText,
// font: 'bold 14px sans-serif',
// fillColor: Cesium.Color.WHITE,
// showBackground: true,
// backgroundColor: boxColor.withAlpha(0.85),
// pixelOffset: new Cesium.Cartesian2(0, -40),
// disableDepthTestDistance: Number.POSITIVE_INFINITY,
// //scale: new Cesium.CallbackProperty(computeDistanceScale, false),
//},
});
} else {
entity.position = position;
@@ -497,27 +568,29 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
if (entity.billboard && iconImage) {
entity.billboard.image = iconImage;
entity.billboard.scale = new Cesium.CallbackProperty(computeDistanceScale, false);
}
if (entity.label) {
entity.label.text = labelText;
entity.label.backgroundColor = boxColor.withAlpha(0.85);
entity.label.scale = new Cesium.CallbackProperty(computeDistanceScale, false);
}
}
liveObstacleEntities.set(id, entity);
});
// 自动跳转到第一个障碍物
if (firstPos) {
flyToView(viewer, 100, {
destination: Cesium.Cartesian3.fromDegrees(firstPos.lon, firstPos.lat, 60),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-40),
roll: 0
},
duration: 2.0
}, 'live-obstacle-jump');
}
//if (firstPos) {
// flyToView(viewer, 100, {
// destination: Cesium.Cartesian3.fromDegrees(firstPos.lon, firstPos.lat, 60),
// orientation: {
// heading: Cesium.Math.toRadians(0),
// pitch: Cesium.Math.toRadians(-40),
// roll: 0
// },
// duration: 2.0
// }, 'live-obstacle-jump');
//}
viewer.scene.requestRender();
}
@@ -567,10 +640,79 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// return () => clearTimeout(timer);
//}, [stationId]);
//useEffect(() => {
// const viewer = viewerRef.current;
// if (!viewer || !Cesium) return;
// let count = 0;
// const mockTimer = setInterval(() => {
// count++;
// let mockMsg;
// // 奇数次:模拟有障碍物
// if (count % 2 === 1) {
// mockMsg = {
// objects: [
// {
// track_id: "obs-v-001",
// latitude: 31.2989,
// longitude: 120.5853,
// size_x: 1.8,
// size_y: 4.2,
// size_z: 1.5,
// angle: 30,
// class_name: "车辆",
// distance: 15.5
// },
// {
// track_id: "obs-p-002",
// latitude: 31.2992,
// longitude: 120.5856,
// size_x: 0.6,
// size_y: 0.6,
// size_z: 1.7,
// angle: 0,
// class_name: "行人",
// distance: 8.2
// },
// {
// track_id: "obs-t-003",
// latitude: 31.2987,
// longitude: 120.5850,
// size_x: 2.5,
// size_y: 7.0,
// size_z: 3.0,
// angle: 90,
// class_name: "货车",
// distance: 22.6
// }
// ]
// };
// console.log("模拟发送:有障碍物", mockMsg);
// } else {
// // 偶数次:模拟没有障碍物
// mockMsg = {
// objects: []
// };
// console.log("模拟发送:没有障碍物");
// }
// updateLiveObstacleBoxes(mockMsg);
// }, 3000); // 每隔3秒发送一次
// return () => {
// clearInterval(mockTimer);
// };
//}, [stationId]);
const handleDetectFn = (res) => {
if (!res) return;
liveObstacleLastTsRef.current = Date.now();
updateLiveObstacleBoxes(res);
};
@@ -648,7 +790,6 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
};
const clearDrawingPath = () => {
const viewer = viewerRef.current;
if (!viewer) return;
@@ -672,6 +813,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
// 特点:多层扩散动画光圈,独立一套 id
// ============================================================
function ensureRealtimeHalo(viewer, position, color, size = 100, haloId = 'realtime_car_halo') {
return;
const haloBaseId = haloId;
const RING_COUNT = 3;
const MIN_SIZE = 100;
@@ -724,6 +866,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
pixelOffset: new Cesium.Cartesian2(0, 0),
color: ringColor,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scale: new Cesium.CallbackProperty(computeDistanceScale, false),
heightReference: Cesium.HeightReference.NONE,
},
});
@@ -1223,6 +1366,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
function resolveDeviceStatus(device) {
const fsRaw = device?.color;
return fsRaw === 'red' ? 'offline' : fsRaw === 'green' ? 'working' : fsRaw === 'blue' ? 'idle' : 'idle';
////if (device?.onlineStatus == 0) return 'offline';
//if (stRaw !== undefined && stRaw !== null && stRaw !== '') {
@@ -1312,6 +1456,42 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
offline: { text: t('devices.offline'), color: DEVICE_STATUS_COLORS.offline }
};
const status = statusMap[stateKey] || statusMap.idle;
// 控制模式 / 系统模式 / 定位状态 文案映射(与任务规划页保持一致)
const controlModeMap = {
'0': t('devices.controlOff'),
'1': t('devices.localCpntrol'),
'2': t('devices.autoTask'),
'3': t('devices.remoteControl')
};
const systemModeMap = {
'2': t('devices.autoTask'),
'3': t('devices.remoteControl')
};
const fixStatusMap = {
no_fix: t('devices.noFix'),
single: t('devices.single'),
dgnss: t('devices.dgnss'),
ins: t('devices.ins'),
rtk_fixed: t('devices.rtkFixed'),
rtk_float: t('devices.rtkFloat'),
single_no_heading: t('devices.singleNoHeading'),
dgnss_no_heading: t('devices.dgnssNoHeading'),
rtk_fixed_no_heading: t('devices.rtkFixedNoHeading'),
rtk_float_no_heading: t('devices.rtkFloatNoHeading')
};
// 以下状态行仅在设备携带对应字段时展示,普通标记点的悬浮提示不受影响
const hasWorkStatus = robot.color !== undefined || robot.status !== undefined || robot.feStatus !== undefined;
const controlModeText = robot.controlMode !== undefined && robot.controlMode !== null && robot.controlMode !== ''
? (controlModeMap[String(robot.controlMode)] || '-')
: '';
const systemModeText = robot.sm !== undefined && robot.sm !== null && robot.sm !== ''
? (systemModeMap[String(robot.sm)] || '-')
: '';
const fixStatusText = robot.fix_status ? (fixStatusMap[robot.fix_status] || String(robot.fix_status)) : '';
const batteryRaw = robot.battery !== undefined && robot.battery !== null
? robot.battery
: (robot.batteryLevel !== undefined ? robot.batteryLevel : undefined);
const batteryText = batteryRaw !== undefined && batteryRaw !== null && batteryRaw !== '' ? Number(batteryRaw) + '%' : '';
let deviceValuesHTML = '';
if (robot.devicevalue && robot.devicevalue.length > 0) {
deviceValuesHTML = robot.devicevalue.map((device) => `
@@ -1335,13 +1515,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
</span>
` : ''}</div >
${deviceValuesHTML ? `<div style="margin-top:8px;"><strong>${t('devices.deviceData')}:</strong>${deviceValuesHTML}</div>` : ''}
${hasWorkStatus ? `<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>` : ''}
${controlModeText ? `<div>${t('devices.controlMode')}${controlModeText}</div>` : ''}
${systemModeText ? `<div>${t('devices.systemMode')}:${systemModeText}</div>` : ''}
${batteryText ? `<div>${t('devices.rtBattery')}:${batteryText}</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 >
@@ -3033,6 +3213,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const haloId = `${id}_halo`;
const haloColor = getDeviceHaloColor(device);
if (isRealtimeMode) {
// 一机一光圈:实时模式下移除设备光圈,避免原位置残留
viewer.entities.removeById(haloId);
@@ -3311,11 +3492,17 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const _allowedFrom = ["mapEditor"];
if (!_allowedFrom.includes(from))
return;
const cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
// 优先拾取椭球面;失败时回退到地形拾取,避免视角偏远/贴地平线时打点无效
let cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
if (!cartesian) {
const ray = viewer.camera.getPickRay(movement.position);
if (ray) cartesian = viewer.scene.globe.pick(ray, viewer.scene);
}
if (!cartesian) return;
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const lon = Cesium.Math.toDegrees(cartographic.longitude);
const lat = Cesium.Math.toDegrees(cartographic.latitude);
if (!Number.isFinite(lon) || !Number.isFinite(lat)) return;
onMarkPointRef.current?.({ lon, lat });
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
@@ -3326,7 +3513,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
return () => {
handler.destroy();
};
}, [drawPoints, from, devices]);
}, [from]);
//useEffect(() => {
// const viewer = viewerRef.current;
@@ -3378,6 +3565,18 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
realtimePosition.lat &&
!isNaN(Number(realtimePosition.lon)) &&
!isNaN(Number(realtimePosition.lat));
const rtHaloColor = realtimePosition?.status == "online" ? Cesium.Color.fromCssColorString('#19cd08') : Cesium.Color.fromCssColorString('#ef340b');
// =============================
// 判断是否需要飞行
// =============================
const needFlight = hasRealtime && !hasFlownRef.current && !realtimeHiddenRef.current;
// =============================
// 判断是否需要隐藏
// =============================
// ====================================
// 情况1:没有实时数据 -> 清理所有 realtime
@@ -3515,7 +3714,6 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 1);
// 实时光圈颜色:优先取设备状态色,缺省蓝色(工作)
const rtHaloColor = Cesium.Color.fromCssColorString('#19cd08');
// ====================================
// 无人机模式:保持原来的逻辑
@@ -3786,7 +3984,7 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
realtimeCarEntityRef.current.billboard.rotation = rotation;
// 实时光圈跟随机器移动,原光随动不残留
ensureRealtimeHalo(viewer, position, rtHaloColor, 38);
//ensureRealtimeHalo(viewer, position, rtHaloColor, 38);
}
// 机器人模式只在导航模式下显示额外的实时轨迹线
@@ -3891,6 +4089,28 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
handleDetectFn(detectReportInfo)
}, [detectReportInfo])
// // 超时兜底:2s 没收到新的障碍物消息,自动清掉(防止上游停推时残留)
useEffect(() => {
const TIMEOUT = 2000;
const timer = setInterval(() => {
const now = Date.now();
if (liveObstacleLastTsRef.current > 0 && now - liveObstacleLastTsRef.current > TIMEOUT) {
const v = viewerRef.current;
if (!v || !v.scene) return;
// 按 id 前缀扫掉所有 live-obstacle 实体(不依赖 Map 记录)
const toRemove = [];
v.entities.values.forEach((ent) => {
if (ent && ent.id && String(ent.id).startsWith('live-obstacle-')) toRemove.push(ent);
});
toRemove.forEach((ent) => v.entities.remove(ent));
liveObstacleEntities.clear();
liveObstacleLastTsRef.current = 0;
v.scene.requestRender();
}
}, 500);
return () => clearInterval(timer);
}, []);
// 暴露 ref 方法
useImperativeHandle(ref, () => ({
captureScreenshot,
@@ -3973,112 +4193,110 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
</div>
)}
{/* 图例:返航点 / 分区 */}
{(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0 || stationOverlay.tempObstaclePoints.length > 0) && (
<div
<div
style={{
position: "absolute",
right: 12,
top: 12,
zIndex: 20,
background: "rgba(255,255,255,0.92)",
borderRadius: 6,
padding: "8px 10px",
fontSize: 12,
color: "#333",
lineHeight: "18px",
boxShadow: "0 2px 8px rgba(0,0,0,0.12)",
}}
>
<div style={{ fontWeight: 600, marginBottom: 6 }}>{t('devices.mapEditor.legend')}</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "returnPoint" ? 600 : 400,
color: legendHighlight === "returnPoint" ? "#165DFF" : "#333",
background: legendHighlight === "returnPoint" ? "#e8f3ff" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 10,
height: 10,
background: "#165DFF",
borderRadius: "50% 50% 50% 0",
transform: "rotate(-45deg)",
}} />
<span>{t('devices.mapEditor.returnPoint')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "region" ? 600 : 400,
color: legendHighlight === "region" ? "#13C2C2" : "#333",
background: legendHighlight === "region" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 12,
height: 10,
border: "1px solid #13C2C2",
background: "rgba(19,194,194,0.18)",
}} />
<span>{t('devices.mapEditor.restArea')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "obstaclePoint" ? 600 : 400,
color: legendHighlight === "obstaclePoint" ? "#13C2C2" : "#333",
background: legendHighlight === "obstaclePoint" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span
style={{
display: 'inline-block',
width: 12,
height: 12,
border: '2px solid #F5222D',
borderRadius: '50%',
background: 'rgba(245,34,45,0.18)',
boxSizing: 'border-box',
}}
/>
<span>{t('devices.mapEditor.obstacle')}</span>
</div>
<button
onClick={handleFlyToDevice}
style={{
position: "absolute",
right: 12,
top: 12,
zIndex: 20,
background: "rgba(255,255,255,0.92)",
borderRadius: 6,
padding: "8px 10px",
fontSize: 12,
color: "#333",
lineHeight: "18px",
boxShadow: "0 2px 8px rgba(0,0,0,0.12)",
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
padding: '4px 8px',
color: '#fff',
fontSize: '14px',
fontWeight: 500,
background: 'linear-gradient(135deg, #409eff 0%, #1677ff 100%)',
border: 'none',
borderRadius: '8px',
boxShadow: '0 3px 10px rgba(22, 119, 255, 0.25)',
cursor: 'pointer',
transition: 'all 0.2s ease',
}}
>
<div style={{ fontWeight: 600, marginBottom: 6 }}>{t('devices.mapEditor.legend')}</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "returnPoint" ? 600 : 400,
color: legendHighlight === "returnPoint" ? "#165DFF" : "#333",
background: legendHighlight === "returnPoint" ? "#e8f3ff" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 10,
height: 10,
background: "#165DFF",
borderRadius: "50% 50% 50% 0",
transform: "rotate(-45deg)",
}} />
<span>{t('devices.mapEditor.returnPoint')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "region" ? 600 : 400,
color: legendHighlight === "region" ? "#13C2C2" : "#333",
background: legendHighlight === "region" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 12,
height: 10,
border: "1px solid #13C2C2",
background: "rgba(19,194,194,0.18)",
}} />
<span>{t('devices.mapEditor.restArea')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "obstaclePoint" ? 600 : 400,
color: legendHighlight === "obstaclePoint" ? "#13C2C2" : "#333",
background: legendHighlight === "obstaclePoint" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span
style={{
display: 'inline-block',
width: 12,
height: 12,
border: '2px solid #F5222D',
borderRadius: '50%',
background: 'rgba(245,34,45,0.18)',
boxSizing: 'border-box',
}}
/>
<span>{t('devices.mapEditor.obstacle')}</span>
</div>
<button
onClick={handleFlyToDevice}
style={{
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
padding: '4px 8px',
color: '#fff',
fontSize: '14px',
fontWeight: 500,
background: 'linear-gradient(135deg, #409eff 0%, #1677ff 100%)',
border: 'none',
borderRadius: '8px',
boxShadow: '0 3px 10px rgba(22, 119, 255, 0.25)',
cursor: 'pointer',
transition: 'all 0.2s ease',
}}
>
<span style={{ fontSize: '18px', lineHeight: 1 }}>⌖</span>
<span>{t('devices.mapEditor.location')}</span>
</button>
</div>
)}
<span style={{ fontSize: '18px', lineHeight: 1 }}>⌖</span>
<span>{t('devices.mapEditor.location')}</span>
</button>
</div>
</div>
);

View File

@@ -300,13 +300,13 @@ export default function AlarmCenterPage() {
{t('common.view')}
</Button>
<Button
{/*<Button
type="link"
icon={<EditOutlined />}
onClick={() => openEditModal(record)}
>
{t('common.modify')}
</Button>
</Button>*/}
</Space>
)
@@ -850,7 +850,7 @@ export default function AlarmCenterPage() {
{/* 根因分析 */}
{/* 推荐处理措施 */}
<Card size="small" title={t('alerts.recommendedAction')} style={{ marginBottom: 16 }}>
{/*<Card size="small" title={t('alerts.recommendedAction')} style={{ marginBottom: 16 }}>
<div style={{ color: '#333' }}>{currentAlarm.handleSuggestion || '-'}</div>
<div className="flex justify-between">
<div>
@@ -864,7 +864,7 @@ export default function AlarmCenterPage() {
</div>
</div>
</Card>
</Card>*/}
{/* 处理操作 */}
<Card size="small" title={t('alerts.handleOperation')} style={{ marginBottom: 16 }}>

View File

@@ -1,6 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { subscribeEmergencyStop } from './emergencyStopControl';
import {
ChevronUp,
ChevronDown,
@@ -60,6 +61,10 @@ const DPadControl: React.FC<DPadControlProps> = ({
const [pressed, setPressed] = useState<Record<string, boolean>>({});
const [speed, setSpeed] = useState(0.5);
// 急停锁存状态:与其他入口(手柄 / 功能按钮)共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
// 每个物理输入单独记录,避免同方向不同按键互相干扰
// 例如 ArrowUp 和 W 可以同时按下
@@ -69,7 +74,6 @@ const DPadControl: React.FC<DPadControlProps> = ({
const speedRef = useRef(0.5);
const pressTimer = useRef<number | null>(null);
const disabledRef = useRef(disabled);
const emergencyTimer = useRef<number | null>(null);
const onGamepadUpdateRef = useRef(onGamepadUpdate);
const onSpeedChangeRef = useRef(onSpeedChange);
@@ -204,29 +208,11 @@ const DPadControl: React.FC<DPadControlProps> = ({
stopTimer();
emit();
}, [stopTimer, emit]);
const startEmergency = useCallback(() => {
// 急停:切换锁存状态(第一次按下→发送 eStop=1,第二次按下→发送 eStop=0)
// 视觉由订阅到的共享锁存状态驱动,与手柄 / 其他入口保持一致
const toggleEmergency = useCallback(() => {
if (disabledRef.current) return;
pressedRef.current = {
...pressedRef.current,
center: true,
};
setPressed({ ...pressedRef.current });
onEmergencyStopRef.current?.();
if (emergencyTimer.current !== null) {
window.clearTimeout(emergencyTimer.current);
}
emergencyTimer.current = window.setTimeout(() => {
pressedRef.current = {
...pressedRef.current,
center: false,
};
setPressed({ ...pressedRef.current });
emergencyTimer.current = null;
}, 350);
}, []);
// 键盘控制:支持方向键 + WASD 组合
@@ -247,7 +233,7 @@ const DPadControl: React.FC<DPadControlProps> = ({
// 防止长按空格时重复触发急停
if (!e.repeat) {
startEmergency();
toggleEmergency();
}
return;
@@ -287,7 +273,7 @@ const DPadControl: React.FC<DPadControlProps> = ({
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur);
};
}, [startPress, endPress, releaseAll, startEmergency]);
}, [startPress, endPress, releaseAll, toggleEmergency]);
// 禁用时立即停止;卸载时清理定时器
useEffect(() => {
@@ -317,17 +303,17 @@ const DPadControl: React.FC<DPadControlProps> = ({
};
}, [disabled, stopTimer]);
// 紧急停止按钮的短暂按压动画
// 急停锁存相关清理
useEffect(() => {
return () => {
if (emergencyTimer.current !== null) {
window.clearTimeout(emergencyTimer.current);
}
stopTimer();
};
}, [stopTimer]);
//useEffect(() => {
// return () => {
// if (emergencyTimer.current !== null) {
// window.clearTimeout(emergencyTimer.current);
// }
// stopTimer();
// };
//}, [stopTimer]);
const btnBase =
'flex items-center justify-center w-8 h-8 rounded-xl border transition-all duration-150 select-none active:scale-95 touch-none';
@@ -390,14 +376,14 @@ const DPadControl: React.FC<DPadControlProps> = ({
type="button"
aria-label={t('devices.emergencyStop')}
disabled={disabled}
className={`${btnBase} relative ${pressed.center
className={`${btnBase} relative ${eStopActive
? 'border-red-500 bg-red-500/40 text-white shadow-[0_0_16px_rgba(239,68,68,0.6)]'
: 'border-red-500/70 bg-red-500/10 text-red-400 hover:bg-red-500/20'
} ${disabled
? 'opacity-40 cursor-not-allowed'
: 'cursor-pointer'
}`}
onClick={startEmergency}
onClick={toggleEmergency}
>
<ShieldAlert className="w-5 h-5" />
<span className="absolute -top-1 -right-1 px-1 bg-slate-900/80 text-[8px] text-red-400/80 rounded border border-red-500/30 pointer-events-none">

View File

@@ -0,0 +1,567 @@
/* 设备总览页样式(由 DeviceOverviewPage.tsx 内联样式外联而来) */
/* ===== 顶部统计卡片 ===== */
.device-overview-page {
background: #f5f7fa;
min-height: 100%;
}
.device-overview-title-wrap {
padding: 4px 0px 8px;
}
.device-overview-title.ant-typography {
margin: 0;
font-size: clamp(14px, 1.2vw, 18px);
}
.device-overview-content.ant-layout-content {
margin: 0 8;
}
.device-overview-top-row.ant-row {
margin-bottom: 8px;
flex-wrap: wrap;
}
.device-overview-top-col.ant-col {
min-width: 200px;
flex: 1 0 auto;
max-width: 260px;
}
.device-overview-top-icon-blue.anticon {
color: #165DFF;
font-size: 24px;
}
.device-overview-top-icon-cyan.anticon {
color: #13c2c2;
font-size: 24px;
}
.device-overview-top-icon-purple.anticon {
color: #722ED1;
font-size: 24px;
}
.device-overview-top-icon-pink.anticon {
color: #eb2f96;
font-size: 24px;
}
.device-overview-top-icon-indigo.anticon {
color: #2f54eb;
font-size: 24px;
}
.device-overview-stat-card.ant-card {
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
height: 101px;
}
.device-overview-stat-card .ant-card-body {
padding: 20px 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
}
.device-overview-stat-info {
flex: 1;
display: flex;
flex-direction: column;
align-items: flex-start;
}
.device-overview-stat-title {
font-size: 14px;
color: #86909C;
margin-bottom: 8px;
font-weight: 500;
}
.device-overview-stat-value {
font-size: 28px;
font-weight: 700;
line-height: 1;
margin-bottom: 8px;
color: var(--card-color);
}
.device-overview-stat-sub {
font-size: 12px;
color: #86909C;
font-weight: 500;
}
.device-overview-stat-icon {
width: 48px;
height: 48px;
border-radius: 50%;
background-color: var(--icon-bg);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
margin-left: 8px;
}
/* ===== 地图 / 设备列表卡片 ===== */
.device-overview-card.ant-card {
border-radius: 8px;
margin-bottom: 8px;
}
.device-overview-map-card .ant-card-body {
padding: 0;
}
.device-overview-control-card .ant-card-body {
padding: 12px;
padding-bottom: 0;
}
.device-overview-map-container {
width: 100%;
height: 350px;
border-radius: 8px;
position: relative;
overflow: hidden;
}
.device-overview-tag-flat.ant-tag {
margin: 0;
}
/* ===== 任务日志 / 告警记录面板 ===== */
.device-overview-panels-row.ant-row {
width: 100%;
}
.device-overview-panel-card.ant-card {
border-radius: 8px;
height: 100%;
}
.device-overview-text-13 {
font-size: 13px;
}
.device-overview-more {
text-align: center;
margin-top: 8px;
}
.device-overview-more-btn.ant-btn {
font-size: 13px;
color: #1890ff;
}
.device-overview-time-nowrap {
font-size: 12px;
white-space: nowrap;
}
.device-overview-text-12 {
font-size: 12px;
}
.device-overview-handled-tag.ant-tag {
font-size: 11px;
margin: 0;
}
.device-overview-handle-btn.ant-btn {
padding: 0;
font-size: 12px;
}
/* ===== 设备控制面板 ===== */
.device-overview-control-title-icon.anticon {
margin-right: 6px;
}
.device-overview-device-select.ant-select {
width: 80%;
margin-bottom: 8px;
}
.device-overview-block-12 {
margin-bottom: 12px;
}
.device-overview-device-head {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 12px;
flex-wrap: wrap;
}
.device-overview-device-type-icon {
font-size: 20px;
color: #1890ff;
}
.device-overview-device-name {
font-size: 14px;
font-weight: 600;
}
.device-overview-detail-btn.ant-btn {
border-radius: 4px;
font-size: 11px;
margin-left: auto;
}
.device-overview-stats-row {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
}
.device-overview-stat-cell {
display: flex;
align-items: center;
gap: 4px;
}
.device-overview-battery-icon {
color: #52c41a;
}
.device-overview-temp-cell {
display: flex;
align-items: center;
gap: 6px;
}
.device-overview-temp-value {
color: #faad14;
}
.device-overview-detail-list {
display: flex;
flex-direction: column;
gap: 6px;
margin-bottom: 12px;
max-height: 160px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #ccc transparent;
}
.device-overview-detail-row {
display: flex;
justify-content: space-between;
}
.device-overview-label-12 {
color: #666;
font-size: 12px;
}
.device-overview-detail-row-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 8px;
}
.device-overview-label-nowrap {
color: #666;
font-size: 12px;
white-space: nowrap;
}
.device-overview-sn-value {
font-size: 12px;
word-break: break-all;
white-space: normal;
text-align: right;
max-width: 70%;
}
.device-overview-rtk-badge.ant-badge {
background-color: #52c41a;
transform: scale(0.8);
}
.device-overview-action-row {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px;
}
.device-overview-action-btn.ant-btn {
border-radius: 8px;
flex: 1;
}
.device-overview-block-8 {
margin-bottom: 8px;
}
/* ===== 视频区域 ===== */
.device-overview-video-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.device-overview-video-title {
font-size: 14px;
font-weight: 500;
color: #666;
}
.device-overview-video-stop {
text-align: right;
}
.device-overview-video-source-select.ant-select {
width: 120px;
}
.device-overview-video-box {
width: 100%;
height: 160px;
border-radius: 8px;
position: relative;
overflow: hidden;
background: #000;
}
.device-overview-video-inner {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
background: #000;
border-radius: 8px;
}
.device-overview-video-loading {
color: #ccc;
display: flex;
height: 100%;
align-items: center;
justify-content: center;
}
.device-overview-play-overlay {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
background: #000;
}
.device-overview-play-btn {
width: 48px;
height: 48px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.25);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 22px;
}
.device-overview-manual-row {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
/* ===== 气象/执行条件卡片 ===== */
.device-overview-weather-card.ant-card {
border-radius: 12px;
margin-bottom: 8px;
}
.device-overview-weather-body {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: center;
}
.device-overview-weather-grid {
display: flex;
border: 1px solid #e8e8e8;
border-radius: 12px;
overflow: hidden;
flex: 1;
}
.device-overview-weather-cell {
flex: 1;
text-align: center;
white-space: nowrap;
padding: 12px 4px;
border-right: 1px solid #e8e8e8;
}
.device-overview-weather-cell-last {
flex: 1;
text-align: center;
white-space: nowrap;
padding: 12px 4px;
}
.device-overview-weather-cell-label {
font-size: 11px;
color: #666;
font-weight: 600;
}
.device-overview-weather-cell-value {
font-size: 14px;
font-weight: 700;
color: #222;
margin-top: 2px;
}
.device-overview-weather-cell-value-good {
font-size: 14px;
font-weight: 700;
color: #52c41a;
margin-top: 2px;
}
.device-overview-weather-good {
width: 110px;
padding: 12px 4px;
border-radius: 8px;
background: #f6ffed;
border: 1px solid #b7eb8f;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
}
.device-overview-weather-good-title {
font-size: 12px;
font-weight: 700;
color: #52c41a;
}
.device-overview-weather-good-icon {
width: 18px;
height: 18px;
border-radius: 50%;
background: #52c41a;
display: flex;
align-items: center;
justify-content: center;
}
.device-overview-weather-good-icon-mark.anticon {
font-size: 12px;
color: #fff;
}
.device-overview-weather-good-sub {
font-size: 11px;
color: #666;
}
/* ===== 机器人状态统计 ===== */
.device-overview-robot-card.ant-card {
border-radius: 12px;
margin-bottom: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
border: 1px solid #f0f0f0;
}
.device-overview-robot-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 600;
}
.device-overview-robot-title-icon.anticon {
color: #165DFF;
}
.device-overview-robot-stats.ant-row {
align-items: center;
}
.device-overview-robot-stat {
padding: 12px 16px;
border-radius: 10px;
background: #F7F8FA;
text-align: center;
border: 1px solid transparent;
transition: all 0.2s;
}
.device-overview-robot-stat-title {
font-size: 11px;
color: #666666;
font-weight: 400;
}
.device-overview-robot-statistic.ant-statistic .ant-statistic-content {
font-size: 20px;
font-weight: 700;
color: #165DFF;
margin-top: 4px;
}
/* ===== 任务执行时间 ===== */
.device-overview-schedule-card.ant-card {
border-radius: 12px;
}
.device-overview-schedule-extra {
font-size: 12px;
color: #666;
}
.device-overview-timeline-label {
font-size: 11px;
color: #999;
}
.device-overview-empty.ant-empty {
margin-top: 100px;
}
.device-overview-more-12 {
text-align: center;
margin-top: 12px;
}
/* ===== 编辑机器人设备信息弹窗 ===== */
.device-overview-edit-body {
padding: 8px 0;
}
.device-overview-edit-row {
margin-bottom: 16px;
}
.device-overview-required-mark {
color: red;
}
.device-overview-edit-hint {
margin-top: 8px;
font-size: 12px;
color: #999;
}

File diff suppressed because it is too large Load Diff

View File

@@ -21,6 +21,7 @@ import {
message,
Modal,
Switch,
DatePicker
} from 'antd';
import {
DashboardOutlined,
@@ -65,7 +66,8 @@ import VideoPlayer from '../VideoPlayer.tsx';
import SteerButton from './SteerButton';
import AgrtcRoomRobot from '../AgrtcRoomRobot';
import DeviceController from './DeviceController';
import { DatePicker } from 'antd';
import { deviceRunParamSelectByDeviceId } from '@/api/stationManage/index';
import dayjs from 'dayjs';
import { MowerAllView } from './MowerAllView';
import { useMqtt } from '@/hooks/useMqtt';
@@ -77,8 +79,9 @@ import { useTranslation } from 'react-i18next';
import { backToRestPointCommand } from '@/api/mapEdit';
import CarReverseGuideLine from './CarReverseGuideLine';
import mowerImg from '../../assets/images/mower.png';
import { sendEmergencyStop } from './emergencyStopControl';
import { sendEmergencyStop, syncEmergencyStop } from './emergencyStopControl';
const { RangePicker } = DatePicker;
const { Text } = Typography;
const ConsoleBadge = ({ online, text, color }: any) => (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, color: color || (online ? '#52c41a' : '#8c8c8c'), whiteSpace: 'nowrap' }}>
@@ -86,15 +89,7 @@ const ConsoleBadge = ({ online, text, color }: any) => (
{text}
</span>
);
const ConsoleRow = ({ icon, label, value }: any) => (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#8c8c8c', whiteSpace: 'nowrap' }}>
{icon}
{label}
</span>
<span style={{ fontSize: 12, color: '#262626', textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{value}</span>
</div>
);
// 暗色控制台面板(参考图样式:细边框、小圆角、蓝色竖条标题、右侧状态 badge)
const ConsolePanel = ({ title, extra, badge, children, style, bodyStyle }: any) => (
<div style={{ display: 'flex', flexDirection: 'column', background: '#fff', borderRadius: 10, overflow: 'hidden', ...style }}>
@@ -108,76 +103,7 @@ const ConsolePanel = ({ title, extra, badge, children, style, bodyStyle }: any)
<div style={{ flex: 1, minHeight: 0, padding: 10, ...bodyStyle }}>{children}</div>
</div>
);
// 方向盘功能按钮(暗色小方块,样式参考参考图)
// SteerButton:支持长按持续发送(与 DPadControl 方向键行为一致)
//const SteerButton = ({ icon, label, color, onPressStart, onPressEnd }: any) => {
// const [pressed, setPressed] = useState(false);
// const holdingRef = useRef(false);
// const intervalRef = useRef<number | null>(null);
// const emitEndedRef = useRef(false);
// const stopHold = useCallback(() => {
// if (intervalRef.current !== null) { window.clearInterval(intervalRef.current); intervalRef.current = null; }
// if (!holdingRef.current) return;
// holdingRef.current = false;
// emitEndedRef.current = false;
// setPressed(false);
// onPressEnd?.();
// }, [onPressEnd]);
// const startHold = useCallback(() => {
// if (holdingRef.current) return;
// holdingRef.current = true;
// emitEndedRef.current = false;
// setPressed(true);
// if (intervalRef.current !== null) window.clearInterval(intervalRef.current);
// // 立即首帧 + 每 100ms 持续(DPadControl 也是 100ms)
// onPressStart?.();
// intervalRef.current = window.setInterval(() => {
// if (!holdingRef.current) return;
// onPressStart?.();
// }, 100);
// }, [onPressStart]);
// useEffect(() => () => {
// if (intervalRef.current !== null) window.clearInterval(intervalRef.current);
// if (holdingRef.current) stopHold();
// }, [stopHold]);
// return (
// <button
// type="button"
// aria-label={label}
// onMouseDown={(e) => { e.preventDefault(); e.stopPropagation(); startHold(); }}
// onMouseUp={(e) => { e.preventDefault(); e.stopPropagation(); stopHold(); }}
// onMouseLeave={() => { if (holdingRef.current) stopHold(); }}
// onTouchStart={(e) => { e.preventDefault(); startHold(); }}
// onTouchEnd={(e) => { e.preventDefault(); stopHold(); }}
// onTouchCancel={() => { if (holdingRef.current) stopHold(); }}
// onContextMenu={(e) => e.preventDefault()}
// onClick={(e) => e.preventDefault()}
// style={{
// flex: '1 1 0',
// display: 'flex',
// flexDirection: 'column',
// alignItems: 'center',
// justifyContent: 'center',
// gap: 4,
// minHeight: 46,
// padding: '6px 4px',
// borderRadius: 8,
// background: pressed ? color + '30' : '#1e293b',
// border: '1px solid ' + (pressed ? color : color + '55'),
// color: color,
// cursor: 'pointer',
// userSelect: 'none',
// touchAction: 'none',
// transform: pressed ? 'scale(0.94)' : 'scale(1)',
// boxShadow: pressed ? '0 0 14px ' + color + '66' : 'none',
// transition: 'transform .08s, background .12s, border-color .12s, box-shadow .12s',
// }}
// >
// <span style={{ display: 'inline-flex', fontSize: 16, lineHeight: 1 }}>{icon}</span>
// <span style={{ fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap' }}>{label}</span>
// </button>
// );
//};
export default function DeviceStatusPage() {
const { t } = useTranslation();
const { userInfo } = useSelector((state: RootState) => state.user);
@@ -198,9 +124,20 @@ export default function DeviceStatusPage() {
const [messageApi, contextHolder] = message.useMessage();
// 视频播放开关
const [isVideoPlaying, setIsVideoPlaying] = useState(false);
// 当前机器人摄像头路数(接口返回 cameraNum,1-4)
const [cameraNum, setCameraNum] = useState<number>(1);
// 行车辅助线开关(仅前视/后视单路叠加)
const [showGuideLine, setShowGuideLine] = useState<boolean>(true);
// 设备 Agora 视频频道号(后端 paramData 或 device 字段;最终兜底 SN)
const toggleVideoPlay = useCallback(() => {
setIsVideoPlaying(prev => !prev);
}, []);
// 选中机器人变化 → 拉设备参数,取 cameraNum 决定视频网格布局(1/2/4 路)
const [isControlled, setIsControlled] = useState(false);
const [hasControlRight, setHasControlRight] = useState(false);
const [connecting, setConnecting] = useState(false);
@@ -271,6 +208,15 @@ export default function DeviceStatusPage() {
const handleFinishEdPoint = (point) => {
setArrivedPoint(point);
}
const ConsoleRow = ({ icon, label, value }: any) => (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#8c8c8c', whiteSpace: 'nowrap' }}>
{icon}
{label}
</span>
<span style={{ fontSize: 12, color: '#262626', textAlign: 'right', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{value}</span>
</div>
);
useEffect(() => {
fetchAllData();
}, [userInfo, stationId]);
@@ -436,6 +382,50 @@ export default function DeviceStatusPage() {
onMessage: handleMqttMessage,
enabled: mqttTopics.length > 0,
});
useEffect(() => {
const id = device?.device_sn || device?.serialNumber || selectedSn;
if (!id || !stationId) {
setCameraNum(1);
return;
}
let cancelled = false;
deviceRunParamSelectByDeviceId({ deviceId: id }).then((res) => {
if (cancelled) return;
if (res?.code === 200) {
const n = Number(res.data?.cameraNum);
// channel 字段:videoChannel / cameraChannel / agoraChannel / rtcChannel / channel
setCameraNum(Number.isFinite(n) && n >= 1 && n <= 4 ? n : 1);
console.log('[DSP] deviceRunParam res.data=', res.data);
} else {
setCameraNum(1);
}
}).catch(() => {
if (!cancelled) setCameraNum(1);
});
return () => { cancelled = true; };
}, [device?.device_sn, device?.serialNumber, selectedSn, stationId]);
// 视角按钮:按摄像头路数动态裁剪
const viewButtons = useMemo(() => {
const all = [
{ key: 'all', label: t('devices.panorama') },
{ key: 'front', label: t('devices.frontView'), minCams: 1 },
{ key: 'back', label: t('devices.backView'), minCams: 1 },
{ key: 'left', label: t('devices.leftView'), minCams: 3 },
{ key: 'right', label: t('devices.rightView'), minCams: 3 },
];
const n = Number(cameraNum) || 1;
return all.filter((b) => !b.minCams || n >= b.minCams);
}, [cameraNum, t]);
// cameraNum 变化时自动把非法视角回退到 front
useEffect(() => {
const n = Number(cameraNum) || 1;
if (n <= 2 && (mowerView === 'left' || mowerView === 'right')) setMowerView('front');
}, [cameraNum, mowerView]);
// 合并无人机和机场数据
const currentDroneData = React.useMemo(() => {
return { ...persistentHostData, ...persistentDroneData };
@@ -461,6 +451,11 @@ export default function DeviceStatusPage() {
...locationInfo
};
}, [device, wsDeviceInfo, isUAV, locationInfo]);
// 实时下发的急停状态同步到共享锁存状态:true=已急停,false=未急停
useEffect(() => {
syncEmergencyStop(runningStatus?.emergency_stop);
}, [runningStatus?.emergency_stop]);
// 统一在线状态判断:优先实时数据,兜底接口数据
const isDeviceOnline = useMemo(() => {
// 1. 优先检查实时数据源(WebSocket 推送的 wsDeviceInfo / locationInfo)
@@ -546,6 +541,7 @@ export default function DeviceStatusPage() {
lon: robotLon,
lat: robotLat,
heading: runningStatus?.yaw || wsDeviceInfo?.yaw || locationInfo?.yaw || device?.lastRunningStatus?.heading || 0,
status: Object.keys(wsDeviceInfo || {}).length > 0 ? 'online' : 'offline',
};
}
return null;
@@ -560,7 +556,6 @@ export default function DeviceStatusPage() {
};
const handleDetectionReport = (res) => {
console.log("获取障碍物信息", res)
setDeportInfo(res);
}
useEffect(() => {
@@ -666,6 +661,12 @@ export default function DeviceStatusPage() {
}, [isUAV, device]);
const mapDevices = useMemo(() => {
if (!device) return null;
// 光圈颜色:无实时数据 → 红色;有实时数据 → feStatus 优先(1 工作中=green / 2 空闲=blue),status 兜底
const hasRealtime = (wsDeviceInfo && Object.keys(wsDeviceInfo).length > 0) || (locationInfo && Object.keys(locationInfo).length > 0);
const rtStatus = String(runningStatus?.feStatus ?? runningStatus?.status ?? '');
const deviceColor = hasRealtime
? (rtStatus === '1' ? 'green' : 'blue')
: 'red';
// 优先使用持久化MQTT数据,其次使用uavState
const lng = currentDroneData?.longitude ?? uavState?.longitude ?? runningStatus?.longitude ?? device.longitude;
const lat = currentDroneData?.latitude ?? uavState?.latitude ?? runningStatus?.latitude ?? device.latitude;
@@ -679,31 +680,33 @@ export default function DeviceStatusPage() {
longitude: lng,
latitude: lat,
name: device?.deviceAlias || device?.callsign || device?.deviceName || t('devices.device'),
color: deviceColor,
type: isUAV
? 'drone'
: device?.productName?.includes(t('constants.mower'))
? 'mower'
: 'robot',
};
}, [device, isUAV, runningStatus, uavState, currentDroneData]);
const handleControlMode = () => {
}, [device, isUAV, runningStatus, uavState, currentDroneData, wsDeviceInfo, locationInfo]);
const handleControlMode = (controlMode: number) => {
if (!selectedSn) {
messageApi.error(t('devices.selectDevice'));
return;
}
console.log(runningStatus, "现在的控制controlmode")
if (runningStatus?.control_mode == 3) {
//console.log(runningStatus,controlMode, "现在的控制controlmode")
if ((controlMode == 3 && runningStatus?.control_mode == 3) || runningStatus?.systemMode == 3) {
messageApi.warning(t('devices.onRemoteControl'));
return;
}
const data = {
controlMode: 3,
controlMode: controlMode,
deviceId: selectedSn
}
modeChage(data).then(res => {
if (res.code == 200) {
if (res.code == 200 && res?.data) {
messageApi.success(t('devices.controlModeSuccess'));
} else {
messageApi.error(res.msg || t('devices.controlModeFail'));
messageApi.error(t('devices.controlModeFail'));
}
}).catch(err => {
messageApi.success(t('devices.controlModeFail'));
@@ -718,38 +721,62 @@ export default function DeviceStatusPage() {
...currentDroneData, // 持久化数据最后覆盖,确保优先显示
};
}, [device, uavState, currentDroneData]);
// 模式/权限提示节流:仅在用户真实操作(有按键或摇杆输入)时提示,2 秒内只提示一次
// 避免点击页面其他区域、手柄轮询中性帧、失焦复位等无输入帧误触发提示
const controlWarnRef = useRef(0);
const handleGamepadUpdate = useCallback((state) => {
// 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏)
if (!isControlled) {
//if (!hasRequestedControlRef.current && !connecting) {
// hasRequestedControlRef.current = true;
// handleControlModal();
//}
return;
}
console.log(realtimePosition?.controlMode, "现在的控制controlmode")
if (realtimePosition?.controlMode && (realtimePosition?.controlMode != 3 || realtimePosition?.control_mode != 3)) {
messageApi.warning(t('devices.noRemoteControl'));
return;
const hasInput =
//(Array.isArray(state?.buttons) && state.buttons.some((v: any) => v == true || v == 1)) ||
(Array.isArray(state?.axes) && state.axes.some((v: any) => Math.abs(Number(v) || 0) > 0.05));
// 只有真实操作才做模式与权限校验,中性帧(无按键、轴为 0)不提示
if (hasInput) {
const now = Date.now();
if (now - controlWarnRef.current > 2000) {
let warned = false;
// 无控制权限时:提示(避免手柄/方向盘高频更新刷屏)
if (!isControlled) {
messageApi.warning("请获取控制权限");
warned = true;
}
console.log(runningStatus, "realtimePosition1111")
if (!(runningStatus?.control_mode == 3 || runningStatus?.systemMode == 3)) {
messageApi.warning(t('devices.switchControl'));
warned = true;
} else if (
runningStatus?.controlMode != 3 &&
runningStatus?.controlMode != 0 &&
runningStatus?.controlMode != null
) {
messageApi.warning(t('devices.noRemoteControl'));
warned = true;
}
if (warned) controlWarnRef.current = now;
}
}
console.log('Gamepad state updated:', state);
// 记录方向盘 xy 坐标,用于倒车影像叠加层
if (state?.axes) {
setSteerXY({ x: state.axes[2] || 0, y: state.axes[1] || 0 });
}
// 无论是否有输入(含 false/中性帧)都必须下发,保证设备侧能收到释放/停止状态
controllerRef.current?.sendGamepad(state);
}, [isControlled, connecting]);
// 手柄已连接时拦截面板操作并提示(2 秒内只提示一次,避免高频刷屏)
const gamepadWarnRef = useRef(0);
const blockIfGamepadConnected = useCallback(() => {
// 没连接手柄 或 还没获取控制权限 → 不拦截(没控制权限本来就发不出消息)
if (!isGamepadConnected || !isControlled) return false;
if (!isGamepadConnected) return false;
if (!isControlled) {
messageApi.warning("请获取控制权限");
return false;
}
const now = Date.now();
if (now - gamepadWarnRef.current > 2000) {
gamepadWarnRef.current = now;
messageApi.warning(t('devices.disconnectGamepadFirst'));
}
return true;
}, [isGamepadConnected, isControlled, t, messageApi]);
// 方向盘功能按钮:复用与手柄一致的遥控帧(指定位按下后短暂释放)
// 方向盘按键按下/释放帧(长按模式:onDown 每 100ms 调用一次;短按模式:sendSteerButton 一次性发送后 300ms 自动释放)
@@ -771,6 +798,63 @@ export default function DeviceStatusPage() {
sendSteerFrame(index, true);
window.setTimeout(() => sendSteerFrame(index, false), 300);
}, [sendSteerFrame]);
// 方向盘功能按钮:三组互斥锁存(割刀启动/停止、底盘升/降、点火/熄火)
type SteerGroup = 'blade' | 'chassis' | 'power';
const EMPTY_STEER_STATE: Record<SteerGroup, string | null> = { blade: null, chassis: null, power: null };
const [steerState, setSteerState] = useState<Record<SteerGroup, string | null>>(EMPTY_STEER_STATE);
const steerStateRef = useRef(steerState);
steerStateRef.current = steerState;
// 按锁存状态组装遥控帧:割刀统一走 button2(启动=true,停止/未点击=false)
const buildSteerButtons = useCallback((s: Record<SteerGroup, string | null>) => {
const buttons = new Array(17).fill(false);
buttons[2] = s.blade === 'start'; // 割刀:button2
buttons[0] = s.chassis === 'up'; // 底盘升起
buttons[1] = s.chassis === 'down'; // 底盘下降
buttons[4] = s.power === 'ignition'; // 点火
buttons[5] = s.power === 'shutdown'; // 熄火
return buttons;
}, []);
const sendSteerState = useCallback((next: Record<SteerGroup, string | null>) => {
steerStateRef.current = next;
setSteerState(next);
handleGamepadUpdate({
buttons: buildSteerButtons(next),
axes: [0, 0, 0, 0],
connected: true,
ts: Date.now(),
});
}, [buildSteerButtons, handleGamepadUpdate]);
// 点击:未激活→激活;再次点击→取消;切换同组另一个按钮时自动互斥
const toggleSteerGroup = useCallback((group: SteerGroup, value: string) => {
if (blockIfGamepadConnected()) return;
const prev = steerStateRef.current;
sendSteerState({ ...prev, [group]: prev[group] === value ? null : value } as Record<SteerGroup, string | null>);
}, [blockIfGamepadConnected, sendSteerState]);
// 锁存期间每 100ms 持续发送,保持"按住"语义
useEffect(() => {
if (steerState.blade === null && steerState.chassis === null && steerState.power === null) return;
const id = window.setInterval(() => {
const cur = steerStateRef.current;
if (cur.blade === null && cur.chassis === null && cur.power === null) return;
handleGamepadUpdate({
buttons: buildSteerButtons(cur),
axes: [0, 0, 0, 0],
connected: true,
ts: Date.now(),
});
}, 200);
return () => window.clearInterval(id);
}, [steerState, buildSteerButtons, handleGamepadUpdate]);
// 切换设备时清空锁存,避免残留
useEffect(() => {
steerStateRef.current = EMPTY_STEER_STATE;
setSteerState(EMPTY_STEER_STATE);
}, [selectedSn]);
const handleControlModal = useCallback(() => {
console.log('请求控制权限');
controllerRef.current?.requestControl();
@@ -1242,6 +1326,34 @@ export default function DeviceStatusPage() {
: '-'
}
/>
<ConsoleRow
icon={<DashboardOutlined />}
label={t('devices.systemMode')}
value={(() => {
const mode =
runningStatus?.system_mode ??
runningStatus?.systemMode ??
runningStatus?.control_mode ??
runningStatus?.controlMode;
switch (mode) {
case '2':
case 2:
return t('devices.autoTask');
case '3':
case 3:
return t('devices.remoteControl');
case '0':
case 0:
return t('devices.controlOff');
case '1':
case 1:
return t('devices.localCpntrol');
default:
return '-';
}
})()}
/>
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.forwardSpeed')} value={(runningStatus?.linear_speed ?? runningStatus?.linearSpeed) !== undefined ? Number(runningStatus?.linear_speed ?? runningStatus?.linearSpeed).toFixed(2) + ' m/s' : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.turnSpeed')} value={(runningStatus?.angular_speed ?? runningStatus?.angularSpeed) !== undefined ? Number(runningStatus?.angular_speed ?? runningStatus?.angularSpeed).toFixed(2) + ' rad/s' : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftMotor')} value={(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent) !== undefined ? Number(runningStatus?.left_motor_current ?? runningStatus?.leftCurrent).toFixed(2) + 'A' : '-'} />
@@ -1249,16 +1361,16 @@ export default function DeviceStatusPage() {
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftTemp')} value={(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.left_motor_temperature ?? runningStatus?.leftMotorTemp), 1).label : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightTemp')} value={(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp) !== undefined ? formatTemperature(Number(runningStatus?.right_motor_temperature ?? runningStatus?.rightMotorTemp), 1).label : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtMainTemp')} value={(runningStatus?.main_temperature ?? runningStatus?.chipTemp) !== undefined ? formatTemperature(Number(runningStatus?.main_temperature ?? runningStatus?.chipTemp), 1).label : '-'} />
<ConsoleRow icon={<EnvironmentOutlined />} label={t('devices.motionStatus')} value={runningStatus?.motion === 'moving' ? t('devices.motionMoving') : runningStatus?.motion === 'stopped' ? t('devices.motionStopped') : runningStatus?.motion === 'blocked' ? t('devices.motionBlocked') : '-'} />
{/*<ConsoleRow icon={<EnvironmentOutlined />} label={t('devices.motionStatus')} value={runningStatus?.motion === 'moving' ? t('devices.motionMoving') : runningStatus?.motion === 'stopped' ? t('devices.motionStopped') : runningStatus?.motion === 'blocked' ? t('devices.motionBlocked') : '-'} />*/}
<ConsoleRow icon={<EnvironmentOutlined />} label={t('devices.cutterSpedd')} value={runningStatus?.cutter_speed ?? "-"} />
<ConsoleRow icon={<SafetyOutlined />} label={t('devices.rtEmergency')} value={runningStatus?.emergency_stop === true ? t('devices.estopTriggered') : runningStatus?.emergency_stop === false ? t('devices.estopNormal') : '-'} />
<ConsoleRow icon={<SafetyOutlined />} label={t('devices.rtEmergency')} value={runningStatus?.emergency_stop == "true" ? t('devices.estopTriggered') : runningStatus?.emergency_stop == "false" ? t('devices.estopNormal') : '-'} />
{/*<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftMeasureRpm')} value={(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed) !== undefined ? Number(runningStatus?.left_measured_rpm ?? runningStatus?.leftMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/}
{/*<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightMeasureRpm')} value={(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed) !== undefined ? Number(runningStatus?.right_measured_rpm ?? runningStatus?.rightMeasureSpeed).toFixed(1) + 'rpm' : '-'} />*/}
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtLeftMotorRpm')} value={runningStatus?.left_motor_rpm !== undefined ? Number(runningStatus?.left_motor_rpm).toFixed(1) + 'rpm' : '-'} />
<ConsoleRow icon={<DashboardOutlined />} label={t('devices.rtRightMotorRpm')} value={runningStatus?.right_motor_rpm !== undefined ? Number(runningStatus?.right_motor_rpm).toFixed(1) + 'rpm' : '-'} />
<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkArea')} value={runningStatus?.total_work_area !== undefined ? Number(runningStatus?.total_work_area).toFixed(2) : '-'} />
{/*<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkArea')} value={runningStatus?.total_work_area !== undefined ? Number(runningStatus?.total_work_area).toFixed(2) : '-'} />
<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkDuration')} value={runningStatus?.total_work_duration !== undefined ? Number(runningStatus?.total_work_duration).toFixed(0) : '-'} />
<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkDistance')} value={runningStatus?.total_work_distance !== undefined ? Number(runningStatus?.total_work_distance).toFixed(2) : '-'} />
<ConsoleRow icon={<GlobalOutlined />} label={t('devices.totalWorkDistance')} value={runningStatus?.total_work_distance !== undefined ? Number(runningStatus?.total_work_distance).toFixed(2) : '-'} />*/}
</div>
</div>
</ConsolePanel>
@@ -1283,51 +1395,57 @@ export default function DeviceStatusPage() {
bodyStyle={{ padding: 8, display: 'flex', flexDirection: 'column', gap: 8 }}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0, overflowX: 'auto' }}>
{[{ key: 'front', label: t('devices.frontView') }, { key: 'left', label: t('devices.leftView') }, { key: 'right', label: t('devices.rightView') }, { key: 'back', label: t('devices.backView') }, { key: 'all', label: t('devices.panorama') }].map((v) => (
{viewButtons.map((v) => (
<Button key={v.key} type={mowerView === v.key ? 'primary' : 'default'} size="small" onClick={() => setMowerView(v.key)}>
{v.label}
</Button>
))}
<span style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#555' }}>
{t('devices.showGuideLine')}
<Switch size="small" checked={showGuideLine} onChange={setShowGuideLine} />
</span>
</div>
<div style={{ position: 'relative', flex: 1, minHeight: 0, borderRadius: 8, overflow: 'hidden', }}>
{isVideoPlaying && (
mowerView === 'all' ? (
// 全景/网格视图:单频道多 UID,按 cameraNum 决定 1/2/4 路布局
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<MowerAllView serialNumber={device?.serialNumber} robotVideo={robotVideo} error={error} ready={ready} />
<AgrtcRoomRobot channel={device?.serialNumber || device?.device_sn || ""} cameraCount={cameraNum} />
</div>
) : mowerView === 'front' ? (
// 前视:单路 UID 101
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<AgrtcRoomRobot CHANNEL={"41-thream03"} />
<AgrtcRoomRobot channel={device?.serialNumber || device?.device_sn || ""} slotUids={[101]} />
<CarReverseGuideLine
direction="forward"
steer={steerXY.x * 45}
linearSpeed={Number(runningStatus?.linear_speed ?? runningStatus?.linearSpeed)}
angularSpeed={Number(runningStatus?.angular_speed ?? runningStatus?.angularSpeed)}
visible={isVideoPlaying}
visible={isVideoPlaying && showGuideLine}
/>
</div>
) : mowerView === 'back' ? (
// 后视:单路 UID 103 + 倒车辅助线
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<AgrtcRoomRobot channel={device?.serialNumber || device?.device_sn || ""} slotUids={[103]} />
<CarReverseGuideLine
direction="reverse"
steer={steerXY.x * 45}
linearSpeed={Number(runningStatus?.linear_speed ?? runningStatus?.linearSpeed)}
angularSpeed={Number(runningStatus?.angular_speed ?? runningStatus?.angularSpeed)}
visible={isVideoPlaying && showGuideLine}
/>
</div>
) : mowerView === 'left' ? (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<AgrtcRoomRobot channel={device?.serialNumber || device?.device_sn || ""} slotUids={[102]} />
</div>
) : (
// 右视:单路 UID 104
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 }}>
<VideoPlayer
deviceId={device?.serialNumber}
idx={mowerView === 'back' ? 2 : mowerView === 'left' ? 3 : 4}
className="w-full h-full object-contain"
video={robotVideo}
error={error}
ready={ready}
/>
{mowerView === 'back' && (
<CarReverseGuideLine
direction="reverse"
steer={steerXY.x * 45}
linearSpeed={Number(runningStatus?.linear_speed ?? runningStatus?.linearSpeed)}
angularSpeed={Number(runningStatus?.angular_speed ?? runningStatus?.angularSpeed)}
visible={isVideoPlaying}
/>
)}
<AgrtcRoomRobot channel={device?.serialNumber || device?.device_sn || ""} slotUids={[104]} />
</div>
)
)}
))}
{!isVideoPlaying && (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 12, color: 'rgba(14, 78, 198, 0.55)' }}>
<VideoCameraOutlined style={{ fontSize: 56, opacity: 0.6 }} />
@@ -1405,10 +1523,10 @@ export default function DeviceStatusPage() {
bodyStyle={{ padding: 10, display: 'flex', alignItems: 'center', gap: 10, overflow: 'hidden' }}
>
<div style={{ width: 300, flexShrink: 0, transform: 'scale(0.82)', transformOrigin: 'left center' }}>
<XboxController onGamepadUpdate={handleGamepadUpdate} onConnectionChange={setIsGamepadConnected} />
<XboxController onGamepadUpdate={handleGamepadUpdate} onConnectionChange={setIsGamepadConnected} deviceId={selectedSn} />
</div>
<div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6, overflow: 'auto' }}>
{[{ k: t('devices.gamepad.leftStick'), v: t('devices.gamepad.leftStickDesc') }, { k: t('devices.gamepad.rightStick'), v: t('devices.gamepad.rightStickDesc') }, { k: t('devices.gamepad.aKey'), v: t('devices.gamepad.aKeyDesc') }, { k: t('devices.gamepad.bKey'), v: t('devices.gamepad.bKeyDesc') }, { k: t('devices.gamepad.xKey'), v: t('devices.gamepad.xKeyDesc') }, { k: t('devices.gamepad.yKey'), v: t('devices.gamepad.yKeyDesc') }, { k: "LB", v: t("devices.gamepad.lbDesc") }, { k: "RB", v: t("devices.gamepad.rbDesc") }].map((item) => (
{[{ k: t('devices.gamepad.leftStick'), v: t('devices.gamepad.leftStickDesc') }, { k: t('devices.gamepad.rightStick'), v: t('devices.gamepad.rightStickDesc') }, { k: t('devices.gamepad.aKey'), v: t('devices.gamepad.aKeyDesc') }, { k: t('devices.gamepad.bKey'), v: t('devices.gamepad.bKeyDesc') }, { k: t('devices.gamepad.xKey'), v: t('devices.gamepad.xKeyDesc') }, { k: t('devices.gamepad.yKey'), v: t('devices.gamepad.yKeyDesc') }, { k: "LB", v: t("devices.gamepad.lbDesc") }, { k: "RB", v: t("devices.gamepad.rbDesc") }, { k: "Stop", v: t("devices.gamepad.Stop") }].map((item) => (
<div key={item.k} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
<span style={{ minWidth: 52, color: '#8c8c8c', whiteSpace: 'nowrap' }}>{item.k}</span>
<span style={{ color: '#262626' }}>{item.v}</span>
@@ -1427,21 +1545,21 @@ export default function DeviceStatusPage() {
<DPadControl
onGamepadUpdate={(state) => { if (blockIfGamepadConnected()) return; handleGamepadUpdate(state); }}
onSpeedChange={() => { }}
onEmergencyStop={() => sendEmergencyStop(userInfo)}
onEmergencyStop={() => sendEmergencyStop(selectedSn)}
/>
</div>
<div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 8 }}>
<div style={{ display: 'flex', gap: 8 }}>
<SteerButton icon={<PlayCircleOutlined />} label={t('devices.steer.ignition')} color="#22c55e" onPressStart={() => sendSteerFrame(4, true)} onPressEnd={() => sendSteerFrame(4, false)} />
<SteerButton icon={<PoweroffOutlined />} label={t('devices.steer.shutdown')} color="#ef4444" onPressStart={() => sendSteerFrame(5, true)} onPressEnd={() => sendSteerFrame(5, false)} />
<SteerButton icon={<PlayCircleOutlined />} label={t('devices.steer.ignition')} color="#22c55e" active={steerState.power === 'ignition'} onToggle={() => toggleSteerGroup('power', 'ignition')} />
<SteerButton icon={<PoweroffOutlined />} label={t('devices.steer.shutdown')} color="#ef4444" active={steerState.power === 'shutdown'} onToggle={() => toggleSteerGroup('power', 'shutdown')} />
</div>
<div style={{ display: 'flex', gap: 8 }}>
<SteerButton icon={<ArrowUpOutlined />} label={t('devices.steer.chassisUp')} color="#3b82f6" onPressStart={() => sendSteerFrame(0, true)} onPressEnd={() => sendSteerFrame(0, false)} />
<SteerButton icon={<ArrowDownOutlined />} label={t('devices.steer.chassisDown')} color="#3b82f6" onPressStart={() => sendSteerFrame(1, true)} onPressEnd={() => sendSteerFrame(1, false)} />
<SteerButton icon={<ArrowUpOutlined />} label={t('devices.steer.chassisUp')} color="#3b82f6" active={steerState.chassis === 'up'} onToggle={() => toggleSteerGroup('chassis', 'up')} />
<SteerButton icon={<ArrowDownOutlined />} label={t('devices.steer.chassisDown')} color="#3b82f6" active={steerState.chassis === 'down'} onToggle={() => toggleSteerGroup('chassis', 'down')} />
</div>
<div style={{ display: 'flex', gap: 8 }}>
<SteerButton icon={<PlusOutlined />} label={t('devices.steer.cutterAccel')} color="#f59e0b" onPressStart={() => sendSteerFrame(2, true)} onPressEnd={() => sendSteerFrame(2, false)} />
<SteerButton icon={<MinusOutlined />} label={t('devices.steer.cutterDecel')} color="#f59e0b" onPressStart={() => sendSteerFrame(3, true)} onPressEnd={() => sendSteerFrame(3, false)} />
<SteerButton icon={<PlusOutlined />} label={t('devices.steer.cutterAccel')} color="#f59e0b" active={steerState.blade === 'start'} onToggle={() => toggleSteerGroup('blade', 'start')} />
<SteerButton icon={<MinusOutlined />} label={t('devices.steer.cutterDecel')} color="#f59e0b" active={steerState.blade === 'stop'} onToggle={() => toggleSteerGroup('blade', 'stop')} />
</div>
</div>
</ConsolePanel>
@@ -1453,12 +1571,13 @@ export default function DeviceStatusPage() {
bodyStyle={{ padding: 10, display: 'flex', flex: "auto" }}
>
<RobotFeatureButtons
showEmergencyStop={false}
showEmergencyStop
deviceId={selectedSn}
activeFeatures={['response', 'obstacleAvoidance', 'lowBatteryReturn', 'tiltProtection', "findCar"]}
onToggle={(feature, enabled) => { console.log('[DeviceStatusPage] Feature toggled: ' + feature + ' = ' + enabled); }}
sendFindCar={() => handleFindCar()}
sendAutoBack={() => handleAutoBack()}
sendControlMode={() => handleControlMode()}
sendControlMode={(data) => handleControlMode(data)}
controlMode={runningStatus?.controlMode}
/>
</ConsolePanel>

View File

@@ -181,11 +181,13 @@ export const MapEditorView = React.forwardRef(function MapEditorView(
}, [presetRoutes, presetModeFilter]);
const selectRobot = useMemo(() => {
if (!Array.isArray(robots)) return [];
// 任务规划页面:机器没有实时消息(无实时位置)时,不在地图上显示
if (extraMapProps && !extraMapProps.realtimePosition) return [];
return robots
.filter(robot => robot.serialNumber == selectedRobotId)
.map(robot => (extraMapProps?.deviceColor ? { ...robot, color: extraMapProps.deviceColor } : robot));
}, [selectedRobotId, robots, extraMapProps?.deviceColor]);
}, [selectedRobotId, robots, extraMapProps?.deviceColor, extraMapProps?.realtimePosition]);
useEffect(() => {
if (extraMapProps.polyPoints?.length > 0) {
setPolyPoints(extraMapProps.polyPoints);
@@ -1553,21 +1555,37 @@ export const MapEditorView = React.forwardRef(function MapEditorView(
}}
>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 500 }}>
{route.workName || route.name || t('devices.mapEditor.unnamed')}
</div>
<div style={{ fontSize: 11, color: '#86909C', marginTop: 2 }}>
{t('devices.mapEditor.mode')}: {route.mode === 'coverage' || route.mode === 'coverage_area'
? t('devices.coverageMode') : route.mode === 'predefined_path' ? t('devices.predefinedPathMode')
: t('devices.singleMode')}
{route.routeType && (
<span style={{ marginLeft: 8 }}>
· {route.routeType === 'MOWING_TASK' ? t('devices.mapEditor.typeMowing')
: route.routeType === 'INSPECTION_TASK' ? t('devices.mapEditor.typeInspection')
: t('devices.mapEditor.typeOther')}
</span>
)}
<div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexDirection: 'row' }}>
<div>
{route?.imgUrl && (
<img
src={route.imgUrl}
alt=""
style={{ width: 20, height: 20, objectFit: 'cover' }}
/>
)}
</div>
<div>
<div style={{ fontSize: 13, fontWeight: 500 }}>
{route.workName || route.name || t('devices.mapEditor.unnamed')}
</div>
<div style={{ fontSize: 11, color: '#86909C', marginTop: 2 }}>
{t('devices.mapEditor.mode')}: {route.mode === 'coverage' || route.mode === 'coverage_area'
? t('devices.coverageMode') : route.mode === 'predefined_path' ? t('devices.predefinedPathMode')
: t('devices.singleMode')}
{route.routeType && (
<span style={{ marginLeft: 8 }}>
· {route.routeType === 'MOWING_TASK' ? t('devices.mapEditor.typeMowing')
: route.routeType === 'INSPECTION_TASK' ? t('devices.mapEditor.typeInspection')
: t('devices.mapEditor.typeOther')}
</span>
)}
</div>
</div>
</div>
</div>
<Button
size="small"

View File

@@ -1,8 +1,8 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { sendEmergencyStop } from './emergencyStopControl';
import { sendEmergencyStop, subscribeEmergencyStop } from './emergencyStopControl';
import {
ShieldAlert,
Zap,
@@ -19,7 +19,8 @@ export type RobotFeature =
| 'tiltProtection'
| 'findCar'
| 'autoback'
| 'controlMode';
| 'controlMode'
| 'personFollow';
export interface FeatureConfig {
key: RobotFeature;
@@ -37,6 +38,7 @@ const FEATURES: FeatureConfig[] = [
//{ key: 'tiltProtection', icon: <MoveVertical className="w-6 h-6" />, activeColor: '#10b981', inactiveColor: '#94a3b8' },
{ key: 'autoback', icon: <Zap className="w-6 h-6" />, activeColor: '#22c55e', inactiveColor: '#94a3b8' },
{ key: 'findCar', icon: <ShieldAlert className="w-6 h-6" />, activeColor: '#ef4444', inactiveColor: '#94a3b8' },
{ key: 'personFollow', icon: <MoveVertical className="w-6 h-6" />, activeColor: '#10b981', inactiveColor: '#94a3b8' },
];
// 急停方块
@@ -55,6 +57,7 @@ interface RobotFeatureButtonsProps {
sendFindCar?: () => void;
sendAutoBack?: () => void;
sendControlMode?: () => void;
deviceId?: string;
controlMode?: number | string;
}
@@ -66,19 +69,24 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
sendFindCar,
sendAutoBack,
sendControlMode,
controlMode
controlMode,
deviceId
}) => {
const { t } = useTranslation();
const { userInfo } = useSelector((state: RootState) => state.user);
const [active, setActive] = useState<Set<RobotFeature>>(new Set(activeFeatures));
// 临时按压闪烁标记
const [flashKey, setFlashKey] = useState<RobotFeature | null>(null);
// 急停锁存状态:与 DPad / 手柄共用同一份状态,点击后保持按下态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
// 一次性触发,不toggle的按钮列表
const oneShotKeys: RobotFeature[] = ['emergencyStop', 'findCar', 'autoback', 'controlMode'];
const oneShotKeys: RobotFeature[] = ['emergencyStop', 'findCar', 'autoback', 'controlMode', 'personFollow'];
const list = showEmergencyStop ? [EMERGENCY, ...FEATURES] : FEATURES;
const handleClick = (feature: RobotFeature) => {
// 触发按压反馈
setFlashKey(feature);
@@ -89,7 +97,7 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
// 一次性按钮:只发指令,不切换active状态
if (oneShotKeys.includes(feature)) {
if (feature === 'emergencyStop') {
sendEmergencyStop(userInfo);
sendEmergencyStop(deviceId || "");
onToggle?.(feature, true);
return;
}
@@ -100,8 +108,12 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
sendAutoBack?.();
}
if (feature === 'controlMode') {
sendControlMode?.();
sendControlMode?.(3);
}
if (
feature === 'personFollow'
) sendControlMode?.(4);
return;
}
@@ -129,9 +141,11 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
`}
</style>
{list.map((f) => {
const isOneShot = oneShotKeys.includes(f.key);
const isActive = active.has(f.key);
const isFlashing = flashKey === f.key;
const isEmergency = f.key === 'emergencyStop';
const isOneShot = oneShotKeys.includes(f.key) && !isEmergency;
// 急停走锁存状态,其余按钮沿用本地 toggle 状态
const isActive = isEmergency ? eStopActive : active.has(f.key);
const isFlashing = flashKey === f.key
const shouldGlow = f.key === 'controlMode' && controlMode != 3;
return (

View File

@@ -1,186 +1,368 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Row, Col, Card, Space, Typography, Select, Empty } from 'antd';
import { Car, Satellite, LayoutGrid, CheckCircle2, AlertCircle, TrendingUp } from 'lucide-react';
import { getSiteDevice, getSiteUAVList } from '../../api/device';
import { useSelector } from 'react-redux';
import { RootState } from '@/src/store';
import { useTranslation } from 'react-i18next';
import { WayLineView } from './WayLineView';
import { TaskPlanningView } from './TaskPlanningView';
import type { ViewStats } from './WayLineView';
const { Text } = Typography;
// ==================== 合并页面:任务规划 + 地图编辑 + 航线任务 ====================
interface MachineOption {
value: string;
label: string;
group: 'robot' | 'plane';
}
export default function RobotTaskPage() {
const { t } = useTranslation();
const { stationId, currentStation } = useSelector((state: RootState) => state.station);
const [machineOptions, setMachineOptions] = useState<MachineOption[]>([]);
const [selectedMachine, setSelectedMachine] = useState<string | undefined>(undefined);
const [selectedGroup, setSelectedGroup] = useState<'robot' | 'plane' | undefined>(undefined);
const [robotStats, setRobotStats] = useState<ViewStats>({});
const [droneStats, setDroneStats] = useState<ViewStats>({});
const [robotOnline, setRobotOnline] = useState({ online: 0, total: 0 });
// 顶部统一机器列表:机器人 + 无人机合并
useEffect(() => {
if (!stationId) return;
let ignore = false;
const loadMachines = async () => {
try {
const [robotRes, planeRes] = await Promise.all([
getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1, orgId: currentStation?.orgId }),
getSiteUAVList(stationId),
]);
if (ignore) return;
const robots = robotRes?.code === 200 ? (robotRes.rows || []) : [];
const planes = planeRes?.code === 200 ? (planeRes.rows || []) : [];
const options: MachineOption[] = [
...robots
.filter((r) => !!r.serialNumber)
.map((r) => ({ value: r.serialNumber, label: r.deviceAlias || r.deviceName || r.serialNumber, group: 'robot' as const })),
...planes
.filter((p) => !!p.device_sn)
.map((p) => ({ value: p.device_sn, label: p.drone_callsign || p.device_sn, group: 'plane' as const })),
];
setMachineOptions(options);
// 初始化时默认选中机器人分组的第一个(无机器人时取第一个选项)
const firstRobot = options.find((o) => o.group === 'robot') || options[0];
if (firstRobot) {
setSelectedMachine((prev) => prev || firstRobot.value);
setSelectedGroup((prev) => prev || firstRobot.group);
setSelectedMachine(firstRobot.value);
setSelectedGroup(firstRobot.group);
}
setRobotOnline({
online: robots.filter((r) => r.onlineStatus == 1).length,
total: robots.length,
});
} catch (err) {
console.error('获取机器列表失败', err);
}
};
loadMachines();
return () => { ignore = true; };
}, [stationId, currentStation?.orgId]);
const handleMachineChange = (value: string | undefined) => {
setSelectedMachine(value);
const hit = machineOptions.find((o) => o.value === value);
setSelectedGroup(hit?.group);
};
// 分组下拉:仅有对应机器时才显示该分组
const groupedOptions = useMemo(() => {
const groups: { label: string; options: { value: string; label: string }[] }[] = [];
const robots = machineOptions.filter((o) => o.group === 'robot');
const planes = machineOptions.filter((o) => o.group === 'plane');
if (robots.length) {
groups.push({ label: t('devices.robot'), options: robots.map((o) => ({ value: o.value, label: o.label })) });
}
if (planes.length) {
groups.push({ label: t('devices.drone'), options: planes.map((o) => ({ value: o.value, label: o.label })) });
}
return groups;
}, [machineOptions]);
const cardStyle = { borderRadius: 12, border: 'none', boxShadow: '0 2px 12px rgba(0,0,0,0.04)' };
// 顶部统计卡:机器人任务 + 无人机航线任务数据合并
const mergedCards = useMemo(() => {
const planTotal = (robotStats.planTotal || 0) + (droneStats.planTotal || 0);
const working = (robotStats.working || 0) + (droneStats.working || 0);
const finishCount = (robotStats.finishCount || 0) + (droneStats.finishCount || 0);
const totalCount = (robotStats.totalCount || 0) + (droneStats.totalCount || 0);
const completionRate = totalCount ? Math.round((finishCount / totalCount) * 100) : 0;
const onlineRate = robotOnline.total ? Math.round((robotOnline.online / robotOnline.total) * 100) : 0;
const totalWorkArea = robotStats?.workArea ?? "0";
return [
{ title: t('devices.statTodayPlan'), value: planTotal, unit: t('devices.unitPlan'), desc: t('devices.statInProgress'), icon: <LayoutGrid size={22} />, color: '#165DFF' },
{ title: t('devices.statWorkingRobots'), value: working, unit: t('devices.unitRobot'), desc: t('devices.statWorking'), icon: <Car size={22} />, color: '#165DFF' },
{ title: t('devices.statTotalDistance'), value: '12.5', unit: 'km', trend: t('devices.vsYesterday', { value: '+1.2' }), trendColor: '#00B42A', icon: <TrendingUp size={22} />, color: '#722ED1' },
//{ title: t('devices.totalWorkArea'), value: totalWorkArea, unit: '㎡', trend: "", trendColor: '#00B42A', icon: <TrendingUp size={22} />, color: '#722ED1' },
{ title: t('devices.statCompletionRate'), value: completionRate, unit: '%', trend: t('devices.vsYesterday', { value: '+5%' }), trendColor: '#00B42A', icon: <CheckCircle2 size={22} />, color: '#00B42A' },
{ title: t('devices.statAlerts'), value: '0', unit: t('devices.unitTimes'), trend: t('devices.vsYesterday', { value: '-1' }), trendColor: '#00B42A', icon: <AlertCircle size={22} />, color: '#F53F3F' },
{ title: t('devices.statOnlineRate'), value: `${onlineRate}`, unit: '%', desc: t('devices.good'), icon: <Satellite size={22} />, color: '#165DFF' },
] as { title: string; value: any; unit: string; desc?: string; trend?: string; trendColor?: string; icon: React.ReactElement; color: string }[];
}, [robotStats, droneStats, robotOnline, t]);
return (
<div style={{ background: '#f5f7fa', minHeight: '100vh' }}>
<div style={{ zIndex: 100, padding: '8px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
<Typography.Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.2vw, 18px)' }}>
{t('devices.robotTask')}
</Typography.Title>
<Space>
<Text type="secondary">{t('devices.mapEditor.selectRobot')}</Text>
<Select
showSearch
allowClear
style={{ width: 340 }}
placeholder={t('devices.mapEditor.selectRobot')}
value={selectedMachine}
onChange={handleMachineChange}
optionFilterProp="label"
options={groupedOptions}
/>
</Space>
</div>
<div style={{ padding: '8px 2px 0' }}>
<Row gutter={[16, 16]} style={{ marginBottom: 8 }}>
<Row gutter={[16, 16]} wrap={false} style={{ marginBottom: 8 }}>
{mergedCards.map((item, index) => (
<Col xs={12} sm={8} md={4} key={index}>
<Col flex="1" key={index}>
<Card
variant="borderless"
styles={{ body: { padding: '12px 14px', height: '100%', display: 'flex', alignItems: 'center' } }}
style={{ ...cardStyle, height: '100%', minHeight: '84px' }}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%' }}>
<div
style={{
width: 36,
height: 36,
background: 'rgba(22, 93, 255, 0.1)',
borderRadius: 10,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
color: item.color,
flexShrink: 0,
}}
>
{React.cloneElement(item.icon as React.ReactElement, { size: 18 })}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, color: '#86909C', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.title}</div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4, margin: '2px 0' }}>
<span style={{ fontSize: 'clamp(16px, 1vw, 20px)', fontWeight: 700, color: '#1D2129', lineHeight: '1.2' }}>{item.value}</span>
<span style={{ fontSize: 9, color: '#4E5969' }}>{item.unit}</span>
</div>
<div style={{ fontSize: 9, color: (item as any).trendColor || '#86909C', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{item.trend || item.desc}
</div>
</div>
</div>
</Card>
</Col>
))}
</Row>
{!selectedMachine ? (
<TaskPlanningView selectedMachineSn={selectedMachine} embedded onStatsChange={setRobotStats} />
) : selectedGroup === 'plane' ? (
<WayLineView selectedSn={selectedMachine} embedded onStatsChange={setDroneStats} />
) : (
<TaskPlanningView selectedMachineSn={selectedMachine} embedded onStatsChange={setRobotStats} />
)}
</div>
</div>
);
}

View File

@@ -1,122 +1,33 @@
import { useCallback, useEffect, useRef, useState } from 'react';
interface SteerButtonProps {
icon: React.ReactNode;
label: string;
color: string;
onPressStart?: () => void;
onPressEnd?: () => void;
interval?: number;
// 受控高亮:由父组件统一管理,保证同组按钮互斥(不会同时显示为按下)
active?: boolean;
disabled?: boolean;
onToggle?: () => void;
}
/**
* 锁存按钮(受控):
* 高亮状态完全由 active 决定,点击只触发 onToggle。
* 持续发送 / 互斥逻辑由父组件统一管理。
*/
const SteerButton = ({
icon,
label,
color,
onPressStart,
onPressEnd,
interval = 100,
active = false,
disabled = false,
onToggle,
}: SteerButtonProps) => {
const [pressed, setPressed] = useState(false);
// 是否处于按下状态
const holdingRef = useRef(false);
// 定时发送句柄
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// 保存最新的回调,避免定时器使用过期闭包
const onPressStartRef = useRef(onPressStart);
const onPressEndRef = useRef(onPressEnd);
useEffect(() => {
onPressStartRef.current = onPressStart;
}, [onPressStart]);
useEffect(() => {
onPressEndRef.current = onPressEnd;
}, [onPressEnd]);
// 停止长按
const stopHold = useCallback(() => {
if (!holdingRef.current) return;
holdingRef.current = false;
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
setPressed(false);
// 只在有效按压结束时发送一次释放数据
onPressEndRef.current?.();
}, []);
// 开始长按
const startHold = useCallback(() => {
// 防止重复触发
if (holdingRef.current) return;
holdingRef.current = true;
setPressed(true);
// 立即发送第一帧
onPressStartRef.current?.();
// 持续发送
const scheduleNext = () => {
if (!holdingRef.current) return;
timerRef.current = setTimeout(() => {
if (!holdingRef.current) return;
onPressStartRef.current?.();
scheduleNext();
}, interval);
};
scheduleNext();
}, [interval]);
// 组件卸载时清理定时器
useEffect(() => {
return () => {
holdingRef.current = false;
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
}, []);
return (
<button
type="button"
aria-label={label}
aria-pressed={pressed}
onPointerDown={(e) => {
e.preventDefault();
e.stopPropagation();
// 仅响应鼠标左键,触摸和笔不受影响
if (e.pointerType === 'mouse' && e.button !== 0) return;
// 捕获指针,确保在按钮外松开也能收到事件
e.currentTarget.setPointerCapture(e.pointerId);
startHold();
}}
onPointerUp={(e) => {
e.preventDefault();
e.stopPropagation();
stopHold();
}}
onPointerCancel={stopHold}
onLostPointerCapture={stopHold}
aria-pressed={active}
disabled={disabled}
onClick={onToggle}
onContextMenu={(e) => e.preventDefault()}
style={{
flex: '1 1 0',
@@ -128,15 +39,18 @@ const SteerButton = ({
minHeight: 46,
padding: '6px 4px',
borderRadius: 8,
border: `1px solid ${pressed ? color : `${color}55`}`,
border: `1px solid ${active ? color : `${color}55`}`,
background: active ? `${color}22` : 'transparent',
color,
cursor: 'pointer',
cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.4 : 1,
userSelect: 'none',
touchAction: 'none',
transform: pressed ? 'scale(0.94)' : 'scale(1)',
boxShadow: pressed ? `0 0 14px ${color}66` : 'none',
transform: active ? 'scale(0.97)' : 'scale(1)',
boxShadow: active ? `0 0 14px ${color}66, inset 0 0 8px ${color}22` : 'none',
fontWeight: active ? 700 : 500,
transition:
'transform .08s, background .12s, border-color .12s, box-shadow .12s',
'transform .08s, background .12s, border-color .12s, box-shadow .12s, font-weight .12s, opacity .12s',
}}
>
<span style={{ display: 'inline-flex', fontSize: 16, lineHeight: 1 }}>

View File

@@ -1,9 +1,9 @@
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Row, Col, Card, Button, Space, Table, Tag, Typography, Badge, Tabs, Input, Switch, Tooltip, Timeline, Select, message, DatePicker, TimePicker, Popconfirm, App, Radio, Empty } from 'antd';
import { Row, Col, Card, Button, Space, Table, Tag, Typography, Badge, Tabs, Input, Switch, Tooltip, Timeline, Select, message, DatePicker, TimePicker, Popconfirm, App, Radio, Empty, Collapse } from 'antd';
import { PlusOutlined, ImportOutlined, NodeIndexOutlined, SaveOutlined, DeleteOutlined, CloseOutlined, ReloadOutlined, ExclamationCircleOutlined, EnvironmentOutlined, EnvironmentFilled } from '@ant-design/icons';
import { Car, Navigation, MapPinned, Route, Satellite, LayoutGrid, CheckCircle2, AlertCircle, TrendingUp, Maximize2 } from 'lucide-react';
import TaskTypeRadio from '../taskRadio/taskRadio';
import { getRobotRouteList, getSingleRouteList, saveDeviceTask, getRobotTaskList, deleteDeviceTask, getSiteDevice, excuetRoute, cancelRoute, pauseRoute, recoverRoute, getDeviceTastPool, getSiteDeviceTaskHistory, getRouteByTask, deleteRoute, getTaskPath, createConsecutiveTasks, cancelConsecutiveTask, getConsecutiveTask, modeChage } from '../../api/device';
import { getRobotRouteList, getSingleRouteList, saveDeviceTask, getRobotTaskList, deleteDeviceTask, getSiteDevice, excuetRoute, cancelRoute, pauseRoute, recoverRoute, getDeviceTastPool, getSiteDeviceTaskHistory, getRouteByTask, deleteRoute, getTaskPath, createConsecutiveTasks, cancelConsecutiveTask, getConsecutiveTask, modeChage, getDeviceTotalData } from '../../api/device';
import dayjs from 'dayjs';
import DraggableBox from '../Draggable';
import utils from '../../lib/utils';
@@ -17,6 +17,11 @@ import { getStationRegions } from '@/api/stationManage';
import { Reorder } from 'motion/react';
import { MapEditorView } from './MapEditorView';
import type { ViewStats } from './WayLineView';
import { backToRestPointCommand } from '@/api/mapEdit';
import { sendEmergencyStop, subscribeEmergencyStop, syncEmergencyStop } from './emergencyStopControl';
import AgrtcRoomRobot from '../AgrtcRoomRobot.js';
import { deviceRunParamSelectByDeviceId } from '@/api/stationManage/index.js';
const { Text, Title } = Typography;
const { RangePicker } = DatePicker;
@@ -48,6 +53,9 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const [excuteStatus, setExcuteStatus] = useState("stop"); //"stop" "running" "pause"
// 全量设备实时状态(mapPush),实时数据统一从这里取
const [realtimeMap, setRealtimeMap] = useState<any>({});
// 急停锁存状态:与 DPad / 手柄 / 设备控制页共用同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
const [execute, setExecute] = useState(false); // 是否执行任务
const [taskList, setTaskList] = useState([]);
const { modal } = App.useApp();
@@ -55,13 +63,13 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const [detectReportInfo, setDeportInfo] = useState<any>(null);
const [selectedDeviceMap, setSelectedDeviceMap] = useState<Record<string, string>>({});
const [consecutiveTaskList, setConsecutiveTaskList] = useState([]);
const [deviceStatistics, setDeviceStatistics] = useState<any>({});
// 设备数据
const [devices, setDevices] = useState([]);
const [deleteLoading, setDeleteLoading] = useState(false);
@@ -79,6 +87,8 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const [routeSearch, setRouteSearch] = useState('');
const [routeList, setRouteList] = useState([]);
// 任务下发:按模式分组的路线(折叠面板使用)
const dispatchRouteGroups = useMemo(() => groupRoutesByMode(routeList, t), [routeList, t]);
const [consecutiveLoading, setConsecutiveLoading] = useState(false);
// 执行任务弹窗
@@ -101,6 +111,7 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
// 当前激活的Tab
const [activeTab, setActiveTab] = useState('pool'); // 'task' for 任务列表, 'pool' for 任务池, 'history' for 历史任务
const [cameraNum, setCameraNum] = useState(0);
// 任务池和历史任务筛选表单
const [poolFilterForm, setPoolFilterForm] = useState({
@@ -211,18 +222,6 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
const controllerRef = useRef<DeviceController | null>(null);
const isFirstConnect = useRef(true);
const mapRef = useRef(null);
const fixStatusMap: Record<string, string> = {
'no_fix': t('devices.noFix'),
'single': t('devices.single'),
'dgnss': t('devices.dgnss'),
'ins': t('devices.ins'),
'rtk_fixed': t('devices.rtkFixed'),
'rtk_float': t('devices.rtkFloat'),
'single_no_heading': t('devices.singleNoHeading'),
'dgnss_no_heading': t('devices.dgnssNoHeading'),
'rtk_fixed_no_heading': t('devices.rtkFixedNoHeading'),
'rtk_float_no_heading': t('devices.rtkFloatNoHeading'),
}
const handleFinish = (data) => {
@@ -349,17 +348,57 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
}, []);
// 切换场站时统一清理旧场站残留:地图画线、机器、实时数据、任务执行状态等
useEffect(() => {
if (!stationId) return;
// 清空地图上所有画的线、打点、规划点、规划区域
setPolyPoints([]);
setPoints([]);
setProPoints({});
setRouteMode('');
setClearNavLine(v => v + 1);
setClearPlanLine(v => v + 1);
setNum(v => v + 1);
setFocusLocation(null);
// 清空上一个场站的设备/实时数据
setDevices([]);
setRealtimeMap({});
// 清空上一个场站的任务执行与机器状态
setExecute(false);
setExecutingRobot(null);
setShowVideo(false);
setRunningPoolTask(null);
setExcuteStatus('stop');
// 清空上一个场站的任务下发选择
setDispatchRouteIds([]);
setDispatchRobotSns([]);
setSelectedRouteForExecute(null);
setSelectedRobotForExecute(null);
setExecuteModalVisible(false);
// 清空地图编辑器区域选中
setEditorType(null);
}, [stationId]);
// 全量设备实时状态 WebSocket(mapPush):实时数据统一从这里获取,退出页面断开连接
useEffect(() => {
if (!userInfo || !stationId || !controllerRef.current) return;
const controller = controllerRef.current;
controller.siteId = stationId;
// 切换场站时先清空上一站的实时缓存,避免跨站脏数据残留
setRealtimeMap({});
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
return () => {
controller.closeMapPush?.();
};
}, [userInfo, stationId]);
// 监听任务列表和设备列表变化,自动连接正在执行中的机器人(仅在没有选择任务时)
useEffect(() => {
if (!taskPoolList || taskPoolList.length == 0) {
@@ -430,10 +469,12 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
if (!rt) return null;
return {
...rt,
longitude: rt.lng,
latitude: rt.lat,
fix_status: rt.fixStatus,
controlMode: rt.controlMode ?? targetRobot?.lastRunningStatus?.controlMode,
longitude: rt?.lng,
latitude: rt?.lat,
fix_status: rt?.fixStatus,
controlMode: rt?.controlMode ?? rt?.control_mode ?? targetRobot?.lastRunningStatus?.controlMode,
sm: rt?.sm,
e: rt?.emergencyStop,
};
}, [realtimeMap, targetRobot]);
@@ -727,6 +768,10 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
});
};
useEffect(() => {
syncEmergencyStop(robotRealtimePosition?.emergencyStop);
}, [robotRealtimePosition?.emergencyStop]);
@@ -1329,16 +1374,60 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
}];
// 向合并页面汇报统计口径(与无人机任务统计合并展示)
useEffect(() => {
const workingCount = taskPoolList?.filter(item => ['EXECUTING', 'PAUSE'].includes(item.taskStaus))?.length || 0;
if (!selectedMachineSn) return;
const params = {
deviceId: selectedMachineSn,
};
getDeviceTotalData(params).then((res) => {
if (res.code === 200) {
setDeviceStatistics(res.data || {});
}
});
const id = selectedMachineSn;
if (!id || !stationId) {
setCameraNum(1);
return;
}
let cancelled = false;
deviceRunParamSelectByDeviceId({ deviceId: id }).then((res) => {
if (cancelled) return;
if (res?.code === 200) {
const n = Number(res.data?.cameraNum);
setCameraNum(Number.isFinite(n) && n >= 1 && n <= 4 ? n : 1);
console.log('[DSP] deviceRunParam res.data=', res.data);
} else {
setCameraNum(1);
}
}).catch(() => {
if (!cancelled) setCameraNum(1);
});
return () => { cancelled = true; };
}, [selectedMachineSn]);
useEffect(() => {
const workingCount = taskPoolList?.filter(item =>
['EXECUTING', 'PAUSE'].includes(item.taskStaus)
)?.length || 0;
onStatsChange?.({
planTotal: taskList.length,
working: workingCount,
finishCount: successfulTaskList.length,
totalCount: taskHistoryList.length,
...deviceStatistics,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [taskList.length, taskPoolList, successfulTaskList.length, taskHistoryList.length]);
}, [
taskList.length,
taskPoolList,
successfulTaskList.length,
taskHistoryList.length,
deviceStatistics,
]);
// ===== 分区列表 =====
useEffect(() => {
@@ -1361,6 +1450,28 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
return (routeList || []).filter(rt => ids.has(rt.id));
}, [regionList, dispatchRegionIds, routeList]);
const handleAutoBack = () => {
const payload = {
deviceId: selectedMachineSn,
orgId: currentStation?.orgId,
siteId: stationId,
}
backToRestPointCommand(payload).then(res => {
if (res.code == 200) {
messageApi.success(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2'));
} else {
messageApi.error(res.msg || t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2Failed2'));
}
}).catch(err => {
console.error('返回休息点失败', err);
})
}
// 急停:与 DPad 保持一致,调用共享锁存接口(再次点击解除)
const handleEmergencyStop = () => {
sendEmergencyStop(selectedMachineSn || targetRobot?.serialNumber || '');
};
// 选中的路径对象列表(用于拖拽排序显示)
const selectedRouteObjects = useMemo(() => {
// 根据 dispatchRouteIds 的顺序返回路径对象
@@ -1720,8 +1831,8 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
points,
polyPoints,
routeMode,
realtimePosition,
realtimeDevice: targetRobot ? { ...targetRobot, color: robotMapColor } : targetRobot,
realtimePosition: robotRealtimePosition ? realtimePosition : null,
realtimeDevice: targetRobot ? { ...targetRobot, ...(robotRealtimePosition || {}), color: robotMapColor } : targetRobot,
deviceColor: robotMapColor,
realtimeType: 'robot',
ifClearNavLine: clearNavLine,
@@ -1735,8 +1846,8 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
onSave={() => fetchRouteList()}
/>
{/* 机器人状态悬浮面板 - 绝对定位左上角 */}
{execute && executingRobot && (
{/* 机器人操作面板(状态信息改为鼠标悬浮机器时在地图上显示) */}
{targetRobot && (
<div
style={{
position: 'absolute',
@@ -1759,13 +1870,15 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
}}
>
<span style={{ fontWeight: 600 }}>
🤖 {executingRobot.deviceAlias || executingRobot.serialNumber}
🤖 {targetRobot.deviceAlias || targetRobot.serialNumber}
</span>
<span>
{t('devices.controlMode')}
{(() => {
const mode = robotRealtimePosition?.controlMode || robotRealtimePosition?.control_mode;
const mode =
robotRealtimePosition?.controlMode ??
robotRealtimePosition?.control_mode;
const modeConfig: Record<string, { label: string; color: string }> = {
'0': {
@@ -1786,6 +1899,38 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
},
};
const config =
mode !== undefined && mode !== null
? modeConfig[String(mode)]
: undefined;
return config ? (
<span style={{ color: config.color }}>
{config.label}
</span>
) : (
<span style={{ color: '#999999' }}>-</span>
);
})()}
</span>
{/*<span>
{t('devices.systemMode')}
{(() => {
const mode = robotRealtimePosition?.sm || robotRealtimePosition?.sm;
const modeConfig: Record<string, { label: string; color: string }> = {
'2': {
label: t('devices.autoTask'),
color: '#9eff9e',
},
'3': {
label: t('devices.remoteControl'),
color: '#9eff9e',
},
};
const config =
mode !== undefined && mode !== null
? modeConfig[String(mode)]
@@ -1799,15 +1944,13 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
</span>
);
})()}
</span>
</span>*/}
<span>
{t('devices.location')}
{robotRealtimePosition?.fix_status ? fixStatusMap[robotRealtimePosition?.fix_status] : t('constants.locationUnknown')}
</span>
{/* 视频开关 */}
<span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
@@ -1855,11 +1998,33 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
}}
onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.3)'}
onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.18)'}
onClick={handleAutoBack}
>
<EnvironmentOutlined />
{t('devices.features.autoback')}
</span>
<span
onClick={handleEmergencyStop}
style={{
display: 'flex',
alignItems: 'center',
gap: 4,
padding: '3px 10px',
background: eStopActive ? '#cf1322' : 'rgba(255,255,255,0.18)',
borderRadius: 12,
cursor: 'pointer',
whiteSpace: 'nowrap',
fontWeight: 600,
transition: 'background 0.2s',
}}
onMouseEnter={e => { if (!eStopActive) e.currentTarget.style.background = 'rgba(255,255,255,0.3)'; }}
onMouseLeave={e => { e.currentTarget.style.background = eStopActive ? '#cf1322' : 'rgba(255,255,255,0.18)'; }}
>
<ExclamationCircleOutlined />
{eStopActive ? t('devices.estopTriggered') : t('devices.features.emergencyStop')}
</span>
</div>
)}
@@ -2237,7 +2402,7 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
<div style={{ fontWeight: 600, marginBottom: 8 }}>{t('devices.dispatchSource')}</div>
<Radio.Group value={dispatchSource} onChange={e => { setDispatchSource(e.target.value); setDispatchRouteIds([]); setDispatchRegionIds([]); }} buttonStyle="solid">
<Radio.Button value="route">{t('devices.dispatchByRoute')}</Radio.Button>
<Radio.Button value="region">{t('devices.dispatchByRegion')}</Radio.Button>
{/*<Radio.Button value="region">{t('devices.dispatchByRegion')}</Radio.Button>*/}
</Radio.Group>
</div>
@@ -2248,61 +2413,67 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
{(!routeList || routeList.length === 0) ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 280, overflowY: 'auto' }}>
{groupRoutesByMode(routeList, t).map(group => (
<div key={group.key}>
<div style={{ fontSize: 12, fontWeight: 600, color: group.color, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
<Collapse
size="small"
ghost
defaultActiveKey={dispatchRouteGroups.map(g => g.key)}
style={{ maxHeight: 280, overflowY: 'auto' }}
items={dispatchRouteGroups.map(group => ({
key: group.key,
label: (
<div style={{ fontSize: 12, fontWeight: 600, color: group.color, display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: group.color }} />
{group.label}
<span style={{ color: '#999', fontWeight: 400, fontSize: 11 }}>({group.items.length})</span>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
),
children: (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{group.items.map(route => {
const checked = dispatchRouteIds.includes(route.id);
return (
<Tag.CheckableTag
<div
key={route.id}
checked={checked}
style={{
display: 'inline-flex',
alignItems: 'center',
border: `1px solid ${checked ? '#1677ff' : '#dce5f2'}`,
background: checked ? '#f0f7ff' : '#fff',
color: '#344054',
borderRadius: 4,
padding: '3px 12px',
margin: 0,
fontSize: 12,
lineHeight: '20px',
whiteSpace: 'nowrap',
}}
onChange={nextChecked => {
// 按路线下发:单选
setDispatchRouteIds(nextChecked ? [route.id] : []);
if (nextChecked) {
// 选择下发路径时,取消上方任务规划的选中
onClick={() => {
// 按路线下发:单选,一行一个;再次点击可取消
setDispatchRouteIds(checked ? [] : [route.id]);
if (!checked) {
setEditorType(null);
flyToRoute(route.id);
}
}}
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
width: '100%',
boxSizing: 'border-box',
padding: '6px 10px',
borderRadius: 6,
cursor: 'pointer',
border: `1px solid ${checked ? '#1677ff' : '#e5e6eb'}`,
background: checked ? '#f0f7ff' : '#fff',
fontSize: 12,
color: '#344054',
transition: 'all .15s',
}}
>
<span
style={{
color: '#344054',
display: 'inline-block',
}}
>
{route.workName || route.name}
</span>
</Tag.CheckableTag>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: group.color, flex: '0 0 auto' }} />
{route?.imgUrl && (
<img
src={route.imgUrl}
alt=""
style={{ width: 20, height: 20, objectFit: 'cover' }}
/>
)} <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{route.workName || route.name}</span>
{checked && <span style={{ color: '#1677ff', fontWeight: 700 }}>✓</span>}
</div>
);
})}
</div>
</div>
))}
</div>
)
}))}
/>
)}
</div>
)}
@@ -2810,7 +2981,7 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
</div>
<Button onClick={handleDispatchCancel}>{t('common.cancel')}</Button>
<Button type="primary" style={{ flex: 1 }} loading={dispatchLoading} onClick={handleDispatchTask}>
<Button type="primary" style={{ flex: 1 }} loading={dispatchLoading} onClick={handleDispatchTask} disabled={dispatchLoading}>
{dispatchMode === 'immediate' ? t('devices.taskExecuteNow') : t('devices.taskSaveSchedule')}
</Button>
</div>
@@ -2957,22 +3128,18 @@ export function TaskPlanningView({ selectedMachineSn, embedded = false, onStatsC
</Row>*/}
{/*{showVideo && executingRobot && execute && taskPoolList.length > 0 && (
{showVideo && (
<DraggableBox
defaultPosition={{ x: 50, y: 50 }}
title={t('devices.robotPanoramaVideo', { robot: executingRobot.deviceAlias || executingRobot.serialNumber })}
title={t('devices.robotPanoramaVideo', { robot: targetRobot.deviceAlias || targetRobot.serialNumber })}
onClose={() => setShowVideo(false)}
>
<div style={{ height: '100%', width: '100%' }}>
<MowerAllView
serialNumber={executingRobot.serialNumber}
robotVideo={robotVideo}
ready={ready}
error={error}
/>
<AgrtcRoomRobot channel={targetRobot?.serialNumber || targetRobot?.device_sn || ""} cameraCount={cameraNum} />
</div>
</DraggableBox>
)}*/}
)}
</div >
);
}

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
Row, Col, Card, Button, Space, Table, Tag, Typography, Progress, Badge,
Tabs, Input, Switch, Divider, Tooltip, Timeline, Select, message, DatePicker,

View File

@@ -1,6 +1,7 @@
import React, { useEffect, useState, useRef } from 'react';
import { sendEmergencyStop, subscribeEmergencyStop } from './emergencyStopControl';
import { useTranslation } from 'react-i18next';
const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
const XboxController = ({ onGamepadUpdate, onConnectionChange, deviceId }: { onGamepadUpdate?: any; onConnectionChange?: any; deviceId?: string }) => {
const { t } = useTranslation();
const [gamepadState, setGamepadState] = useState<{
buttons: boolean[];
@@ -23,19 +24,94 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
const lastSendRef = useRef(0);
const SEND_INTERVAL = 1000 / 10; // 20Hz
const lastPayloadRef = useRef('');
// 物理按键上一帧状态(上升沿检测)
const lastButtonsRef = useRef<boolean[]>(new Array(17).fill(false));
const [eStopActive, setEStopActive] = useState(false);
const eStopActiveRef = useRef(false);
eStopActiveRef.current = eStopActive;
// 锁存状态:底盘升降 / 点火熄火,同组互斥(不会同时显示为按下)
// 割刀不锁存:按下 X → button2=true,按下 Y → button2=false,都没按 → button2=null
const [latchState, setLatchState] = useState<{
chassisUp: boolean;
chassisDown: boolean;
ignition: boolean;
shutdown: boolean;
}>({
chassisUp: false,
chassisDown: false,
ignition: false,
shutdown: false,
});
const latchRef = useRef(latchState);
latchRef.current = latchState;
// 订阅急停锁存状态变化:任何入口触发急停都能同步到按钮视觉
useEffect(() => {
const unsub = subscribeEmergencyStop((val) => setEStopActive(val));
return unsub;
}, []);
const updateGamepad = () => {
const gp = navigator.getGamepads()[0];
if (gp) {
const physical = gp.buttons.map(b => b.pressed);
const prev = lastButtonsRef.current;
const axes = gp.axes.map(normalizeAxis);
// 上升沿:底盘(A 升 / B 降)、点火熄火(LB / RB),同组按键互斥
const next = { ...latchRef.current };
if (physical[0] && !prev[0]) {
next.chassisUp = !next.chassisUp;
if (next.chassisUp) next.chassisDown = false;
}
if (physical[1] && !prev[1]) {
next.chassisDown = !next.chassisDown;
if (next.chassisDown) next.chassisUp = false;
}
if (physical[4] && !prev[4]) {
next.ignition = !next.ignition;
if (next.ignition) next.shutdown = false;
}
if (physical[5] && !prev[5]) {
next.shutdown = !next.shutdown;
if (next.shutdown) next.ignition = false;
}
// button8 (急停) 上升沿 → 调接口,不走 WebSocket
if (physical[8] && !prev[8] && deviceId) {
sendEmergencyStop(deviceId);
}
lastButtonsRef.current = physical;
const latchChanged =
next.chassisUp !== latchRef.current.chassisUp ||
next.chassisDown !== latchRef.current.chassisDown ||
next.ignition !== latchRef.current.ignition ||
next.shutdown !== latchRef.current.shutdown;
if (latchChanged) {
latchRef.current = next;
setLatchState(next);
}
const latch = latchChanged ? next : latchRef.current;
// 割刀:按下 X → button2=true,按下 Y → button2=false,两个都没按 → button2=null
const bladeValue = physical[2] ? true : physical[3] ? false : null;
// 锁存状态写入发送帧
const wsButtons: any[] = physical.slice();
wsButtons[0] = latch.chassisUp;
wsButtons[1] = latch.chassisDown;
wsButtons[2] = bladeValue;
wsButtons[3] = false; // Y 仅作为"割刀停止"指令,不再透传为按键
wsButtons[4] = latch.ignition;
wsButtons[5] = latch.shutdown;
wsButtons[8] = false;
// 手柄图形显示:割刀启动/停止同一时刻只点亮一个
const displayButtons = wsButtons.slice();
displayButtons[3] = !physical[2] && physical[3];
const state = {
buttons: gp.buttons.map(b => b.pressed),
axes: gp.axes.map(normalizeAxis),
buttons: displayButtons,
axes,
connected: true,
ts: Date.now(),
};
setGamepadState(state);
const payload = JSON.stringify({
buttons: state.buttons,
axes: state.axes,
buttons: wsButtons,
axes,
});
const now = performance.now();
if (
@@ -81,6 +157,10 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
console.log('❌ Gamepad disconnected');
//handleControlModal({ control: false });
setGamepadState(prev => ({ ...prev, connected: false }));
// 断开连接时清空锁存,避免按钮残留为按下状态
const reset = { chassisUp: false, chassisDown: false, ignition: false, shutdown: false };
latchRef.current = reset;
setLatchState(reset);
};
window.addEventListener('gamepadconnected', handleConnect);
window.addEventListener('gamepaddisconnected', handleDisconnect);
@@ -177,15 +257,17 @@ const XboxController = ({ onGamepadUpdate, onConnectionChange }) => {
<circle cx="-20" cy="0" r="12" fill={buttons[2] ? "#3b82f6" : "#0f172a"} stroke="#3b82f6" strokeWidth="1" opacity={buttons[2] ? 1 : 0.6} /> {/* X */}
<text x="-20" y="4" textAnchor="middle" fill={buttons[2] ? "#fff" : "#3b82f6"} fontSize="14" fontWeight="bold">X</text>
<circle cx="0" cy="-20" r="12" fill={buttons[3] ? "#eab308" : "#0f172a"} stroke="#eab308" strokeWidth="1" opacity={buttons[3] ? 1 : 0.6} /> {/* Y */}
<circle cx="0" cy="-20" r="12" fill={buttons[3] ? "#eab308" : "#0f172a"} stroke="#eab308" strokeWidth="1" opacity={buttons[3] ? 1 : 0.6} /> Y
<text x="0" y="-16" textAnchor="middle" fill={buttons[3] ? "#fff" : "#eab308"} fontSize="14" fontWeight="bold">Y</text>
</g>
{/* Menu Buttons + Text Label button8=急停, button9=Menu */}
<circle cx="180" cy="140" r="6" fill={buttons[8] ? "#22d3ee" : "#334155"} />
<text x="180" y="152" textAnchor="middle" fill={buttons[8] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold">急停</text>
{/* Emergency Stop button 急停 */}
<circle cx="180" cy="140" r="14" fill={eStopActive || buttons[8] ? "#dc2626" : "#7f1d1d"} stroke={eStopActive || buttons[8] ? "#fca5a5" : "#991b1b"} strokeWidth="2" style={eStopActive || buttons[8] ? { filter: 'drop-shadow(0 0 8px #ef4444)' } : { filter: 'drop-shadow(0 0 2px #450a0a)' }} />
<text x="180" y="144" textAnchor="middle" fill={eStopActive || buttons[8] ? "#ffffff" : "#fca5a5"} fontSize="10" fontWeight="900">STOP</text>
{/*<text x="180" y="160" textAnchor="middle" fill={buttons[8] ? "#fecaca" : "#991b1b"} fontSize="7" fontWeight="bold">急停</text>*/}
<circle cx="220" cy="140" r="6" fill={buttons[9] ? "#22d3ee" : "#334155"} />
<text x="220" y="152" textAnchor="middle" fill={buttons[9] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold">Menu</text>
<text x="220" y="152" textAnchor="middle" fill={buttons[9] ? "#22d3ee" : "#64748b"} fontSize="9" fontWeight="bold"></text>
</svg>
</div>
);

View File

@@ -51,6 +51,7 @@ export default class DeviceController {
this.onIsExecuting = null;
this.handleArrivedPoint = null;
this.onDetectionReport = null;
this.onDeviceErrorPush = null;
// 全量设备实时状态(mapPush)连接
this.mapPushWs = null;
@@ -134,6 +135,7 @@ export default class DeviceController {
const key = String(it?.id ?? '');
if (!key) return;
next[key] = {
...it,
id: key,
lng: String(it?.lng ?? it?.lon ?? it?.longitude),
lat: String(it?.lat ?? it?.latitude),
@@ -149,6 +151,8 @@ export default class DeviceController {
controlMode: it?.cm ?? it?.controlMode,
progress: it?.p ?? it?.progress,
workName: it?.wk ?? null,
sm: it?.sm ?? null,
emergencyStop: it?.e
};
});
@@ -160,6 +164,7 @@ export default class DeviceController {
console.log('task finish');
this.onIsFinished?.(msg);
} else {
console.log("device_task_change", msg.status)
this.onIsExecuting?.(true);
}
@@ -172,6 +177,53 @@ export default class DeviceController {
this.deviceStatusChangedMsg?.(msg);
}
if (msg?.type == 'device_error_push') {
console.log('device_error_push', msg);
const list = Array.isArray(msg?.alarms)
? msg.alarms
: Array.isArray(msg?.data?.alarms)
? msg.data.alarms
: Array.isArray(msg?.data) ? msg.data : [];
const levelMap = { 1: 'ERROR', 2: 'WARNING', 3: 'INFO', 4: 'INFO' };
// 后端 LocalDateTime 以数组 [年,月,日,时,分,秒,纳秒] 下发,需单独转换
const formatAlarmTime = (time) => {
if (time === null || time === undefined || time === '') return '';
if (Array.isArray(time)) {
const [y, mo, d, h = 0, mi = 0, se = 0] = time;
if (!y) return '';
const dt = dayjs(new Date(y, mo - 1, d, h, mi, se));
return dt.isValid() ? dt.format('YYYY-MM-DD HH:mm:ss') : '';
}
const dt = dayjs(time);
return dt.isValid() ? dt.format('YYYY-MM-DD HH:mm:ss') : String(time);
};
// alarmTitle 若为编码(如 SAFETY_FAULT_HEARTBEAT_TIMEOUT),改用 alarmContent 中文描述
const isAlarmCode = (val) => typeof val === 'string' && /^[A-Z][A-Z0-9_]*$/.test(val);
const alarms = list.map((a) => {
if (!a || typeof a !== 'object') return null;
// 统一告警级别:后端 ErrorLevel 1严重/2重要/3一般/4提示 → ERROR/WARNING/INFO
const rawLevel = a.alertLevel ?? a.alarmLevel;
const alertLevel = typeof rawLevel === 'number'
? (levelMap[rawLevel] || 'INFO')
: String(rawLevel || 'INFO').toUpperCase();
const rawTitle = a.alarmTitle;
const alarmTitle = (isAlarmCode(rawTitle) ? (a.alarmContent || rawTitle) : (rawTitle || a.alarmContent)) || a.alarmNo || '';
return {
...a,
alertLevel,
alarmTitle,
handleStatus: a.handleStatus ?? 1,
alarmTime: formatAlarmTime(a.alarmTime),
};
}).filter(Boolean);
if (alarms.length) {
this.onDeviceErrorPush?.({
deviceId: msg?.deviceId || msg?.data?.deviceId,
alarms,
});
}
}
if (msg?.type == 'route_post') {
console.log('route_post');
this.onRoutePost?.(msg);

View File

@@ -1,28 +1,80 @@
import { wsManager } from '../WebSocketManager';
import utils from '../../lib/utils';
import { eStopChange } from '../../api/device';
// 急停对应手柄 button7(buttons 数组下标 7)
const EMERGENCY_STOP_BUTTON_INDEX = 7;
// 本地锁存状态
let active = false;
const listeners = new Set<(val: boolean) => void>();
// 构建单帧遥控数据:仅急停位按下/松开,其余按键与摇杆轴保持空闲
const buildFrame = (pressed: boolean) => {
const buttons = new Array(17).fill(false);
buttons[EMERGENCY_STOP_BUTTON_INDEX] = pressed;
return { buttons, axes: [0, 0, 0, 0], connected: true, ts: Date.now() };
const emit = () => {
for (const fn of listeners) {
try { fn(active); } catch { }
}
};
/**
* 单击急停:绕过控制权限校验,直接经 WebSocket 下发 button7;
* 约 300ms 后自动补发一帧复位数据,模拟按下再松开。
*/
export const sendEmergencyStop = (userInfo?: any) => {
const send = (pressed: boolean) =>
wsManager.send({
type: 'remoteControl',
remoteData: buildFrame(pressed),
token: userInfo?.token,
userName: userInfo?.username,
/** 订阅急停锁存状态变化,返回 unsubscribe */
export const subscribeEmergencyStop = (fn: (val: boolean) => void) => {
listeners.add(fn);
fn(active); // 立即回调一次当前值
return () => listeners.delete(fn);
};
/** 由实时数据(runningStatus.emergency_stop)同步急停状态,只更新本地显示,不发请求 */
export const syncEmergencyStop = (val: any) => {
// 兼容后端可能下发的 boolean / 1 / 0 / "true" / "false"
if (val === undefined || val === null || val === '') return;
const next = val === true || val === 1 || val === '1' || val === 'true';
if (active === next) return;
active = next;
emit();
};
/** 切换急停状态(toggle) */
export const sendEmergencyStop = async (deviceId: string) => {
if (!deviceId) return active;
const newActive = !active;
console.log('[EmergencyStop] eStop=' + (newActive ? 1 : 0) + ' sending');
try {
const res = await eStopChange({
deviceId,
eStop: newActive ? 1 : 0
});
if (res?.code == 200) {
active = newActive;
emit();
utils.message.success('急停状态切换成功');
send(true);
setTimeout(() => send(false), 300);
console.log('[EmergencyStop] eStop=' + (active ? 1 : 0) + ' success');
} else {
utils.message.error('急停状态切换失败');
console.warn('[EmergencyStop] eStop failed:', res);
}
} catch (err) {
console.error('[EmergencyStop] eStop request error:', err);
}
return active;
};
export const toggleEmergencyStop = sendEmergencyStop;
export const startEmergencyStop = async (deviceId: string) => {
if (!deviceId || active) return;
await sendEmergencyStop(deviceId);
};
export const stopEmergencyStop = async (deviceId: string) => {
if (!deviceId || !active) return;
await sendEmergencyStop(deviceId);
};
export const isEmergencyStopActive = () => active;
if (typeof window !== 'undefined') {
window.addEventListener('beforeunload', () => {
active = false;
emit();
});
}

View File

@@ -198,4 +198,8 @@ h4, .ant-typography h4 { font-size: clamp(1rem, 1.5vw, 1.25rem) !important; }
}
}
.badge-rtc-connected .ant-badge-status-text{
color:#fff !important
}

View File

@@ -352,8 +352,11 @@
robotRouteMonitor: 'Robot Path Planning & Monitoring',
clearRealtimeTrack: 'Clear Track',
clearPlanRoute: 'Clear Planned Route',
controlMode: 'Control Mode:',
controlMode: 'RemoteControlStatus',
personFollow: 'Person Follow',
localMode: 'Local',
systemMode: 'System Mode',
remoteMode: 'Remote',
heading: 'Heading:',
initialized: 'Initialized',
@@ -489,6 +492,7 @@
autoFetch: 'Auto Fetch',
autoResumeFromBreakpoint: 'Auto Resume From Breakpoint',
backView: 'Back View',
showGuideLine: "Show Guide Line",
batteryCapacity: 'Battery Capacity',
batteryWithPercent: 'Battery with Percent',
batteryWithValue: 'Battery with Value',
@@ -679,6 +683,8 @@
lbDesc: 'Ignition',
rbKey: 'RB',
rbDesc: 'Shut Down',
Stop: "Emergency Stop",
},
steer: {
ignition: 'Ignition',
@@ -703,6 +709,7 @@
findCar: 'Find Car',
autoback: 'Auto Back',
controlMode: 'Control Mode Switch',
personFollow: 'Person Follow',
},
dpad: {
title: 'Direction Control',
@@ -1560,7 +1567,10 @@
fixed2TaskSuspended22: 'Fixed2 Task Suspended2 已启动',
fixed2ReturnHomeFixed2CommandIssuedFixed2: 'Fixed2 Return Home Fixed2 Command Issued Fixed2',
fixed2ReturnHomeFixed2CommandIssuedFixed2: 'Return Home Command Issued ',
switchControl: 'switchControl',
onRemoteControl: "onRemoteControl",
fixed2ReturnHomeFixed2CommandIssuedFixed2Failed: 'Return Home Command Issued Failed ',
commandIssuedFixed2: '回充 Command Issued Fixed2',

View File

@@ -341,7 +341,7 @@ const zh = {
thu: '周四',
fri: '周五',
sat: '周六',
planByDay: '按天 | 开始日期{{startDate}} {{dayTime}}',
planByDay: '按天 | 开始时间{{startDate}} {{dayTime}}',
planByWeek: '按周 | {{weekText}} {{dayTime}}',
planByMonth: '按月 | {{monthText}} {{dayTime}}',
daySuffix: '{{day}}日',
@@ -375,7 +375,7 @@ const zh = {
robotRouteMonitor: '机器人路径规划与监控',
clearRealtimeTrack: '清空实时轨迹',
clearPlanRoute: '清空规划区域',
controlMode: '控制模式:',
controlMode: '遥控器状态:',
localMode: '本地',
remoteMode: '远程',
heading: '航向:',
@@ -513,6 +513,7 @@ const zh = {
autoFetch: '自动获取',
autoResumeFromBreakpoint: '自动恢复从断点',
backView: '后视角',
showGuideLine: "显示辅助线",
batteryCapacity: '电量容量',
batteryWithPercent: '电量带百分比',
batteryWithValue: '电量带值',
@@ -707,13 +708,14 @@ const zh = {
bKey: 'B 键',
bKeyDesc: '降底盘',
xKey: 'X 键',
xKeyDesc: '割刀加速',
xKeyDesc: '割刀启动',
yKey: 'Y 键',
yKeyDesc: '割刀减速',
yKeyDesc: '割刀停止',
lbKey: 'LB 键',
lbDesc: '点火',
rbKey: 'RB 键',
rbDesc: '熄火',
Stop: "急停",
},
steer: {
ignition: '点火',
@@ -725,8 +727,8 @@ const zh = {
chassisDown: '底盘下降',
chassisDownHint: '底盘下降',
cutterControl: '割刀控制',
cutterAccel: '割刀加速',
cutterDecel: '割刀减速',
cutterAccel: '割刀启动',
cutterDecel: '割刀停止',
},
features: {
title: '功能控制',
@@ -738,6 +740,7 @@ const zh = {
findCar: '寻车',
autoback: '返航',
controlMode: '控制模式切换',
personFollow: '智能跟随',
},
@@ -988,6 +991,7 @@ const zh = {
rtLeftTemp: '左电机温度',
rtMainTemp: '芯片温度',
rtMode: '控制模式',
systemMode: '系统模式',
rtPitchAngle: '俯仰角度',
rtRollAngle: '翻滚角度',
rtPositioning: '定位',
@@ -1400,6 +1404,9 @@ const zh = {
fixed2TaskSuspended22: '任务已启动',
fixed2ReturnHomeFixed2CommandIssuedFixed2: '返航指令已下发',
fixed2ReturnHomeFixed2CommandIssuedFixed2Failed2: '返航指令下发失败',
commandIssuedFixed2: '回充指令已下发',
@@ -1523,9 +1530,13 @@ const zh = {
"ultrasonicPresent": "超声波在位",
"dacPresent": "DAC在位",
"operator": "质检员",
onRemoteControl: "当前正处于远程控制状态",
"inspectionNo": "检测报告号",
"activeTime": "激活时间",
"dealer": "经销商",
switchControl: '请先模式切换',
taskConsecutive: '连续任务',
paramEnum: {
@@ -1872,6 +1883,8 @@ const zh = {
handled: '已处理',
restored: '已恢复',
ignored: '已忽略',
ignore: "忽略",
unableToHandle: '无法处理',
manufacturerHandling: '厂家处理中',
falseAlarm: '误报',

432
src/pages/Agri.css Normal file
View File

@@ -0,0 +1,432 @@
/* 农业AI算法分析页面样式(由 Agri.jsx 内联样式外联而来) */
/* ===== 页面骨架 ===== */
.agri-page {
padding: 8px;
background: #f4f7f9;
min-height: 100vh;
}
.agri-page-header {
display: flex;
justify-content: space-between;
align-items: center;
padding-bottom: 16px;
}
.agri-page-title.ant-typography {
margin: 0;
font-size: clamp(18px, 1.5vw, 24px);
color: #1D2129;
}
.agri-main-row.ant-row {
flex-wrap: wrap;
}
/* ===== 顶部统计卡片 ===== */
.agri-stats-row.ant-row {
margin-bottom: 8px;
}
.agri-stat-card.ant-card {
height: 100%;
}
.agri-stat-card.ant-card .ant-card-body {
padding: 20px 16px;
}
.agri-stat-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
}
.agri-stat-main {
flex: 1;
}
.agri-stat-title {
font-size: clamp(12px, 0.8vw, 13px);
color: #86909C;
margin-bottom: 8px;
white-space: nowrap;
}
.agri-stat-value {
font-size: clamp(20px, 1.4vw, 24px);
font-weight: 800;
color: var(--agri-stat-value-color);
display: flex;
align-items: baseline;
gap: 4px;
}
.agri-stat-unit {
font-size: 13px;
font-weight: 400;
color: #86909C;
}
.agri-stat-icon-box {
width: 44px;
height: 44px;
background: var(--agri-stat-icon-bg);
border-radius: 12px;
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
box-shadow: var(--agri-stat-icon-shadow);
}
/* ===== 通用间距 ===== */
.agri-mb-16 {
margin-bottom: 16px;
}
.agri-mt-16.ant-row,
.agri-mt-16.ant-space {
margin-top: 16px;
}
.agri-mt-24,
.agri-mt-24.ant-space {
margin-top: 24px;
}
/* ===== 检测/分割工作区 ===== */
.agri-workspace-pane {
padding: 0 8px;
}
.agri-model-label.ant-typography {
font-size: 15px;
}
.agri-model-select.ant-select {
width: 100%;
margin-top: 8px;
}
.agri-field-label.ant-typography {
font-size: 13px;
display: block;
margin-bottom: 8px;
}
.agri-field-hint.ant-typography {
font-size: 12px;
display: block;
}
.agri-full-width.ant-input-number,
.agri-full-width.ant-select {
width: 100%;
}
.agri-detect-dragger.ant-upload-wrapper .ant-upload-drag {
background: #fafafa;
border-radius: 8px;
}
.agri-seg-dragger.ant-upload-wrapper .ant-upload-drag {
background: #fafafa;
border-radius: 8px;
height: 120px;
}
.agri-upload-icon.anticon {
color: #1677ff;
}
.agri-seg-drag-icon.ant-upload-drag-icon {
font-size: 24px;
}
.agri-seg-upload-hint {
font-size: 12px;
}
/* ===== 结果卡片标题/提示 ===== */
.agri-card-title.ant-typography {
font-size: 14px;
}
.agri-card-extra.ant-typography {
font-size: 11px;
}
.agri-json-hint.ant-typography {
font-size: 11px;
display: block;
margin-bottom: 12px;
}
.agri-note-hint.ant-typography {
font-size: 11px;
margin-bottom: 12px;
}
.agri-workspace-intro.ant-typography {
font-size: 11px;
display: block;
margin-bottom: 16px;
}
.agri-result-card.ant-card {
margin-top: 12px;
border-radius: 8px;
}
.agri-result-card.ant-card .ant-card-body {
padding: 12px;
}
.agri-preview-card.ant-card {
height: 480px;
}
.agri-side-card.ant-card {
border-radius: 8px;
height: 100%;
}
.agri-side-card.ant-card .ant-card-body {
padding: 8px;
}
.agri-workspace-card.ant-card {
border-radius: 8px;
}
.agri-workspace-card.ant-card .ant-card-body {
padding: 16px;
}
.agri-detail-card.ant-card {
height: 400px;
}
.agri-detail-card.ant-card .ant-card-body {
height: 350px;
}
/* ===== 媒体/JSON 展示区 ===== */
.agri-media-stage {
height: 400px;
background: #001529;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.agri-result-stage {
height: 400px;
display: flex;
align-items: center;
justify-content: center;
background: #fafafa;
}
.agri-json-stage {
height: 400px;
overflow-y: auto;
background: #fafafa;
padding: 8px;
}
.agri-json-pre {
font-size: 10px;
margin: 0;
}
.agri-media-fit {
max-width: 100%;
max-height: 100%;
}
/* ===== 分割结果:顶部统计块 ===== */
.agri-stat-tile.ant-card {
border-radius: 8px;
height: 100%;
}
.agri-stat-tile.ant-card .ant-card-body {
padding: 12px 8px;
}
.agri-stat-tile-green.ant-card {
background: #E8FFEA;
}
.agri-stat-tile-blue.ant-card {
background: #E6F4FF;
}
.agri-stat-tile-orange.ant-card {
background: #FFF7E8;
}
.agri-stat-tile-purple.ant-card {
background: #F3E8FF;
}
.agri-stat-tile-title {
font-size: 15px;
color: #86909C;
}
.agri-stat-count-red.ant-statistic .ant-statistic-content {
font-size: 18px;
font-weight: 600;
color: #FF4D4F;
}
.agri-stat-count-blue.ant-statistic .ant-statistic-content {
font-size: 18px;
font-weight: 600;
color: #1677FF;
}
.agri-stat-count-orange.ant-statistic .ant-statistic-content {
font-size: 18px;
font-weight: 600;
color: #FF7D00;
}
.agri-stat-count-purple.ant-statistic .ant-statistic-content {
font-size: 18px;
font-weight: 600;
color: #722ED1;
}
/* ===== 分割结果:热成像图与热点 ===== */
.agri-thermal-stage {
background: #001529;
border-radius: 8px;
height: 400px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
position: relative;
}
/* ===== 分割结果:点位详情 ===== */
.agri-detail-body {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
box-sizing: border-box;
padding-bottom: 8px;
}
.agri-detail-top {
flex: 1;
min-height: 0;
overflow-y: auto;
padding-right: 4px;
box-sizing: border-box;
height: 50%;
}
.agri-detail-bottom {
flex: 1;
min-height: 0;
overflow-y: auto;
padding-right: 4px;
box-sizing: border-box;
}
.agri-detail-row {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px dashed #eee;
}
.agri-detail-divider {
height: 1px;
background: #eee;
margin: 12px 0;
flex-shrink: 0;
}
.agri-panel-item {
display: flex;
justify-content: space-between;
padding: 8px 12px;
border-radius: 4px;
margin-bottom: 4px;
background: var(--agri-panel-item-bg);
cursor: pointer;
font-size: 12px;
}
.agri-panel-temp {
color: #ff4d4f;
}
/* ===== 算法列表 ===== */
.agri-algo-item {
padding: 12px;
border-radius: 8px;
cursor: pointer;
margin-bottom: 8px;
border: 1px solid var(--agri-algo-border-color);
background: var(--agri-algo-bg);
transition: all 0.3s;
}
.agri-algo-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.agri-algo-tag.ant-tag {
margin: 0;
font-size: 10px;
}
.agri-algo-meta {
font-size: 11px;
color: #999;
margin-bottom: 4px;
}
.agri-algo-desc {
font-size: 11px;
color: #999;
}
/* ===== 历史记录 ===== */
.agri-history-item {
padding: 10px;
border-radius: 6px;
border: 1px solid #f0f0f0;
margin-bottom: 8px;
font-size: 12px;
}
.agri-history-head {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
}
.agri-history-id {
color: #999;
font-size: 11px;
margin-bottom: 4px;
}
.agri-history-time {
color: #ccc;
font-size: 10px;
}

View File

@@ -24,6 +24,7 @@ import {
} from '../api/aiAnalysis';
import utils from '../lib/utils';
import { useTranslation } from 'react-i18next';
import './Agri.css';
const { Title, Text } = Typography;
const { Dragger } = Upload;

38
src/pages/Alerts.css Normal file
View File

@@ -0,0 +1,38 @@
/* 告警中心页面样式(由 Alerts.tsx 内联样式外联而来) -- test */
.alerts-layout {
min-height: 100vh;
overflow: hidden;
}
.alerts-topbar {
display: flex;
padding-bottom: 4px;
}
.alerts-title-box {
padding: 8px 12px 0;
}
.alerts-title {
margin: 0;
font-size: clamp(14px, 1.2vw, 18px);
}
.alerts-header {
padding: 0;
border-bottom: 1px solid #f0f0f0;
position: sticky;
top: 0;
z-index: 10;
height: 40px;
line-height: 40px;
}
.alerts-content {
max-height: calc(100vh - 40px);
overflow-y: auto;
background: #f5f7fa;
scrollbar-width: none;
ms-overflow-style: none;
}

View File

@@ -8,6 +8,7 @@ import { getMenuList } from '../api/mune';
import AlarmOverview from '../components/alerts/AlarmOverview';
import { useTranslation } from 'react-i18next';
import './Alerts.css';
@@ -31,13 +32,13 @@ export default function AlarmCenterPage() {
};
return (
<Layout style={{ minHeight: '100vh', overflow: 'hidden' }}>
<div style={{ display: 'flex', paddingBottom: "4px" }}>
<div style={{ padding: '8px 12px 0' }}>
<Typography.Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.2vw, 18px)' }}>{t('router.alerts')}</Typography.Title>
<Layout className="alerts-layout">
<div className="alerts-topbar">
<div className="alerts-title-box">
<Typography.Title level={4} className="alerts-title">{t('router.alerts')}</Typography.Title>
</div>
<Header style={{ padding: 0, borderBottom: '1px solid #f0f0f0', position: 'sticky', top: 0, zIndex: 10, height: 40, lineHeight: '40px' }}>
<Header className="alerts-header">
{/*<Menu
mode="horizontal"
selectedKeys={[activeTab]}
@@ -55,10 +56,7 @@ export default function AlarmCenterPage() {
</div>
<Content style={{
maxHeight: 'calc(100vh - 40px)', overflowY: 'auto', background: '#f5f7fa',
scrollbarWidth: 'none', msOverflowStyle: 'none',
}}>
<Content className="alerts-content">
{renderTabContent()}
</Content>
</Layout>

View File

@@ -1485,6 +1485,7 @@ const RealTimeMonitorPage = () => {
console.log('[RTMonitor Feature]', feature, enabled);
}}
controlMode={pickRealtimeRecord(realtimeMap, selectedDevice)?.controlMode}
deviceId={selectedDevice?.serialNumber}
/>
</Card>

View File

@@ -28,7 +28,7 @@ import { RootState } from '../store';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import { getRobotTaskList, getSiteDevice, getDeviceTastPool, getSiteDeviceTaskHistory, getRouteByTask, getSingleRouteList, getTaskPath } from '../api/device';
import { getAlarmList, getAlarmStatistics } from '../api/alarmApi';
import { getAlarmList, getAlarmStatistics, handleAlarm } from '../api/alarmApi';
import { alarmTypeMap } from '@/constants.js';
import { useNavigate } from 'react-router-dom';
import DeviceController from '../components/devices/DeviceController';
@@ -51,6 +51,41 @@ const TASK_STATUS_MAP: Record<string, { text: string; color: string }> = {
const getTaskStatusStyle = (status?: string) =>
TASK_STATUS_MAP[String(status || '').toUpperCase()] || { text: status || '--', color: 'default' };
// 告警时间兼容:Java LocalDateTime 数组 / ISO 字符串 / 时间戳
const formatAlarmTime = (value: any, fmt = 'HH:mm:ss') => {
if (value === null || value === undefined || value === '') return '';
if (Array.isArray(value)) {
const [y, mo, d, h = 0, mi = 0, se = 0] = value;
if (!y) return '';
const dt = dayjs(new Date(y, mo - 1, d, h, mi, se));
return dt.isValid() ? dt.format(fmt) : '';
}
const dt = dayjs(value);
return dt.isValid() ? dt.format(fmt) : String(value);
};
// 告警标题:alarmTitle 是编码(如 SAFETY_FAULT_HEARTBEAT_TIMEOUT)时改用 alarmContent
const isAlarmCode = (value: any) => typeof value === 'string' && /^[A-Z][A-Z0-9_]*$/.test(value);
const getAlarmTitleText = (record: any) => {
const title = record?.alarmTitle;
return (isAlarmCode(title) ? record?.alarmContent : (title || record?.alarmContent)) || record?.alarmNo || '';
};
// 告警级别展示:严重 / 重要 / 提示
const ALARM_LEVEL_ALIAS: Record<string, string> = {
'1': 'ERROR', '2': 'WARNING', '3': 'INFO', '4': 'INFO',
CRITICAL: 'ERROR', MAJOR: 'WARNING', MINOR: 'INFO',
};
const ALARM_LEVEL_META: Record<string, { text: string; color: string; tag: string }> = {
ERROR: { text: '严重', color: '#ff4d4f', tag: 'red' },
WARNING: { text: '重要', color: '#faad14', tag: 'orange' },
INFO: { text: '提示', color: '#1677ff', tag: 'blue' },
};
const resolveAlarmLevel = (record: any) => {
const raw = String(record?.alertLevel ?? record?.alarmLevel ?? 'INFO').toUpperCase();
return ALARM_LEVEL_ALIAS[raw] || raw;
};
// 浅色主题卡片组件
const MonitorCard: React.FC<{ title: string; icon: React.ReactNode; children: React.ReactNode; extra?: React.ReactNode; height?: number | string; bodyOverflow?: string }> = ({ title, icon, children, extra, height, bodyOverflow = 'auto' }) => (
<Card
@@ -105,6 +140,8 @@ const TaskMonitorPage: React.FC = () => {
const [polyPoints, setPolyPoints] = useState<any[]>([]);
const [routeMode, setRouteMode] = useState('');
const [points, setPoints] = useState<any[]>([]);
const [detectReportInfo, setDeportInfo] = useState<any>(null);
const controllerRef = useRef<DeviceController | null>(null);
@@ -119,6 +156,9 @@ const TaskMonitorPage: React.FC = () => {
}
return null;
};
const handleDetectionReport = (res) => {
setDeportInfo(res);
}
// 电量优先取实时数据,实时没有时回退到设备结构里的 lastRunningStatus / locationMessage
const getDeviceBattery = (device: any): number | undefined => {
@@ -152,11 +192,40 @@ const TaskMonitorPage: React.FC = () => {
controller.onIsExecuting = refreshData;
controller.deviceStatusChangedMsg = refreshData;
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
controller.onDetectionReport = handleDetectionReport;
// 全局推送的新告警:合并到列表顶部
controller.onDeviceErrorPush = (payload: any) => {
const incoming: any[] = Array.isArray(payload?.alarms) ? payload.alarms : [];
if (!incoming.length) return;
setAlarmList((prev: any[]) => {
const incomingIds = new Set(incoming.map((a) => a.id));
return [...incoming, ...prev.filter((a) => !incomingIds.has(a.id))].slice(0, 5);
});
};
controllerRef.current = controller;
return () => {
controller.closeMapPush();
};
}, [userInfo, stationId]);
// 手动处理告警:handleStatus=2 表示已关闭
const handleAlarmItem = async (record: any) => {
const alarmId = record?.id;
if (!alarmId) return;
try {
const res = await handleAlarm({ alarmId, handleStatus: 2 });
if (res?.code === 200) {
utils.message.success('处理成功');
setAlarmList((prev: any[]) => prev.filter((a) => a.id !== alarmId));
} else {
utils.message.error(res?.msg || '处理失败');
}
} catch (err) {
console.error('处理告警失败', err);
utils.message.error('处理失败');
}
};
const fetchRouteDetail = async (id) => {
try {
const params = {
@@ -562,28 +631,36 @@ const TaskMonitorPage: React.FC = () => {
</MonitorCard>
<MonitorCard title="告警中心" icon={<Bell size={18} color="#ff4d4f" />} extra={<Space size={8}><Badge count={alarmList.filter(a => a.handleStatus === 1).length} overflowCount={99} /><Button type="link" size="small" onClick={() => navigate('/alerts/all')}>查看更多</Button></Space>} height="25%">
<MonitorCard title="告警中心" icon={<Bell size={18} color="#ff4d4f" />} extra={<Space size={8}><Badge count={alarmList.filter((a: any) => a.handleStatus !== 2).length} overflowCount={99} /><Button type="link" size="small" onClick={() => navigate('/alerts/all')}>查看更多</Button></Space>} height="25%">
<List
size="small"
dataSource={alarmList.filter(a => a.handleStatus === 1).slice(0, 3)}
renderItem={(item: any) => (
<List.Item style={{ padding: '8px 0' }}>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, width: '100%' }}>
<AlertTriangle size={16} color={item.alarmLevel === 'ERROR' ? '#ff4d4f' : '#faad14'} style={{ marginTop: 2 }} />
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontWeight: 500, color: '#262626' }}>{item.alarmTitle}</span>
<Tag color={item.alarmLevel === 'ERROR' ? 'red' : 'orange'} size="small" style={{ margin: 0, borderRadius: 4 }}>
{item.alarmLevel === 'ERROR' ? '紧急' : '重要'}
</Tag>
</div>
<div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 4 }}>
{item.deviceName} | {dayjs(item.alarmTime).format('HH:mm:ss')}
dataSource={alarmList.filter((a: any) => a.handleStatus !== 2).slice(0, 3)}
renderItem={(item: any) => {
const level = resolveAlarmLevel(item);
const meta = ALARM_LEVEL_META[level] || ALARM_LEVEL_META.INFO;
const title = getAlarmTitleText(item);
return (
<List.Item style={{ padding: '8px 0' }}>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, width: '100%' }}>
<AlertTriangle size={16} color={meta.color} style={{ marginTop: 2 }} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
<Tooltip title={title}>
<span style={{ fontWeight: 500, color: '#262626', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title || '--'}</span>
</Tooltip>
<Space size={4}>
<Tag color={meta.tag} size="small" style={{ margin: 0, borderRadius: 4 }}>{meta.text}</Tag>
<Button type="link" size="small" style={{ padding: 0, fontSize: 12 }} onClick={() => handleAlarmItem(item)}>处理</Button>
</Space>
</div>
<div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.deviceAlias || item.deviceName || item.deviceId || '--'} | {item.alarmTime}
</div>
</div>
</div>
</div>
</List.Item>
)}
</List.Item>
);
}}
locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无未处理告警" /> }}
/>
</MonitorCard>
@@ -669,10 +746,11 @@ const TaskMonitorPage: React.FC = () => {
polyPoints={polyPoints}
routeMode={routeMode}
points={points}
detectReportInfo={detectReportInfo}
/>
{/* 地图叠加操作:清空实时轨迹 / 清空规划区域 */}
<div style={{ position: 'absolute', top: 12, right: 12, display: 'flex', gap: 8, zIndex: 10 }}>
<div style={{ position: 'absolute', top: 12, right: 112, display: 'flex', gap: 8, zIndex: 10 }}>
{/*<Button size="small" icon={<ClearOutlined />} onClick={clearRealtimeTrack} >清空实时轨迹</Button>*/}
<Button size="small" icon={<ClearOutlined />} onClick={clearTaskRoute} >清空规划区域</Button>
</div>

View File

@@ -1,4 +1,4 @@
import React, { lazy, Suspense } from 'react';
import React, { lazy, Suspense } from 'react';
import type { RouteObject } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -150,10 +150,7 @@ export const routes: RouteObject[] = [
path: 'agri',
element: withSuspense(Agri)
},
{
path: 'alerts/all',
element: withSuspense(Alerts)
},
{
path: 'reportCenter/overview',
element: withSuspense(ReportCenterOverview)