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

212 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Platform workflow kinds. Scanner 14 is a platform extension, not a vendor SDK enum.
import { SCANNER_OPERATIONS, getScannerOperation } from './scannerOperations.mjs'
import { validateScannerParameters } from './scannerParameters.mjs'
import { frameworkReferences } from './frameworkReferences.mjs'
import { validateRequestBindings } from './scannerRequestBindings.mjs'
import { ROTARY_BASE_ACTIONS, validateRotaryBaseParameters } from './rotaryBaseParameters.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', '超时(毫秒)', 120000, {
componentType: 'number', min: 1, max: 3600000, step: 1,
})
const unit = () => field('unit', '位置单位', 'DEGREE', {
componentType: 'select', selectOptions: [
{ value: 'DEGREE', label: '度' },
{ value: 'RADIAN', label: '弧度(rad)' },
],
})
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 = {
BATTERY: [['source','string'], ['freshnessLimitMs','number'], ['scanner','object'], ['tracker','object']],
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'], ['scanMode', 'string'], ['scanType', 'string'], ['scanDevice', 'string'], ['initialized', 'boolean'], ['calibrationActive', 'boolean'], ['deviceType', 'number'], ['frameworkImported', 'boolean'], ['frameworkFileCount', 'number'], ['projectHasAcquisition', 'boolean'], ['frameworkHasAcquisition', 'boolean'], ['frameworkOptimized', 'boolean']],
CAPABILITIES: [['exportFormats', 'array<string>'], ['controls', 'object'], ['features', 'object'], ['calibration', 'object'], ['calibrationModes', 'array<object>'], ['rawDataAvailable', 'boolean']],
SCENE: [['available', 'boolean'], ['reason', 'string'], ['source', 'string'], ['frameId', 'number'], ['datatype', 'number'], ['capturedUnixMs', 'number'], ['version', 'string'], ['projectUuid', 'string'], ['cloudUuid', 'string'], ['pointIdsAvailable', 'boolean'], ['pointIdNote', 'string'], ['coordinates', 'string'], ['cloudSource', 'string'], ['meshSource', 'string'], ['pointCount', 'number'], ['markerCount', 'number'], ['meshPointCount', 'number'], ['meshFaceCount', 'number'], ['sourcePointCount', 'number'], ['sourceMarkerCount', 'number'], ['sourceMeshPointCount', 'number'], ['sourceMeshFaceCount', 'number'], ['pointsTruncated', 'boolean'], ['markersTruncated', 'boolean'], ['meshTruncated', 'boolean']],
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, '设备接口原始字段'))
if (['CALIBRATION_MODE','CALIBRATION_APPLY_LAST','TASK'].includes(op.key))
fields.find(field => field.name === 'result').children.push(output('mode', 'number', '已成功设置或应用的标定类别编号'), output('modeName', 'string', '标定类别中文名称;仅相关成功任务返回'))
if (op.key === 'CAPABILITIES')
fields.find(field => field.name === 'calibration').children = [output('mode','number','当前命令缓存的标定类别;不能据此认定标定合格'),output('modeName','string','标定类别中文名称')]
if (op.key === 'BATTERY') {
fields.find(field => field.name === 'scanner').children = [output('percent','number','有效电量百分比;未知时为空'),output('available','boolean','电量可用'),output('fresh','boolean','消息未过期'),output('updatedUtc','string','消息接收时间')]
fields.find(field => field.name === 'tracker').children = [output('channels','array<object>','各独立频道电量,不推断物理电池槽')]
}
if (op.key === 'STATUS') fields.push(output('battery','object','扫描仪和跟踪仪各频道电量'))
if (op.key === 'EXPORT' || op.key === 'TASK') fields.push(output('frameworkFiles', 'array<object>', '已筛选P3/TXT/ASC,直接引用到导入框架组件'), output('frameworkUrls', 'array<string>', '框架下载URL'))
if (op.key === 'FRAMEWORK_IMPORT') fields.push(output('frameworkTransfer', 'array<object>', '源URL、登记编号及复用记录'))
if (op.method === 'POST') fields.push({ ...output('request', 'object', '本次请求参数,非硬件状态读回'), children: (op.requestFields || []).map(field => output(field.key, 'any', field.label)) }, output('requestJson', 'string', '本次请求JSON,保留原始整数和显式null'))
return [...fields, output('responseJson', 'string', '完整响应 JSON 文本,保留64位整数')]
}
const specs = [
['MOTOR_SET_MODE', '设置模式', '仅设置模式;切换前先停止并去使能,再设置模式并使能', [field('mode', '控制模式', 1, { componentType: 'select', selectOptions: [{ value: 1, label: '轮廓位置' }, { value: 3, label: '轮廓速度' }] })]],
['MOTOR_ENABLE', '使能', '新版接口以轮廓位置模式使能,不下发目标位置;速度控制由速度接口设置', []],
['MOTOR_DISABLE', '去使能', '关闭驱动力;驱动确认不代表机械已停稳,也不是硬件急停', []],
['MOTOR_MOVE', '轮廓位置控制', '按输出轴绝对位置定位,范围为±1800°(弧度模式为±10π),收到到位反馈后继续;0表示回到绝对零位', [
position(), unit(), number('velocity', '轮廓速度(所选单位/秒)', 15, 0.0001),
number('acceleration', '加速度(所选单位/秒²)', 20, 0.0001),
]],
['MOTOR_VELOCITY', '轮廓速度控制', '正负控制方向,0下发零速目标;指令成功不表示停稳。持续运行后应安排去使能', [unit(), number('velocity', '目标速度(所选单位/秒)', 0, -57.29578), number('acceleration', '加速度(所选单位/秒²)', 20, 0.0001)]],
['MOTOR_LIST', '获取电机列表', '获取电机列表,只读', []],
['MOTOR_GET_INFO', '获取电机信息', '获取电机标识和服务限值,只读;限值不是硬件限位回读', []],
['MOTOR_GET_STATE', '获取电机状态', '读取位置、速度、模式和故障,并检查反馈是否有效', []],
['MOTOR_GET_MODE', '读取运行模式', '读取当前运行模式,以有效状态反馈为准', []],
['MOTOR_GET_Q', '读取输出轴位置', '读取输出轴位置,单位为弧度,以有效位置反馈为准', []],
['MOTOR_GET_QD', '读取输出轴速度', '读取输出轴速度,单位为弧度每秒,以有效速度反馈为准', []],
['MOTOR_REACHED_TARGET', '读取位置到达状态', '读取是否到达目标位置;未到达时立即返回,不等待', []],
['MOTOR_QUICK_STOP', '快速停止', '请求驱动快速停止;驱动确认不代表机械停稳,也不替代硬件急停', []],
['MOTOR_HOMING', '自动机械回零', '按方法4反向搜索原点开关和编码器零位信号,建立零位;会使能并运动', [
field('method','回零方法',4,{componentType:'select',selectOptions:[{value:4,label:'方法4(反向搜索原点开关和编码器零位信号)'}]}),
{...number('fastSpeed','搜索原点开关速度(弧度/秒)',0.105,0.0001),max:1},
{...number('slowSpeed','搜索编码器零位信号速度(弧度/秒)',0.0105,0.0001),max:1},
{...number('acceleration','回零加速度(弧度/秒²)',1,0.0001),max:1},
{...number('timeoutSeconds','服务端等待时间(秒)',120,1),max:300},
{...number('offset','输出轴原点偏移(弧度)',0,-2*Math.PI),max:2*Math.PI,precision:undefined},
]],
]
const motorFeedbackOutputs = () => [output('feedbackValid','boolean','位置/速度反馈有效;无效时不输出测量值'), output('statusValid','boolean','模式/故障/使能等状态有效'),
output('position','number','有效反馈下的输出轴位置,rad'),output('velocity','number','有效反馈下的输出轴速度,rad/s'),output('mode','number','有效状态下的当前模式'),output('statusWord','number','有效状态下的驱动状态字'),output('errorCode','number','有效状态下的驱动错误码'),output('enabled','boolean','有效状态下的驱动使能'),output('fault','boolean','有效状态下的故障'),
output('sampledAtSeconds','number','反馈采样时间'),output('feedbackUnit','string','反馈固定RADIAN,与请求选择的单位分别说明'),
{...output('state','object','仅包含有效反馈组'),children:[output('feedbackValid','boolean','位置/速度有效'),output('statusValid','boolean','模式/故障有效'),output('position','number','rad'),output('velocity','number','rad/s'),output('mode','number','模式'),output('enabled','boolean','驱动使能'),output('fault','boolean','故障'),output('statusWord','number','状态字'),output('errorCode','number','错误码')]},
{...output('info','object','电机标识和服务配置限值'),children:['managerId','nodeId','jointName','driver','limitQLower','limitQUpper','limitVelocity','limitAcceleration'].map(key=>output(key,'any',key))}]
export const WORKCELL_ACTION_KINDS = Object.freeze(Object.fromEntries([...specs, ...['MOTOR_HOME', 'MOTOR_WAIT', 'MOTOR_STOP', 'MOTOR_STATUS'].map(action => [action]), ...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 || '')
let outputContracts
const oldMotorTitles = { MOTOR_LIST:'ListMotors', MOTOR_GET_INFO:'GetInfo', MOTOR_GET_STATE:'GetState', MOTOR_GET_MODE:'getMode', MOTOR_GET_Q:'getQ', MOTOR_GET_QD:'getQd', MOTOR_REACHED_TARGET:'reachedTargetQ', MOTOR_QUICK_STOP:'quickStop' }
export function refreshWorkcellOutputs(nodes = []) {
const presets = outputContracts || (outputContracts = new Map(createWorkcellNodeGroups().flatMap(group => group.nodeList).map(node => [node.action, node.outputParams])))
const merge = (existing = [], declared = []) => {
const result = Array.isArray(existing) ? JSON.parse(JSON.stringify(existing)) : []
for (const field of declared) {
const saved = result.find(item => item.name === field.name)
if (!saved) result.push(structuredClone(field))
else {
if(field.name==='mechanicalStateAvailable' && saved.desc==='固定false;当前协议未提供实时状态') saved.desc=field.desc
if (field.children?.length) saved.children = merge(saved.children || [], field.children)
}
}
return result
}
for (const node of nodes) {
const spec = specs.find(([action]) => action === node.properties?.action)
if (spec) {
if (oldMotorTitles[spec[0]] && node.properties.name === oldMotorTitles[spec[0]]) node.properties.name = spec[1]
node.properties.desc = spec[2]
}
const outputs = presets.get(node.properties?.action)
if (outputs) node.properties.outputParams = merge(node.properties.outputParams, outputs)
if(node.properties?.action==='MOTOR_ENABLE' && node.properties.desc==='按当前模式使能,不下发目标位置') node.properties.desc='新版接口以轮廓位置模式使能,不下发目标位置;速度控制由速度接口设置'
}
return nodes
}
export function createWorkcellNodeGroups(icons = {}) {
const scannerGroup = {
collapseTitle: '扫描仪',
nodeList: SCANNER_OPERATIONS.filter((op) => op.action).sort((a,b) => Number(a.key === 'BATTERY') - Number(b.key === 'BATTERY')).map((op) => ({
icon: icons.SCANNER, name: op.title, type: 'serviceNode', nodeType: 'EDGE', action: op.action,
scannerOperation: op.key,
desc: op.note || (op.method === 'POST' ? '提交设备操作并等待任务结果' : op.key === 'TASK' ? '等待设备命令终态,不代表整件扫描完成' : '读取扫描服务数据'),
nodeParams: [
...(op.method === 'POST' ? [field('requestJson', '扫描操作参数', JSON.stringify(op.key === 'FRAMEWORK_IMPORT' ? {} : op.defaultBody, null, 2))] : []),
...(op.key === 'FRAMEWORK_IMPORT' ? [field('frameworkUrls', '框架文件URL', '', { type: 'quote', quote: [], quoteType: 'output' })] : []),
...(op.key === 'TASK' ? [field('taskId', '设备任务编号', '')] : []),
timeout(),
],
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('driverAcknowledged', 'boolean', '驱动确认本次操作'),
...(action === 'MOTOR_MOVE' ? [output('reachedTarget', 'boolean', '位置控制到位确认'), output('targetPosition', 'number', '本次目标位置,非实时测量位置'), output('unit', 'string', '本次目标位置单位')] : []),
...(action === 'MOTOR_VELOCITY' ? [output('targetVelocity', 'number', '已下发的目标速度,不是实际速度'), output('unit', 'string', '本次目标速度单位'), output('motionCompleted', 'boolean', '固定false;速度接口不确认运动完成')] : []),
...(action === 'MOTOR_DISABLE' ? [output('driveDisabledConfirmed', 'boolean', '驱动已确认去使能')] : []),
...(action === 'MOTOR_HOMING' ? [output('homingCompleted','boolean','机械回零成功且确认到位'),output('reachedTarget','boolean','回零到位')] : []),
...(action === 'MOTOR_REACHED_TARGET' ? [output('reachedTarget','boolean','本次读取的到达标志'),output('reachedTargetValid','boolean','成功响应中的有效到达标志')] : []),
...(action === 'MOTOR_QUICK_STOP' ? [output('quickStopAcknowledged','boolean','驱动已确认快速停止请求'),output('standstillConfirmed','boolean','固定false,不将控制确认当作机械停稳')] : []),
...(action === 'MOTOR_LIST' ? [output('motors','array<object>','电机列表')] : motorFeedbackOutputs()),
{ ...output('request', 'object', '本次请求参数,非机械状态读回'), children: params.map(field => output(field.name, field.componentType === 'number' ? 'number' : 'any', field.label)) },
output('detail', 'string', '设备反馈说明'), output('mechanicalStateAvailable', 'boolean', '至少一组反馈有效;具体值仍检查feedbackValid/statusValid'), output('responseJson', 'string', '操作反馈JSON')],
})),
}))]
}
// 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)
const bindings = params.find(param => param.name === 'requestFields')?.children || []
if (scanner) { try { validateRequestBindings(scanner, bindings) } catch (error) { errors.push(error.message) } }
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对象')
else if(scanner.key === 'PARAMETERS') {
const known = { ...body }; bindings.forEach(field => delete known[field.name]); validateScannerParameters(known)
}
else if(scanner.key === 'FRAMEWORK_IMPORT' && params.some(p => p.name === 'frameworkUrls')) {
if(Object.keys(body).some(key => key !== 'confirm')) errors.push('URL引用不能同时填写旧文件编号,请重新配置组件')
}
} catch (error) { errors.push(error instanceof SyntaxError ? '扫描参数JSON格式无效' : error.message) }
}
if (scanner?.key === 'TASK' && param.name === 'taskId' && value && !/^[a-fA-F0-9]{32}$/.test(value)) errors.push('设备任务编号必须为32位十六进制字符')
if (scanner?.key === 'FRAMEWORK_IMPORT' && param.name === 'frameworkUrls') {
try { frameworkReferences(value) } catch (error) { errors.push(error.message) }
}
}
if (String(action).startsWith('MOTOR_')) {
if (!ROTARY_BASE_ACTIONS.includes(action)) errors.push('旋转底座接口未开放此旧电机动作,请重新选择已接入组件')
else if (params.every(param => param.type === 'input')) {
try { validateRotaryBaseParameters(action, Object.fromEntries(params.map(param => [param.name, param.input]))) }
catch (error) { errors.push(error.message) }
}
}
return errors
}