feat: 离线报警:设备页和当前扫描任务显示告警,同一次离线只通知一次,恢复后清除;启动前检查:机械臂急停、离线或安全状态无法确认时,禁止开始并提示具体原因;运行中急停:立即安全停止,同时通知并持续展示取消原因,刷新后仍可查看。

This commit is contained in:
zhanghao 2026-11-20 20:10:49 +08:00
parent 6ace9b135e
commit c39abb5241
14 changed files with 286 additions and 28 deletions

View File

@ -35,7 +35,7 @@
- 用户要求:项目原有自动化回归测试代码保留;每次任务新增的测试源码及专用验证脚本按上述要求清理;开发验证成功后,清理本次生成的业务测试用例、任务、执行日志、导入文件、输出文件和临时文件,不能留在业务页面中。
- 通过明确的验证批次前缀登记测试数据。优先执行 `scripts/cleanup_verification.py --prefix <本次前缀> --apply`,先结束运行中的任务并确认资源释放。不要用“名称包含 test”、创建时间或清空整表来判断测试数据。
- 若验证失败,保留必要诊断信息;修复并通过后必须完成清理。最终核对没有本轮测试数据及机器人占用残留。
- 用户明确要求的永久在线模拟机器人 `am-freescan-sim-robot` 和模拟设备 `am-freescan-sim-agv` 继续保留,除非用户另行要求删除。
- 2026-11-20 用户已要求删除模拟机器人 `am-freescan-sim-robot` 和模拟设备 `am-freescan-sim-agv`;开发库资源及运行绑定已移除,对应模拟器自动启动已禁用。以后不得自动重建或启动,恢复须由用户重新明确授权。已有演示任务、历史记录及其资源档案继续保留。
- 2026-10-22 用户另行要求创建并保留两条全流程演示数据:前缀 `DEMO-20261022-091650`,任务 `T-20261022-0005`、`T-20261022-0006`,导入批次 `IB-20261022-0009`。对应测试用例、样品、夹具、技术资料、执行日志和输出均供用户查看,不纳入开发验证自动清理;清单见 `docs/full-flow-demo-20261022.json`。
- 不删除运行配置、凭据、来源指纹、实际业务数据或项目原有回归测试代码。不要输出 `.local/runtime.json` 中的敏感信息。
- 2026-10-27 用户要求集成真实旋转底座,工位 `am-freescan-rotary-base-station-001` 已通过正常接口登记;设备永久标识 `aima_motor`,服务配置为 `192.168.0.203:50052`。该工位不是验证样例,不自动清理;不得用传输可达替代机械状态反馈,不在开发验证中自动使能或移动真实底座。

View File

@ -62,5 +62,7 @@ public class ResourceRobot extends BaseEntity {
@TableField(exist = false)
private Integer onlineDeviceCount;
@TableField(exist = false)
private Integer offlineDeviceCount;
@TableField(exist = false)
private Integer faultDeviceCount;
}

View File

@ -25,6 +25,7 @@
<result property="currentMapName" column="current_map_name"/>
<result property="deviceTotal" column="device_total"/>
<result property="onlineDeviceCount" column="online_device_count"/>
<result property="offlineDeviceCount" column="offline_device_count"/>
<result property="faultDeviceCount" column="fault_device_count"/>
<result property="createBy" column="create_by"/>
<result property="createTime" column="create_time"/>
@ -42,6 +43,7 @@
select r.*, m.map_name as current_map_name,
(select count(*) from iot_device d where d.robot_id = r.robot_id) as device_total,
(select count(*) from iot_device d where d.robot_id = r.robot_id and d.online_status = '1') as online_device_count,
(select count(*) from iot_device d where d.robot_id = r.robot_id and d.enabled = '1' and coalesce(d.online_status, '0') != '1') as offline_device_count,
(select count(*) from iot_device d where d.robot_id = r.robot_id and (d.health_status = 3 or d.has_error = '1')) as fault_device_count
from iot_robot r
left join iot_map m on m.id = r.active_map_id

View File

