am-freescan/am-web/src/cmvr/common/utils/scanMotorNodes.mjs

120 lines
7.0 KiB
JavaScript
Raw Normal View History

// Platform workflow kinds. Scanner 14 is a platform extension, not a vendor SDK enum.
import { SCANNER_OPERATIONS, getScannerOperation } from './scannerOperations.mjs'
export const WORKCELL_DEVICE_KIND = Object.freeze({ MOTOR: 10, SCANNER: 14 })
const field = (name, label, input, options = {}) => ({
name, label, type: 'input', input, required: true, disabled: true, ...options,
})
const timeout = () => field('timeoutMs', '超时(毫秒)', 60000, {
componentType: 'number', min: 1, max: 3600000, step: 1,
})
const unit = () => field('unit', '位置单位', 'DEGREE', {
componentType: 'select', selectOptions: [
{ value: 'DEGREE', label: '度' },
{ value: 'MILLIMETER', label: '毫米' },
{ value: 'PULSE', label: '脉冲' },
],
})
const number = (name, label, input, min = 0) => field(name, label, input, {
componentType: 'number', min, step: 0.01, precision: 4,
})
const output = (name, type, desc) => ({ name, type, desc, disabled: true, children: [] })
const position = () => number('targetPosition', '目标位置', 0, -1e9)
const queryOutputs = {
METADATA: [['service', 'string'], ['apiVersion', 'string'], ['routes', 'array<string>']],
HEALTH: [['running', 'boolean'], ['service', 'string'], ['utc', 'string']],
STATUS: [['state', 'string'], ['sessionId', 'string'], ['projectId', 'string'], ['scanning', 'boolean'], ['busy', 'boolean'], ['meshState', 'string'], ['projectReady', 'boolean'], ['deviceOnline', 'boolean'], ['stateUncertain', 'boolean'], ['restartRequired', 'boolean']],
CAPABILITIES: [['exportFormats', 'array<string>'], ['controls', 'object'], ['features', 'object'], ['calibration', 'object'], ['rawDataAvailable', 'boolean']],
SCENE: [['available', 'boolean'], ['projectUuid', 'string'], ['cloudUuid', 'string'], ['pointIdsAvailable', 'boolean'], ['pointCount', 'number'], ['markerCount', 'number']],
METRICS: [['latestSequence', 'number'], ['averageEncodedFps', 'number'], ['frameAgeMs', 'number'], ['encoderRunning', 'boolean']],
}
function scannerOutputs(op) {
const fields = op.method === 'POST' || op.key === 'TASK'
? [output('taskId', 'string', '设备命令编号'), output('state', 'string', '设备任务状态'),
{ ...output('result', 'object', '设备操作结果'), children: [output('projectId', 'string', '工程目录编号'), output('files', 'array<object>', '可下载成果文件')] }]
: (queryOutputs[op.key] || []).map(([name, type]) => output(name, type, '设备接口原始字段'))
return [...fields, output('responseJson', 'string', '完整响应 JSON 文本,保留64位整数')]
}
const specs = [
['MOTOR_ENABLE', '电机使能', '开启电机使能', []],
['MOTOR_DISABLE', '电机去使能', '关闭电机使能', []],
['MOTOR_HOME', '电机回零', '按设备配置执行回零并等待完成', []],
['MOTOR_MOVE', '电机定位', '按指定单位运动到绝对位置', [
position(), unit(), number('velocity', '速度(位置单位/秒)', 1, 0.0001),
number('acceleration', '加速度(位置单位/秒²)', 1, 0.0001),
]],
['MOTOR_WAIT', '等待电机到位', '确认电机已停止且在目标位置容差内', [position(), unit(), number('tolerance', '允许位置误差', 0.1)]],
['MOTOR_STOP', '停止电机', '请求停止并等待设备确认', []],
['MOTOR_STATUS', '读取电机状态', '读取实际位置、运动状态和故障', []],
]
export const WORKCELL_ACTION_KINDS = Object.freeze(Object.fromEntries([...specs, ...SCANNER_OPERATIONS.filter((op) => op.action).map((op) => [op.action])].map(([action]) => [
action, action.startsWith('SCANNER_') ? WORKCELL_DEVICE_KIND.SCANNER : WORKCELL_DEVICE_KIND.MOTOR,
])))
export const isWorkcellAction = (action) => Object.hasOwn(WORKCELL_ACTION_KINDS, action || '')
export function createWorkcellNodeGroups(icons = {}) {
const scannerGroup = {
collapseTitle: '扫描仪',
nodeList: SCANNER_OPERATIONS.filter((op) => op.action).map((op) => ({
icon: icons.SCANNER, name: op.title, type: 'serviceNode', nodeType: 'EDGE', action: op.action,
scannerOperation: op.key,
desc: op.method === 'POST' ? '提交设备操作并等待任务结果' : op.key === 'TASK' ? '等待设备命令终态,不代表整件扫描完成' : '读取扫描服务数据',
nodeParams: [
...(op.method === 'POST' ? [field('requestJson', '扫描操作参数', JSON.stringify(op.defaultBody, null, 2))] : []),
...(op.key === 'TASK' ? [field('taskId', '设备任务编号', '')] : []),
{ ...timeout(), input: 120000 },
],
outputType: 'json',
outputParams: scannerOutputs(op),
})),
}
return [scannerGroup, ...['MOTOR'].map((family) => ({
collapseTitle: '电机',
nodeList: specs.filter(([action]) => action.startsWith(`${family}_`)).map(([action, name, desc, params]) => ({
icon: icons[family], name, desc, action, type: 'serviceNode', nodeType: 'EDGE',
nodeParams: structuredClone([...params, timeout()]), outputType: 'json',
outputParams: [output('position', 'number', '实际位置'), output('unit', 'string', '位置单位'),
output('state', 'string', '电机状态')],
})),
}))]
}
// Only literal values can be checked before execution. Quoted values are checked after resolution.
export function validateWorkcellLiterals(action, params = []) {
if (!isWorkcellAction(action)) return []
const errors = []
const scanner = getScannerOperation(action)
if (!params.some(param => param.name === 'timeoutMs')) errors.push('缺少超时(毫秒)参数,请重新配置节点')
if (scanner?.key === 'TASK' && !params.some(param => param.name === 'taskId')) errors.push('缺少设备任务编号')
if (scanner && params.some((param) => ['planCode', 'jobId', 'format'].includes(param.name))) errors.push('旧扫描节点参数与真实接口不一致,请重新配置')
for (const param of params) {
if (param.type !== 'input') continue
const label = param.label || param.name
const value = param.input
if (param.required && (value == null || String(value).trim() === '')) {
errors.push(`${label}不能为空`)
continue
}
if (param.componentType === 'number' && value != null) {
if (typeof value !== 'number' || !Number.isFinite(value)
|| (param.min != null && value < param.min) || (param.max != null && value > param.max)
|| (param.name === 'timeoutMs' && !Number.isInteger(value))) errors.push(`${label}超出有效范围`)
}
if (param.componentType === 'select' && !param.selectOptions?.some((item) => item.value === value)) {
errors.push(`${label}无效`)
}
if (scanner && param.name === 'requestJson') {
try {
const body = JSON.parse(value)
if (!body || typeof body !== 'object' || Array.isArray(body)) errors.push('扫描参数必须为JSON对象')
} catch { errors.push('扫描参数JSON格式无效') }
}
if (scanner?.key === 'TASK' && param.name === 'taskId' && value && !/^[a-fA-F0-9]{32}$/.test(value)) errors.push('设备任务编号必须为32位十六进制字符')
}
return errors
}