完善扫描流式预览、成果归档与PLY/STL查看、补扫历史、执行步骤及日志展示,支持局域网访问和改名节点的原始组件识别。修复试运行终止后的占用释放及未采集时重复暂停SDK的问题,增加终止中交互与回归验证。 验证:后端1114项通过、18项既有跳过;前端109项通过,类型检查及构建通过;Python脚本54项通过;模拟扫描设备7组试运行/终止接口回归通过。
152 lines
12 KiB
Python
152 lines
12 KiB
Python
"""Create two retained user test tasks. No device controls or physical confirmations."""
|
||
import csv
|
||
import datetime as dt
|
||
import io
|
||
import json
|
||
from pathlib import Path
|
||
import urllib.request
|
||
import uuid
|
||
import argparse
|
||
import time
|
||
from prepare_real_scan_task import flow, ROBOT, DEVICE
|
||
from verify_cmvr_native import Client, TargetReadOnlyDb, require
|
||
|
||
ROOT=Path(__file__).resolve().parents[1]
|
||
MANIFEST=ROOT/'docs/user-scan-two-tasks-20261023.json'
|
||
SPECS=[('STREAM','【现场测试A】流式预览与60秒采集',False),
|
||
('EXPORT','【现场测试B】60秒采集与网格导出',True)]
|
||
|
||
|
||
def graph(export):
|
||
result=flow()
|
||
result['nodes']=[n for n in result['nodes'] if n['properties']['action']!='SCANNER_SNAPSHOT']
|
||
if export:
|
||
extra=[]
|
||
for identifier,label,action,body in [
|
||
('mesh','生成扫描网格','SCANNER_MESH',{'maxTriangles':250000}),
|
||
('confirmMesh','确认扫描网格','SCANNER_MESH_CONFIRM',{}),
|
||
('export','导出PLY和STL模型','SCANNER_EXPORT',{'formats':['PLY','STL']})]:
|
||
extra.append(dict(id=identifier,type='serviceNode',properties=dict(name=label,action=action,inputParams=[],
|
||
nodeType='EDGE',executionTarget=dict(roleKey='scanner',deviceSlotKey='scanner'),
|
||
nodeParams=[dict(name='requestJson',type='input',input=json.dumps(body)),dict(name='timeoutMs',type='input',input=600000)])))
|
||
result['nodes'][-1:-1]=extra
|
||
nodes=result['nodes']
|
||
for i,node in enumerate(nodes):node.update(x=100+250*i,y=180)
|
||
result['edges']=[dict(id='edge-'+str(i),sourceNodeId=a['id'],targetNodeId=b['id']) for i,(a,b) in enumerate(zip(nodes,nodes[1:]))]
|
||
return result
|
||
|
||
|
||
def main(repair_failed=False):
|
||
client=Client().login();db=TargetReadOnlyDb(client)
|
||
api=lambda method,path,body=None,query=None:client.request(method,'/admin-api'+path,body,query,expected=(0,))['data']
|
||
record=json.loads(MANIFEST.read_text(encoding='utf-8')) if MANIFEST.exists() else dict(prefix='USER-SCAN-20261023',retainedForUser=True,tasks=[])
|
||
def save():MANIFEST.write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||
for entry in record['tasks']:
|
||
if entry.get('taskId') and not entry.get('batchId'):
|
||
entry.update(batchId=record['batchId'],batchNo=record.get('batchNo'))
|
||
if entry.get('taskId'):
|
||
existing=api('GET','/lab/scan-task/get',query=dict(taskId=entry['taskId']))
|
||
if existing['config'].get('startedAt'):
|
||
require(repair_failed and existing['task']['status']=='BLOCKED' and not existing['config'].get('stopPending')
|
||
and all(u['status']=='FAILED' for u in existing['units']),'Started task is frozen; only stopped failed tasks can be replaced explicitly')
|
||
old={k:entry[k] for k in ['taskId','taskNo','versionId','batchId']}
|
||
entry.setdefault('previousTasks',[]).append(old)
|
||
entry['externalTaskNo']=record['prefix']+'-'+entry['kind']+'-R'+str(len(entry['previousTasks']))
|
||
for key in ['taskId','taskNo','url','batchId','batchNo','precheck']:entry.pop(key,None)
|
||
save()
|
||
for key,title,export in SPECS:
|
||
entry=next((t for t in record['tasks'] if t['kind']==key),None)
|
||
if entry is None:
|
||
entry=dict(kind=key,title=title,externalTaskNo=record['prefix']+'-'+key);record['tasks'].append(entry);save()
|
||
note=('用户要求保留的现场测试任务。先停止采集并等待成功回执,再新建独立Trak工程并采集60秒;'+
|
||
('停止后生成并确认网格,导出PLY/STL,网格数量上限25万;该SDK导出路径待现场验证。' if export else '使用MJPEG流式预览,完成采集后停止,不请求三维快照。')+
|
||
'样件100×80×50mm、0.5kg为用户授权预设;实际收样、装夹和启动由操作人确认;不调用原始场景快照接口,不接电机。')
|
||
entry['description']=note
|
||
if not entry.get('caseId'):
|
||
case_id=uuid.uuid4().hex
|
||
client.native('POST','/aima/testcase',dict(id=case_id,caseCode=entry['externalTaskNo'],caseName=title,
|
||
caseCategory='功能测试',enabled='0',priority='2',testDescription=note,
|
||
precondition='现场扫描仪已连接、SDK就绪,操作人确认实物及装夹。',
|
||
testSteps='→'.join(n['properties']['name'] for n in graph(export)['nodes']),
|
||
expectedResult='真实设备命令成功;'+('生成实际可读PLY/STL文件,供网页三维查看。' if export else '实时画面流畅,60秒采集后停止并完成任务。'),remark=note))
|
||
case=client.native('GET','/aima/testcase/'+case_id)['data'];entry.update(caseId=case_id,itemId=case['detectItemId']);save()
|
||
if not entry.get('versionId') or entry.get('flowRevision')!=2:
|
||
case=client.native('GET','/aima/testcase/'+entry['caseId'])['data']
|
||
case.update(testDescription=note,testSteps='→'.join(n['properties']['name'] for n in graph(export)['nodes']),remark=note)
|
||
client.native('PUT','/aima/testcase',case)
|
||
item=client.native('GET','/test/detect/'+entry['itemId'])['data']
|
||
saved=client.native('PUT','/flow/draft',dict(id=entry['itemId'],flowData=json.dumps(graph(export),ensure_ascii=False),config={},draftRevision=item.get('draftRevision',0)))['data']
|
||
release=client.native('POST','/flow/publish',dict(id=entry['itemId'],draftRevision=saved['draftRevision'],publishNote=note))['data']
|
||
entry.update(versionId=release['id'],versionNo=release['versionNo'],flowRevision=2);save()
|
||
pending=[e for e in record['tasks'] if not e.get('batchId')]
|
||
if pending:
|
||
columns=['外部任务编号','试验名称','项目名称','车型/产品','试验类型','试验要求','优先级','计划完成日期','申请人','样品编号','样品数量','方法号','备注','样品名称','零件号']
|
||
content=io.StringIO(newline='');writer=csv.writer(content);writer.writerow(columns)
|
||
for entry in pending:
|
||
writer.writerow([entry['externalTaskNo'],entry['title'],'AM FreeScan 现场验证','','OTHER',entry['description'],'NORMAL',
|
||
(dt.datetime.now()+dt.timedelta(days=7)).strftime('%Y-%m-%d'),'admin',entry['externalTaskNo']+'-SAMPLE',1,entry['caseId'],entry['description'],'现场小型测试样件',''])
|
||
boundary='----AMFreeScanUser'+uuid.uuid4().hex
|
||
raw=(f'--{boundary}\r\nContent-Disposition: form-data; name="templateVersion"\r\n\r\nv2.0\r\n'
|
||
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="user-scan-pair-20261023.csv"\r\nContent-Type: text/csv\r\n\r\n').encode()
|
||
raw+=content.getvalue().encode('utf-8-sig')+f'\r\n--{boundary}--\r\n'.encode()
|
||
req=urllib.request.Request(client.base_url+'/admin-api/lab/task/import/upload',data=raw,method='POST',
|
||
headers={'tenant-id':'1','Authorization':'Bearer '+client._token,'Content-Type':'multipart/form-data; boundary='+boundary})
|
||
with urllib.request.urlopen(req,timeout=40) as response:uploaded=json.load(response)
|
||
require(uploaded.get('code')==0,'Upload failed: '+str(uploaded.get('msg')))
|
||
batch=uploaded['data'];record.update(batchId=batch['id'],batchNo=batch.get('batchNo'));save()
|
||
for entry in pending:entry.update(batchId=batch['id'],batchNo=batch.get('batchNo'))
|
||
save()
|
||
require(not batch.get('errorRows'),'Import validation failed; retained batch requires inspection')
|
||
for batch_id in sorted({e['batchId'] for e in record['tasks']}):
|
||
api('POST',f"/lab/task/import/{batch_id}/commit",dict(importValidOnly=False))
|
||
fixture=json.loads((ROOT/'docs/real-scan-ready-20261023.json').read_text(encoding='utf-8'))['fixtureId']
|
||
for entry in record['tasks']:
|
||
page=api('GET','/lab/task/page',query=dict(pageNo=1,pageSize=100,externalTaskNo=entry['externalTaskNo']))
|
||
found=[x for x in page['list'] if x['externalTaskNo']==entry['externalTaskNo']];require(len(found)==1,'Expected exactly one task per variant')
|
||
entry.update(taskId=found[0]['id'],taskNo=found[0]['taskNo'],url=f"http://localhost:5180/lab/scan-task/{found[0]['id']}");save()
|
||
detail=api('GET','/lab/scan-task/get',query=dict(taskId=entry['taskId']));cfg=detail['config']
|
||
require(not cfg.get('startedAt') and not cfg.get('resourcesAcquiredAt'),'Task is already in use; do not overwrite')
|
||
if cfg.get('robotId')!=ROBOT or cfg.get('versionId')!=entry['versionId']:
|
||
api('PUT','/lab/scan-task/prepare',dict(taskId=entry['taskId'],expectedRevision=cfg['revision'],testCaseId=entry['caseId'],versionId=entry['versionId'],
|
||
sampleReceived=False,fixtureConfirmed=False,requireFixture=True,fixtureId=fixture,lengthMm=100,widthMm=80,heightMm=50,weightKg=.5,
|
||
runParams={},robotId=ROBOT,reservationMode='IMMEDIATE',expectedMinutes=30 if entry['kind']=='EXPORT' else 10,
|
||
runtimeAssignments=[dict(roleKey='scanner',members=[dict(memberKey='scanner-1',robotId=ROBOT,devices={'scanner':DEVICE})])]))
|
||
detail=api('GET','/lab/scan-task/get',query=dict(taskId=entry['taskId']))
|
||
published=json.loads(detail['flowData']);validated=0
|
||
for node in published['nodes']:
|
||
props=node['properties'];action=props['action'];require(action!='SCANNER_SNAPSHOT','Unexpected raw snapshot node')
|
||
if props.get('nodeType')=='EDGE':
|
||
params={p['name']:p['input'] for p in props['nodeParams']}
|
||
op={'SCANNER_STATUS':'STATUS','SCANNER_CREATE_PROJECT':'CREATE_PROJECT','SCANNER_PREVIEW_START':'PREVIEW_START','SCANNER_START':'SCAN_START',
|
||
'SCANNER_STOP':'SCAN_STOP','SCANNER_MESH':'MESH','SCANNER_MESH_CONFIRM':'MESH_CONFIRM','SCANNER_EXPORT':'EXPORT'}[action]
|
||
client.native('POST','/scanner/validate',dict(operation=op,requestJson=params['requestJson']));validated+=1
|
||
entry.update(validatedScannerNodes=validated,fixtureId=fixture,actions=[n['properties']['action'] for n in published['nodes']],quantity=len(detail['units']))
|
||
for table in ('lab_execution','lab_resource_occupation'):
|
||
require(db.select('SELECT COUNT(*) n FROM '+table+' WHERE task_id=%s AND deleted=0',(entry['taskId'],))[0]['n']==0,'Preparation unexpectedly started or occupied a device')
|
||
save()
|
||
for entry in record['tasks']:
|
||
for old in entry.get('previousTasks',[]):
|
||
previous=api('GET','/lab/scan-task/get',query=dict(taskId=old['taskId']))
|
||
if previous['task']['status']=='CANCELLED':continue
|
||
status=client.native('GET','/scanner/status')['data']
|
||
require(status.get('scanning') is False and status.get('busy') is False and not status.get('stateUncertain'),'Wait for scanner to stop before releasing old failed task')
|
||
api('POST','/lab/scan-task/cancel',dict(taskId=old['taskId'],reason='保留scan_active失败记录,使用创建工程前先停采集的修正版 '+entry['taskNo']))
|
||
deadline=time.monotonic()+30
|
||
while True:
|
||
previous=api('GET','/lab/scan-task/get',query=dict(taskId=old['taskId']))
|
||
if previous['task']['status']=='CANCELLED' and not previous['resourceState'].get('leases'):break
|
||
require(time.monotonic()<deadline,'Old resource release pending');time.sleep(.3)
|
||
old['status']='CANCELLED';save()
|
||
for entry in record['tasks']:
|
||
entry['precheck']=api('POST','/lab/scan-task/precheck',dict(taskId=entry['taskId']))
|
||
save()
|
||
require(all(x['passed'] for x in entry['precheck']['items'] if x['code'] not in ('RECEIPT','FIXTURE')),'Unexpected non-physical precheck blocker')
|
||
record.update(preparedAt=dt.datetime.now().astimezone().isoformat(),scannerControlsSent=0,robotId=ROBOT,deviceId=DEVICE,
|
||
defaults=dict(lengthMm=100,widthMm=80,heightMm=50,weightKg=.5),physicalConfirmationRequired=True,runSequentially=True)
|
||
save();print(json.dumps(record,ensure_ascii=False))
|
||
|
||
|
||
if __name__=='__main__':
|
||
parser=argparse.ArgumentParser();parser.add_argument('--repair-failed',action='store_true')
|
||
main(parser.parse_args().repair_failed)
|