@ -22,15 +22,7 @@ public class RuntimeResourceCatalog extends ResourceOccupationStore {
public List<ResourceRef> lockedResources(ScanTaskConfigDO c,boolean create,List<ResourceRef> additional) { return resolve(c,create,additional,true); }
private record DeviceBinding(String robot,String device,Long master) {}
private List<ResourceRef> resolve(ScanTaskConfigDO c,boolean create,List<ResourceRef> additional,boolean lock) {
Map<String,ResourceRef> result=new TreeMap<>();Map<String,Set<String>> pairs=new TreeMap<>();
if(c.getRobotId()!=null&&!c.getRobotId().isBlank())pairs.put(c.getRobotId(),new TreeSet<>());
if(c.getRuntimeAssignments()!=null)for(var assignment:c.getRuntimeAssignments()) {
Object members=assignment.get("members");if(!(members instanceof Collection<?> list))continue;
for(Object item:list)if(item instanceof Map<?,?> member&&member.get("robotId")!=null&&!member.get("robotId").toString().isBlank()) {
String robot=member.get("robotId").toString();var devices=pairs.computeIfAbsent(robot,k->new TreeSet<>());
if(member.get("devices") instanceof Map<?,?> map)for(Object device:map.values())if(device!=null&&!device.toString().isBlank())devices.add(device.toString());
}
}
Map<String,ResourceRef> result=new TreeMap<>();Map<String,Set<String>> pairs=deviceAssignments(c);
List<DeviceBinding> bindings=new ArrayList<>();Set<Long> masterIds=new TreeSet<>(),labIds=new TreeSet<>();
for(var pair:pairs.entrySet()) {
String robot=pair.getKey();if(robots.selectByRobotIdentity(robot)==null)throw invalidParamException("请使用机器人的永久 robotId:{}",robot);
@ -65,6 +57,18 @@ public class RuntimeResourceCatalog extends ResourceOccupationStore {
for(Long lab:requiredLabs)result.put("L:"+lab,new ResourceRef("LAB","L:"+lab,lab.toString(),Objects.toString(labs.get(lab).get("lab_name")),null));
return new ArrayList<>(result.values());
}
static Map<String,Set<String>> deviceAssignments(ScanTaskConfigDO c) {
Map<String,Set<String>> pairs=new TreeMap<>();
if(c.getRobotId()!=null&&!c.getRobotId().isBlank())pairs.put(c.getRobotId(),new TreeSet<>());
if(c.getRuntimeAssignments()!=null)for(var assignment:c.getRuntimeAssignments()) {
Object members=assignment.get("members");if(!(members instanceof Collection<?> list))continue;
for(Object item:list)if(item instanceof Map<?,?> member&&member.get("robotId")!=null&&!member.get("robotId").toString().isBlank()) {
String robot=member.get("robotId").toString();var devices=pairs.computeIfAbsent(robot,k->new TreeSet<>());
if(member.get("devices") instanceof Map<?,?> map)for(Object device:map.values())if(device!=null&&!device.toString().isBlank())devices.add(device.toString());
}
}
return pairs;
}
private Long masterDevice(String robot,String device,boolean create) {
var links=rows("SELECT lab_device_id FROM lab_runtime_device_link WHERE robot_id=? AND device_id=? AND tenant_id=1 AND deleted=0",robot,device);
if(!links.isEmpty())return number(links.get(0).get("lab_device_id"));if(!create)return null;

View File

@ -0,0 +1,73 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.iocoder.yudao.module.lab.dal.dataobject.scanonly.ScanTaskConfigDO;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.arm.ArmTeachingOperation;
import com.cmvr.arm.ArmTeachingRequest;
import com.cmvr.arm.ArmTeachingService;
import com.cmvr.resource.domain.ResourceDevice;
import com.cmvr.resource.mapper.ResourceDeviceMapper;
import com.cmvr.resource.mapper.ResourceRobotMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.*;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException;
/** Page refreshes read persisted discovery state only. The explicit start gate also reads arm safety. */
@Service
@RequiredArgsConstructor
public class ScanDeviceStatusService {
private final ResourceRobotMapper robots;
private final ResourceDeviceMapper devices;
private final ArmTeachingService arms;
public record Alert(String code,String robotId,String deviceId,String message) {}
public List<Alert> alerts(ScanTaskConfigDO config) {
List<Alert> result=new ArrayList<>();
for(var binding:RuntimeResourceCatalog.deviceAssignments(config).entrySet()) {
String robotId=binding.getKey();var robot=robots.selectByRobotIdentity(robotId);
if(robot==null||"1".equals(robot.getArchivedStatus())) {
result.add(new Alert("ROBOT_UNAVAILABLE",robotId,"","机器人不存在或已归档:"+robotId));continue;
}
String robotName=Objects.toString(robot.getRobotName(),robotId);
if(!"1".equals(robot.getConnectStatus())) {
result.add(new Alert("ROBOT_OFFLINE",robotId,"","机器人离线:"+robotName+"("+robotId+")"));continue;
}
List<ResourceDevice> found=devices.selectByRobotId(robotId,null,false);
Set<String> selected=new TreeSet<>(binding.getValue());
if(selected.isEmpty())for(var device:found)if("1".equals(device.getEnabled()))selected.add(device.getDeviceId());
for(String id:selected) {
var matches=found.stream().filter(d->id.equals(d.getDeviceId())).toList();
if(matches.size()!=1) {
result.add(new Alert("DEVICE_UNAVAILABLE",robotId,id,"设备未登记或身份不唯一:"+robotId+" / "+id));continue;
}
var device=matches.get(0);String name=Objects.toString(device.getDeviceName(),id);
if(!"1".equals(device.getEnabled()))result.add(new Alert("DEVICE_DISABLED",robotId,id,"设备已停用:"+name+"("+robotId+" / "+id+")"));
else if(!"1".equals(device.getOnlineStatus()))result.add(new Alert("DEVICE_OFFLINE",robotId,id,"设备离线:"+name+"("+robotId+" / "+id+")"));
}
}
return List.copyOf(result);
}
public void assertReady(ScanTaskConfigDO config) {
var issues=alerts(config);
if(!issues.isEmpty())throw invalidParamException("不能开始扫描:{}",issues.get(0).message());
// Match the existing emergency observer: an enabled arm in a bound workcell interlocks its run.
for(String robot:RuntimeResourceCatalog.deviceAssignments(config).keySet())for(var device:devices.selectByRobotId(robot,2,false)) {
if(!"1".equals(device.getEnabled()))continue;
String target=robot+" / "+Objects.toString(device.getDeviceName(),device.getDeviceId())+"("+device.getDeviceId()+")";
if(!"1".equals(device.getOnlineStatus()))throw invalidParamException("不能开始扫描,机械臂离线:{}",target);
ArmTeachingRequest request=new ArmTeachingRequest();request.setRobotId(robot);request.setDeviceId(device.getDeviceId());request.setTimeoutMs(2000L);
JSONObject reply;
try { reply=arms.execute(ArmTeachingOperation.GET_ROBOT_STATE,request); }
catch(RuntimeException error) {throw invalidParamException("不能开始扫描,无法确认机械臂安全状态:{};{}",target,Objects.toString(error.getMessage(),"状态查询失败"));}
JSONObject state=reply==null?null:reply.getJSONObject("state");
if(reply==null||!Boolean.TRUE.equals(reply.getBoolean("success"))||state==null||!Boolean.TRUE.equals(state.getBoolean("connected"))||state.getBoolean("emergencyStopped")==null)
throw invalidParamException("不能开始扫描,未取得有效的机械臂急停状态:{}",target);
if(Boolean.TRUE.equals(state.getBoolean("emergencyStopped")))throw invalidParamException("不能开始扫描,机械臂急停未解除:{}。请处理急停并重新预检",target);
}
}
}

View File

@ -200,7 +200,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
public ScanTaskConfigDO acquireResources(ScanTaskRequests.Acquire request) {
LabTestTaskDO task=owned(request.getTaskId(),false);ScanTaskConfigDO c=config(task.getId());
if(!Objects.equals(c.getRevision(),request.getExpectedRevision()))throw invalidParamException("配置已更新,请刷新后重新准备");
if(!Boolean.TRUE.equals(checks(task,c).get("passed")))throw invalidParamException("资源和就绪检查未通过,请先执行预检查看原因");
var checked=checks(task,c);if(!Boolean.TRUE.equals(checked.get("passed")))throw invalidParamException("不能准备装夹:{}",failedChecks(checked));
resources.acquire(task,c);for(String robot:robotIds(c))acquire(robot,task.getId(),null);configs.updateById(c);
audit(task,"SCAN_RESOURCES_ACQUIRED",map("startAt",c.getPlannedStartAt(),"endAt",c.getPlannedEndAt(),"laboratoryId",c.getLaboratoryId()));return c;
}
@ -242,7 +242,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
ScanSampleUnitDO next=list.stream().filter(u->!"SUCCEEDED".equals(u.getStatus())).findFirst().orElseThrow(()->invalidParamException("所有单件已执行成功"));
if(!Objects.equals(next.getId(),unit.getId())) throw invalidParamException("请按单件顺序执行或重试上一件");
Map<String,Object> checked=checks(task,c);
if(!Boolean.TRUE.equals(checked.get("passed"))) throw invalidParamException("就绪检查未通过,请查看检查项");
if(!Boolean.TRUE.equals(checked.get("passed"))) throw invalidParamException("不能开始扫描:{}",failedChecks(checked));
resources.acquire(task,c);configs.updateById(c);
LabTestMethodRefDO method=methods.ensureMethod(c.getSelectedTestCaseId(),c.getVersionId());
Map<String,Object> params=ScanExecutionPlanService.manifest(c.getRunParams())==null?resolveParams(c.getInputConfig(),frameworkParameters(c),true):planParameters(c,true);
@ -554,8 +554,13 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
}
for(var slice:planSlices(c))validateLegacyDevices(slice);
});
check(checks,"DEVICE_SAFETY",()->resources.validateSafety(c));
boolean passed=checks.stream().allMatch(item->Boolean.TRUE.equals(item.get("passed")));return map("passed",passed,"items",checks);
}
private String failedChecks(Map<String,Object> result) {
return ((List<?>)result.get("items")).stream().filter(Map.class::isInstance).map(Map.class::cast)
.filter(item->!Boolean.TRUE.equals(item.get("passed"))).map(item->Objects.toString(item.get("message"),"就绪检查未通过")).collect(java.util.stream.Collectors.joining(";"));
}
private void validateLegacyDevices(ScanTaskConfigDO c){
JSONObject graph=JSON.parseObject(c.getFlowData());JSONArray nodes=graph.getJSONArray("nodes");if(nodes==null)throw invalidParamException("流程节点缺失");
boolean roles=nodes.stream().filter(JSONObject.class::isInstance).map(JSONObject.class::cast).anyMatch(n->{JSONObject p=n.getJSONObject("properties");return "start".equalsIgnoreCase(n.getString("type"))&&p!=null&&p.getJSONArray("resourceRoles")!=null&&!p.getJSONArray("resourceRoles").isEmpty();});

View File

@ -18,6 +18,7 @@ import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionU
@Service
public class ScanResourceService extends ResourceOccupationStore {
@Resource private RuntimeResourceCatalog catalog;
@Resource private ScanDeviceStatusService deviceStatus;
@Resource @Lazy private ScanResourceService self;
@Resource private RobotExecutionTargetResolver targets;
@Resource @Lazy private TaskInstHolder nativeTasks;
@ -39,6 +40,7 @@ public class ScanResourceService extends ResourceOccupationStore {
public void validate(ScanTaskConfigDO c) {
primary();var window=window(c);checkStart(window);checkSet(taskOwner(c.getTaskId()),c.getTaskId(),resolve(c,false),window,false);
}
public void validateSafety(ScanTaskConfigDO c) { primary();deviceStatus.assertReady(c); }
public void acquire(LabTestTaskDO task,ScanTaskConfigDO c) {
primary();var window=window(c);checkStart(window);acquireSet(taskOwner(task.getId()),task.getId(),null,resolve(c,true),window,true);
if(c.getResourcesAcquiredAt()==null){c.setResourcesAcquiredAt(LocalDateTime.now());c.setPlannedStartAt(window.start());c.setPlannedEndAt(window.end());}
@ -52,7 +54,7 @@ public class ScanResourceService extends ResourceOccupationStore {
primary();List<Map<String,Object>> refs=new ArrayList<>();String problem=null;
try{for(ResourceRef r:catalog.resources(c,false))refs.add(map("type",r.type(),"id",r.id(),"name",r.name(),"robotId",r.robotId()));}catch(RuntimeException error){problem=error.getMessage();}
return map("resources",refs,"bookings",bookings(c.getTaskId()),"leases",rows("SELECT * FROM lab_resource_occupation WHERE task_id=? AND tenant_id=1 AND deleted=0 ORDER BY resource_type,resource_id",c.getTaskId()),
"laboratories",rows("SELECT id,lab_code,lab_name,exclusive_use FROM lab_laboratory WHERE status='ENABLED' AND tenant_id=1 AND deleted=0 ORDER BY lab_code"),"message",problem,"expired",c.getPlannedEndAt()!=null&&!c.getPlannedEndAt().isAfter(LocalDateTime.now()));
"laboratories",rows("SELECT id,lab_code,lab_name,exclusive_use FROM lab_laboratory WHERE status='ENABLED' AND tenant_id=1 AND deleted=0 ORDER BY lab_code"),"deviceAlerts",deviceStatus.alerts(c),"message",problem,"expired",c.getPlannedEndAt()!=null&&!c.getPlannedEndAt().isAfter(LocalDateTime.now()));
}
public List<Map<String,Object>> occupations(){primary();return rows("SELECT * FROM lab_resource_occupation WHERE tenant_id=1 AND deleted=0 ORDER BY create_time,id");}
public AutoCloseable workflowOperation(String robot,String instId) {

View File

@ -38,6 +38,7 @@ export interface ScanConfig {
robotId?: string
startedAt?: string
stopPending: boolean
cancelRequested?: boolean
reservationMode?: 'IMMEDIATE' | 'SCHEDULED'
expectedMinutes?: number
plannedStartAt?: string | number
@ -87,6 +88,7 @@ export interface ScanTaskDetail {
resourceState?: ResourceState
}
export interface ResourceState {
deviceAlerts?: { code: string; robotId: string; deviceId: string; message: string }[]
resources: { type: string; id: Id; name: string; robotId?: string }[]
bookings: Record<string, any>[]
leases: Record<string, any>[]
@ -123,7 +125,7 @@ export const getSupplementOption = (taskId: Id, unitId: Id) => request.get<Suppl
export const startSupplement = (data: { taskId: Id; unitId: Id; parentExecutionId: Id; expectedRevision: number; durationSeconds: number; reason: string; idempotencyKey: string; sampleConfirmed: boolean; fixtureConfirmed: boolean; loadedConfirmed: boolean }) => request.post<Id>({ url: base + '/supplement', data })
export const finishSupplement = (taskId: Id, executionId: Id) => request.post({ url: base + '/finish-supplement', data: { taskId, executionId } })
export const acquireResources = (taskId: Id, expectedRevision: number) =>
request.post<ScanConfig>({ url: base + '/acquire-resources', data: { taskId, expectedRevision } })
request.post<ScanConfig>({ url: base + '/acquire-resources', data: { taskId, expectedRevision }, silentError: true })
export const releaseResources = (taskId: Id, reason: string) =>
request.post<ScanConfig>({
url: base + '/release-resources',
@ -146,7 +148,7 @@ export const getDetail = (taskId: Id) =>
export const prepare = (data: PrepareScanTask) =>
request.put<ScanConfig>({ url: base + '/prepare', data })
export const precheck = (taskId: Id) =>
request.post<ScanPrecheck>({ url: base + '/precheck', data: { taskId } })
request.post<ScanPrecheck>({ url: base + '/precheck', data: { taskId }, silentError: true })
export const startUnit = (data: {
taskId: Id
unitId: Id
@ -155,7 +157,7 @@ export const startUnit = (data: {
idempotencyKey: string
physicalSerial?: string
reason?: string
}) => request.post<Id>({ url: base + '/start-unit', data })
}) => request.post<Id>({ url: base + '/start-unit', data, silentError: true })
export const cancel = (taskId: Id, reason: string) =>
request.post({ url: base + '/cancel', data: { taskId, reason } })
export const confirmStop = (taskId: Id, reason: string) =>

View File

@ -26,6 +26,9 @@
<CmvrRightToolbar v-model:showSearch="showSearch" @queryTable="getList" />
</el-row>
<el-alert v-if="offlineAlerts.length" title="设备离线报警" type="error" :closable="false" show-icon class="mb8">
<div v-for="alert in offlineAlerts" :key="`${alert.code}:${alert.robotId}`">{{ alert.message }}</div>
</el-alert>
<el-table v-loading="loading" :data="robotList" row-key="id">
<el-table-column label="机器人" min-width="190">
<template #default="{ row }">
@ -168,6 +171,9 @@
</el-select>
<el-button icon="Refresh" :loading="deviceLoading" @click="loadDevices">刷新</el-button>
</div>
<el-alert v-if="drawerAlerts.length" title="当前机器人存在离线设备" type="error" :closable="false" show-icon class="mb8">
<div v-for="alert in drawerAlerts" :key="`${alert.code}:${alert.robotId}:${alert.deviceId || ''}`">{{ alert.message }}</div>
</el-alert>
<el-table v-loading="deviceLoading" :data="filteredDevices" empty-text="机器人尚未上报设备">
<el-table-column label="设备" min-width="180">
<template #default="{ row }"><strong>{{ row.deviceName || row.deviceId }}</strong><div class="secondary">{{ row.deviceId }}</div></template>
@ -188,7 +194,8 @@
<script setup name="ResourceRobot">
import { formatNullableDate, dateFormatter } from '@/utils/formatTime'
import { computed, getCurrentInstance, onActivated, onDeactivated, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { createDeviceAlertTracker, robotOfflineAlerts, deviceOfflineAlerts } from '@/utils/deviceAlerts.mjs'
import { addRobot, deleteRobot, getRobotDevices, getRobotList, getRobotStatus, updateRobot } from '@/cmvr/common/api/resource/robot'
import { listResourceMaps as getMapList } from '@/cmvr/common/api/resource/map'
import { agvRuntimeStatusLabel, agvRuntimeStatusType } from '@/cmvr/common/utils/agvRuntimeStatus'
@ -217,6 +224,16 @@ let deviceRefreshTimer
let listRefreshTimer
let pageActive = true
let listRequests = 0
let listGeneration = 0
let deviceGeneration = 0
const offlineAlerts = computed(() => robotOfflineAlerts(robotList.value))
const drawerAlerts = computed(() => deviceOfflineAlerts(activeRobot.value, devices.value))
const offlineNotifications = createDeviceAlertTracker()
function notifyOffline(scope, alerts) {
if (!pageActive || document.hidden) return
const fresh = offlineNotifications.update(scope, alerts)
if (fresh.length) ElNotification.error({ title: '设备离线报警', message: fresh.map(alert => alert.message).join(';'), duration: 10000 })
}
const queryParams = reactive({ pageNum: 1, pageSize: 10, robotId: '', robotName: '', connectStatus: '' })
const emptyForm = () => ({ id: '', robotId: '', robotName: '', robotCode: '', robotModel: '', robotType: '', currentMapId: '' })
@ -235,11 +252,18 @@ const filteredDevices = computed(() => devices.value.filter(item => {
}))
async function getList(showLoading = true) {
const generation = ++listGeneration
listRequests++
if (showLoading) loading.value = true
try {
const res = await getRobotList(queryParams)
if (generation !== listGeneration) return
robotList.value = res.rows || []
for (const robot of robotList.value) notifyOffline(`robot:${robot.robotId}`, robotOfflineAlerts([robot]))
if (deviceOpen.value) {
const current = robotList.value.find(robot => robot.robotId === activeRobot.value.robotId)
if (current) activeRobot.value = current
}
total.value = res.total || 0
} finally { listRequests--; if (showLoading) loading.value = false }
}
@ -270,13 +294,21 @@ async function handleArchive(row) {
await deleteRobot(row.id); ElMessage.success('机器人已归档'); getList()
}
async function openDevices(row) {
activeRobot.value = row; deviceOpen.value = true; deviceKeyword.value = ''; deviceOnline.value = ''; await loadDevices()
clearInterval(deviceRefreshTimer); deviceRefreshTimer = setInterval(() => { if (deviceOpen.value) loadDevices(false) }, 5000)
clearInterval(deviceRefreshTimer)
activeRobot.value = row; devices.value = []; deviceOpen.value = true; deviceKeyword.value = ''; deviceOnline.value = ''; await loadDevices()
if (deviceOpen.value && activeRobot.value.id === row.id && pageActive) deviceRefreshTimer = setInterval(() => { if (deviceOpen.value) loadDevices(false) }, 5000)
}
async function loadDevices(showLoading = true) {
if (!activeRobot.value.id) return
const generation = ++deviceGeneration
if (showLoading) deviceLoading.value = true
try { const res = await getRobotDevices(activeRobot.value.id); devices.value = res.data || [] } finally { deviceLoading.value = false }
const robot = activeRobot.value
try {
const res = await getRobotDevices(robot.id)
if (generation !== deviceGeneration || activeRobot.value.id !== robot.id || !deviceOpen.value) return
devices.value = res.data || []
notifyOffline(`devices:${robot.robotId}`, deviceOfflineAlerts(activeRobot.value, devices.value))
} finally { deviceLoading.value = false }
}
function endpointText(row) { return row.ipAddress && row.port ? `${row.ipAddress}:${row.port}` : '等待连接后自动获取' }
const runtimeStatusLabel = agvRuntimeStatusLabel
@ -326,8 +358,9 @@ onMounted(() => {
})
onActivated(() => { pageActive = true; getList(false) })
onDeactivated(() => { pageActive = false; clearInterval(deviceRefreshTimer) })
onDeactivated(() => { pageActive = false; listGeneration++; deviceGeneration++; clearInterval(deviceRefreshTimer) })
onBeforeUnmount(() => {
pageActive = false; listGeneration++; deviceGeneration++
clearInterval(deviceRefreshTimer)
clearInterval(listRefreshTimer)
})

View File

@ -0,0 +1,77 @@
const identity = (alert) =>
alert.key || JSON.stringify([alert.code, alert.robotId || '', alert.deviceId || ''])
/** Each scope is a complete snapshot (one robot, its drawer, or one task). */
export function createDeviceAlertTracker() {
const scopes = new Map()
return {
update(scope, alerts = []) {
const previous = scopes.get(scope) || new Map()
const current = new Map(alerts.map((alert) => [identity(alert), alert.message]))
scopes.set(scope, current)
return alerts.filter((alert) => previous.get(identity(alert)) !== alert.message)
}
}
}
export function robotOfflineAlerts(robots = []) {
return robots.flatMap((robot) => {
if (!robot.robotId || String(robot.archivedStatus) === '1') return []
const name = robot.robotName || robot.robotId
if (String(robot.connectStatus) === '0')
return [
{
code: 'ROBOT_OFFLINE',
robotId: robot.robotId,
message: `机器人离线:${name}(${robot.robotId})`
}
]
if (String(robot.connectStatus) === '1' && Number(robot.offlineDeviceCount) > 0)
return [
{
code: 'DEVICE_OFFLINE_SUMMARY',
robotId: robot.robotId,
message: `${name}有 ${robot.offlineDeviceCount} 个已启用设备离线,请打开“设备”查看`
}
]
return []
})
}
export function deviceOfflineAlerts(robot, devices = []) {
if (!robot?.robotId) return []
if (String(robot.connectStatus) === '0') return robotOfflineAlerts([robot])
return devices
.filter((device) => String(device.enabled) === '1' && String(device.onlineStatus) !== '1')
.map((device) => ({
code: 'DEVICE_OFFLINE',
robotId: robot.robotId,
deviceId: device.deviceId,
message: `设备离线:${device.deviceName || device.deviceId}(${robot.robotId} / ${device.deviceId})`
}))
}
export function scanCancellationAlert(detail) {
const reason = detail?.task?.cancelReason?.trim()
if (
!reason ||
!(detail.config?.cancelRequested || ['STOP_PENDING', 'CANCELLED'].includes(detail.task.status))
)
return undefined
const stopping = detail.config?.stopPending || detail.task.status === 'STOP_PENDING'
return {
key: `scan-cancellation:${detail.task.id}`,
code: 'SCAN_CANCELLED',
title: reason.startsWith('工位急停')
? stopping
? '检测到机械臂急停,正在停止任务'
: '机械臂急停,任务已取消'
: stopping
? '正在取消任务'
: '任务已取消',
message: reason,
hint: stopping
? '正在确认关联设备停止,停止未确认前继续保留占用。'
: '取消原因已保留;处理设备状态后请重新准备,任务不会自动续跑。'
}
}

View File

@ -12,7 +12,7 @@
<div v-if="!props.embedded || props.active" class="task-summary">
<el-tag v-if="!props.embedded">{{ statusLabel(detail.task.status) }}</el-tag>
<span v-if="!props.embedded" class="summary-count">完成 {{ completedCount }} / {{ detail.units.length }} 件</span>
<span class="summary-spacer" />
<span class="summary-spacer"></span>
<el-popover v-if="!props.embedded" trigger="click" placement="bottom-end" :width="360">
<template #reference><el-button text>任务信息</el-button></template>
<div class="task-metadata">
@ -48,6 +48,25 @@
>
</div>
</Teleport>
<el-alert
v-if="cancellationAlert"
:title="cancellationAlert.title"
type="error"
:closable="false"
show-icon
>
<p>{{ cancellationAlert.message }}</p>
<p>{{ cancellationAlert.hint }}</p>
</el-alert>
<el-alert
v-if="taskDeviceAlerts.length"
title="当前扫描任务的设备不可用"
type="error"
:closable="false"
show-icon
>
<div v-for="alert in taskDeviceAlerts" :key="`${alert.code}:${alert.robotId}:${alert.deviceId}`">{{ alert.message }}</div>
</el-alert>
<el-alert
v-if="detail.config.stopPending"
type="error"
@ -668,7 +687,8 @@
<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { ElMessageBox } from 'element-plus'
import { ElMessageBox, ElNotification } from 'element-plus'
import { createDeviceAlertTracker, scanCancellationAlert } from '@/utils/deviceAlerts.mjs'
import { generateUUID } from '@/utils'
import { scannerTaskParameters, validateScannerParameters, SCANNER_PARAMETER_RUN_KEY } from '@/cmvr/common/utils/scannerParameters.mjs'
import * as ScanApi from '@/api/lab/scan-task'
@ -802,6 +822,16 @@ const locked = computed(
const terminal = computed(() =>
['COMPLETED', 'CANCELLED'].includes(detail.value?.task.status || '')
)
const taskDeviceAlerts = computed(() => terminal.value ? [] : detail.value?.resourceState?.deviceAlerts || [])
const cancellationAlert = computed(() => scanCancellationAlert(detail.value))
const safetyNotifications = createDeviceAlertTracker()
function notifySafetyAlerts() {
if (!props.active || pollingSuspended || document.hidden || !detail.value || String(detail.value.task.id) !== taskId.value) return
const alerts = [...taskDeviceAlerts.value, ...(cancellationAlert.value ? [cancellationAlert.value] : [])]
const fresh = safetyNotifications.update(`task:${taskId.value}`, alerts)
if (fresh.length) ElNotification.error({ title: '扫描任务提醒', message: fresh.map(alert => alert.message).join(';'), duration: 10000 })
}
watch([detail, () => props.active], notifySafetyAlerts, { flush: 'post' })
const caseChanged = computed(
() => !!detail.value?.config.selectedTestCaseId && form.testCaseId !== detail.value.config.selectedTestCaseId
)
@ -1131,7 +1161,8 @@ const action = async (work: () => Promise<void>) => {
try {
await work()
} catch (error: any) {
if (!['cancel', 'close'].includes(error))
// The shared interceptor already displayed business errors rejected as the literal 'error'.
if (!['cancel', 'close', 'error'].includes(error))
message.error(error?.message || '操作失败,请刷新状态后重试')
} finally {
busy.value = false
@ -1369,7 +1400,7 @@ onMounted(() => {
}
}, 5000)
})
onActivated(() => { pollingSuspended = false })
onActivated(() => { pollingSuspended = false; notifySafetyAlerts() })
onDeactivated(() => { pollingSuspended = true })
watch([()=>props.active,activeTab],()=>{if(props.active&&!pollingSuspended){void loadCatalog()}})
watch(() => route.params.id, initialize)
@ -1385,6 +1416,8 @@ onBeforeRouteLeave(async () => {
return true
})
onUnmounted(() => {
pollingSuspended = true
pageGeneration++
pageGeneration++
versionRequest++
clearInterval(timer)

View File

@ -6,7 +6,8 @@ export function agvPollingPolicy(executionId, status) {
export function scanTaskPollInterval(detail) {
if (!detail) return 0
const working = detail.config?.stopPending || active.has(detail.task?.status) || detail.units?.some(unit => active.has(unit.status) || unit.attempts?.some(attempt => active.has(attempt.status)))
return working ? 5000 : 0
const configured = detail.config?.robotId || detail.config?.runtimeAssignments?.some(assignment => assignment.members?.some(member => member.robotId))
return working || (configured && !['COMPLETED', 'CANCELLED', 'FAILED'].includes(detail.task?.status)) ? 5000 : 0
}
export function comparisonPollInterval(status) {
return ['SUBMITTING', 'PROCESSING', 'REVIEW', 'ARCHIVE_PENDING'].includes(status) ? 10000 : 0

View File

@ -0,0 +1,22 @@
# 设备离线报警与扫描急停提示
## 页面行为
- “设备与资源 → 机器人”使用现有刷新结果展示离线告警;设备抽屉列出具体设备。停用设备不参与离线统计。同一离线状态只通知一次,恢复后清除告警,再次离线会重新通知。
- 扫描任务页只展示已保存执行配置中的机器人和设备。传统默认设备流程沿用原有资源选择范围,包含绑定机器人下的启用设备。已完成、已取消任务不持续监测设备。
- 已配置设备的待执行任务继续按 5 秒周期刷新平台记录;刷新不查询机械臂或扫描仪 SDK。
- “确认装夹并开始”进入装夹准备和实际提交执行时均执行后端安全校验。绑定工位中启用的机械臂与既有急停观察器保持一致:急停、离线、断开或无法取得明确状态时禁止开始,返回具体工位、设备及原因。
- 启动安全校验仅调用只读 `GET_ROBOT_STATE`,单次状态查询期限为 2 秒,不改变 120 秒业务操作默认等待。
- 执行期间仍立即响应急停并执行安全停止,不等待前端弹窗或用户确认。页面收到更新后通知并持续展示任务取消原因;停止未确认时仍保留占用,急停复位不自动续跑。刷新页面后仍可查看已持久化的取消原因。
## 升级与配置
本次新增平台记录查询和启动校验,不新增数据库表、迁移、菜单、第三方依赖或私有配置。获准发布后仍通过 `deploy/windows11/update.ps1` 构建前后端并执行既有健康检查,不改写目标私有 YAML、证书或设备地址。
代码修改及打包不会使现有 Java 进程加载新的启动校验。本地启用须按项目约定,以具备进程网络隔离的开发启动方式启动新版后端;本次不启动或恢复现场连接,也不重新创建已删除的永久模拟资源。
## 验证边界
验证使用内存模拟对象和 H2,覆盖离线范围、停用设备排除、告警去重及恢复、取消原因跨刷新保留、急停/未知状态启动拦截、只读查询期限和执行创建前拒绝;不下发现场动作。临时测试源码、构建输出和日志在验证通过后清理,项目原有回归测试保留。
后端 242 项测试及完整 JAR 打包通过;前端 27 项行为检查、3 项启动接口错误保留检查、全量类型检查及 standalone 构建通过。ESLint 无错误,保留既有 7 条格式警告;样式检查仍有原文件中的 140 项规则问题,已核对两份样式内容没有改变,本次未扩展为全文件样式整理。浏览器交互和现场设备验收不包含在这些结果中。本次未启动完整业务后端、未提交、未推送,也未发布。

View File

@ -1,6 +1,8 @@
# 可删除的模拟机器人
# 本机 AGV 模拟器
资源中心已提供一个本机测试机器人和设备:
2026-11-20 已按用户要求从开发库删除下列模拟机器人、设备及运行绑定,并关闭对应模拟器自动启动。已有演示任务、历史记录与设备资源档案保留;重新创建或启动须经用户重新明确授权。以下操作说明仅供获准恢复后使用。
原模拟资源标识:
| 资源 | 名称 | 标识 |
| --- | --- | --- |