接收 全局推送告警 处理告警 优化控制逻辑

This commit is contained in:
mmc
2026-11-16 21:36:53 +08:00
parent d9f4b752dd
commit 2a429722d9
9 changed files with 489 additions and 229 deletions

View File

@@ -0,0 +1,18 @@
## 软著用户手册扩充(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页断开),已在回复中告知用户

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

@@ -29,7 +29,7 @@ import AgrtcRoomRobot from '../AgrtcRoomRobot';
import CesiumMap from '../Map.jsx';
import DeviceParamModal from './DeviceParamModal';
import { getUAVState, getSiteDevice, getSiteUAVList, getsinglePlan, getRobotTaskList, getDeviceTotalData, updateDeviceAliasApi, hasPermission } from '@/api/device.ts';
import { getAlarmList } from '@/api/alarmApi.js';
import { getAlarmList, handleAlarm } from '@/api/alarmApi.js';
import dayjs from 'dayjs';
@@ -48,6 +48,36 @@ import { backToRestPointCommand } from '@/api/mapEdit';
const { Content } = Layout;
const { Text, Title } = Typography;
// 告警时间兼容:Java LocalDateTime 数组 / ISO 字符串 / 时间戳
const formatAlarmTime = (value: any, fmt = 'YYYY-MM-DD 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 是编码时改用 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 || '';
};
// 告警级别:兼容数字 1-4 / CRITICAL 等别名
const ALARM_LEVEL_ALIAS: Record<string, string> = {
'1': 'ERROR', '2': 'WARNING', '3': 'INFO', '4': 'INFO',
CRITICAL: 'ERROR', MAJOR: 'WARNING', MINOR: 'INFO',
};
const resolveAlarmLevel = (record: any) => {
const raw = String(record?.alertLevel ?? record?.alarmLevel ?? 'INFO').toUpperCase();
return ALARM_LEVEL_ALIAS[raw] || raw;
};
export default function DeviceOverviewPage() {
@@ -312,6 +342,11 @@ export default function DeviceOverviewPage() {
if (!userInfo || !stationId) return;
const controller = new DeviceController(userInfo, messageApi, stationId);
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
// 全局推送的新告警:合并到列表顶部(按 id 去重),只显示最近 5 条
controller.onDeviceErrorPush = (payload: any) => {
const incoming: any[] = Array.isArray(payload?.alarms) ? payload.alarms : [];
setAlarmList(incoming);
};
controllerRef.current = controller;
return () => {
if (controllerRef.current) controllerRef.current.closeMapPush();
@@ -601,6 +636,24 @@ export default function DeviceOverviewPage() {
})
}
// 手动处理告警: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) {
messageApi.success(t('alerts.handleSuccess'));
setAlarmList((prev) => prev.filter((a) => a.id !== alarmId));
} else {
messageApi.error(res?.msg || t('alerts.handleFail'));
}
} catch (err) {
console.error('处理告警失败', err);
messageApi.error(t('alerts.handleFail'));
}
};
const fetchAlarmList = async () => {
try {
const res = await getAlarmList({ pageNum: 1, pageSize: 5, siteId: stationId });
@@ -945,7 +998,7 @@ export default function DeviceOverviewPage() {
>
<Table
rowKey="time"
rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTime}
size="small"
pagination={false}
dataSource={taskList}
@@ -1029,33 +1082,57 @@ export default function DeviceOverviewPage() {
</>}
variant="borderless"
style={{ borderRadius: 8, height: '100%' }}
extra={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Button size="small" style={{ borderRadius: 4, border: '1px solid #d9d9d9' }}>
{t('devices.fixed2AllLevels')}
</Button>
</div>
}
>
<Table
rowKey="time"
rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTitle}
size="small"
pagination={false}
dataSource={alarmList}
scroll={{ x: 'max-content' }}
columns={[
{ title: t('common.time'), dataIndex: 'alarmTime', width: 90, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> },
{ title: t('devices.device'), dataIndex: 'deviceName', width: 100, render: (v) => <span style={{ fontSize: 13 }}>{v}</span> },
{
title: t('common.time'),
dataIndex: 'alarmTime',
width: 145,
render: (v) => <span style={{ fontSize: 12, whiteSpace: 'nowrap' }}>{formatAlarmTime(v) || '-'}</span>
},
{
title: t('devices.device'),
dataIndex: 'deviceName',
width: 110,
ellipsis: true,
render: (v, record) => <span style={{ fontSize: 12 }}>{record?.deviceAlias || record?.deviceId || v || '-'}</span>
},
{
title: t('alerts.alarmTitle'),
dataIndex: 'alarmTitle',
width: 70,
dataIndex: 'alarmContent',
width: 220,
render: (_, record) => {
const text = getAlarmTitleText(record);
return (
<Tooltip title={text}>
<span style={{ fontSize: 12 }}>{text || '-'}</span>
</Tooltip>
);
}
},
{
title: t('alerts.alertLevel'), dataIndex: 'alertLevel', render: (l) => <AlarmLevelTag level={l} size="small" />
title: t('alerts.alertLevel'),
width: 70,
render: (_, record) => <AlarmLevelTag level={resolveAlarmLevel(record)} size="small" />
},
{
title: t('alerts.handle'),
width: 70,
render: (_, record) => record?.handleStatus === 2
? <Tag style={{ fontSize: 11, margin: 0 }}>{t('alerts.handled')}</Tag>
: (
<Button type="link" size="small" style={{ padding: 0, fontSize: 12 }} onClick={() => handleAlarmItem(record)}>
{t('alerts.handle')}
</Button>
)
},
{ title: '', width: 70, render: (_, record) => record.level ? <Tag color="red" style={{ fontSize: 11, margin: 0 }}>{record.level}</Tag> : null }
]}
/>
<div style={{ textAlign: 'center', marginTop: 8 }}>

View File

@@ -734,6 +734,7 @@ export default function DeviceStatusPage() {
const handleGamepadUpdate = useCallback((state) => {
// 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏)
if (!isControlled) {
messageApi.warning("请获取控制权限");
//if (!hasRequestedControlRef.current && !connecting) {
// hasRequestedControlRef.current = true;
// handleControlModal();
@@ -741,9 +742,12 @@ export default function DeviceStatusPage() {
//return;
}
console.log(realtimePosition?.controlMode, "现在的控制controlmode")
if (realtimePosition?.controlMode && (realtimePosition?.controlMode != 3 || realtimePosition?.controlMode != 0)) {
if (
realtimePosition?.controlMode != 3 &&
realtimePosition?.controlMode != 0 &&
realtimePosition?.controlMode != null
) {
messageApi.warning(t('devices.noRemoteControl'));
//return;
}
console.log('Gamepad state updated:', state);
// 记录方向盘 xy 坐标,用于倒车影像叠加层
@@ -756,7 +760,11 @@ export default function DeviceStatusPage() {
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;

View File

@@ -1,186 +1,186 @@
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);
}
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;
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.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 }}>
{mergedCards.map((item, index) => (
<Col xs={12} sm={8} md={4} 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>
);
}
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(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)' };

View File

@@ -340,11 +340,49 @@ 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?.();

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;
@@ -172,6 +173,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

@@ -1878,6 +1878,7 @@ const zh = {
handled: '已处理',
restored: '已恢复',
ignored: '已忽略',
ignore: "忽略",
unableToHandle: '无法处理',
manufacturerHandling: '厂家处理中',
falseAlarm: '误报',

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
@@ -158,12 +193,39 @@ const TaskMonitorPage: React.FC = () => {
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 = {
@@ -569,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>