am-freescan/scripts/verify_simulated_robot.py

140 lines
8.3 KiB
Python
Raw Permalink Normal View History

2026-10-22 16:18:37 +08:00
"""Verify the opt-in simulated robot through the original Java workflow engine.
Creates a temporary test case and cleans it on success. --lifecycle additionally verifies
archive, explicit removal, and explicit recreation of this fixture's own rows.
"""
import argparse
import json
import time
import uuid
from robot_simulator import (ROBOT_ID, DEVICE_ID, LOCAL, SETTINGS, ResourceStore,
read_json, write_json)
from verify_cmvr_native import Client, NativeVerifier, response_identifier, require
def demo_flow():
roles = [{'roleKey': 'sim-robot', 'displayName': '模拟机器人', 'required': True,
'deviceSlots': [{'slotKey': 'chassis', 'displayName': '模拟AGV底盘',
'deviceKind': 1, 'required': True, 'allowReuse': False}]}]
def node(identifier, kind, action, parameters=(), edge=False):
properties = dict(name={'start': '流程开始', 'move': '模拟坐标导航', 'station': '模拟站点导航',
'code': '输出模拟标记', 'end': '流程结束'}[identifier],
action=action, inputParams=[], nodeParams=[
dict(name=key, type='input', input=value) for key, value in parameters])
if edge:
properties.update(nodeType='EDGE', executionTarget=dict(roleKey='sim-robot', deviceSlotKey='chassis'))
return dict(id=identifier, type=kind, x=150, y=100, properties=properties)
nodes = [node('start', 'start', 'START'),
node('move', 'serviceNode', 'AGV_MOVE_TO_POINT', [('x', 2), ('y', 3), ('theta', 0.5)], True),
node('station', 'serviceNode', 'AGV_MOVE_TO_STATION', [('stationId', 'SIM-STATION-1')], True),
node('code', 'code', 'CODE', [('code', 'function handler(params) { return {simulated: true, marker: "SIMULATED", message: "模拟设备验证完成,无实际硬件运动"}; }')]),
node('end', 'end', 'END')]
nodes[0]['properties'].update(schemaVersion=2, resourceRoles=roles)
for i, node_value in enumerate(nodes):
node_value['x'] = 150 + i * 270
node_value['y'] = 180
edges = [dict(id='sim-edge-' + str(i), sourceNodeId=nodes[i]['id'], targetNodeId=nodes[i+1]['id'],
sourceAnchorId=nodes[i]['id']+'_out', targetAnchorId=nodes[i+1]['id']+'_in')
for i in range(len(nodes)-1)]
return dict(schemaVersion=2, nodes=nodes, edges=edges)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--lifecycle', action='store_true')
args = parser.parse_args()
client = Client().login()
verifier = NativeVerifier(client)
report = dict(simulated=True, robotId=ROBOT_ID, deviceId=DEVICE_ID, checks=[])
def checked(name):
report['checks'].append(name)
print('PASS', name, flush=True)
rows = client.native('GET', '/resource/robots', query={'robotId': ROBOT_ID})['rows']
require(len(rows) == 1 and rows[0]['connectStatus'] == '1' and rows[0]['onlineDeviceCount'] == 1,
'Expected exactly one online simulated robot and device')
client.native('POST', '/resource/robots/' + ROBOT_ID + '/sync-runtime')
checked('原资源接口在线状态与gRPC状态同步')
client.native('POST', '/resource/robots/' + ROBOT_ID + '/navigate-to-position',
query={'x': 0, 'y': 3.5, 'theta': 0.5})
pose = client.native('GET', '/resource/robots/' + ROBOT_ID + '/location')['data']
require(pose == {'x': 0, 'y': 3.5, 'theta': 0.5}, 'Realtime location did not reflect simulated movement')
checked('原资源导航及实时坐标JSON接口')
owners={r['owner_key'] for r in client.request('GET','/admin-api/lab/scan-task/resource-occupations')['data']
if r.get('robot_id')==ROBOT_ID and r['owner_key'].startswith('MANUAL:')}
require(len(owners)==1,'Expected one manual operation session after navigation')
client.request('POST','/admin-api/lab/scan-task/clear-occupation',dict(ownerKey=owners.pop(),reason=verifier.prefix+' navigation verification finished'))
# Wait longer than the normal 15-second heartbeat timeout.
time.sleep(17)
client.native('POST', '/resource/robots/' + ROBOT_ID + '/sync-runtime')
checked('超过15秒后持续心跳仍有效')
graph = demo_flow()
demo = {}
if not demo:
case_id = uuid.uuid4().hex
client.native('POST', '/aima/testcase', dict(id=case_id, caseCode=(verifier.prefix + '_AGV')[:49],
caseName=verifier.prefix + ' AGV导航流程', caseCategory='功能测试', enabled='0', priority='2',
testDescription='SIMULATED:本机模拟AGV,验证流程、资源分配和执行日志。',
precondition='模拟机器人已启动', testSteps='开始→模拟坐标导航→模拟站点导航→输出模拟标记→结束',
expectedResult='运行成功,日志明确标记SIMULATED,不代表硬件检测结果',
remark='SIMULATED / 可删除的流程验证用例'))
item = client.native('GET', '/aima/testcase/' + case_id)['data']['detectItemId']
version = verifier.publish(item, graph, 'SIMULATED local AGV fixture')
demo = dict(caseId=case_id, itemId=item, versionId=version['id'])
assignments = [dict(roleKey='sim-robot', members=[dict(memberKey='sim-1', robotId=ROBOT_ID,
devices={'chassis': DEVICE_ID})])]
instance_id = response_identifier(client.native('POST', '/flow/executeTrial',
dict(itemId=demo['itemId'], flowData=json.dumps(graph, ensure_ascii=False),
robotId=ROBOT_ID, runtimeAssignments=assignments, runParams={})))
verifier.wait_native(instance_id)
logs = verifier.node_logs(instance_id)
station = next(row for row in logs if row.get('action') == 'AGV_MOVE_TO_STATION')
require('SIMULATED' in (station.get('paramsOut') or ''), 'AGV result did not retain simulation marker')
require(any(result.get('simulated') is True for result in verifier.code_results(instance_id)),
'Final simulated result was not reached')
checked('原版角色分配→坐标导航→站点导航→结果输出完整试运行成功')
report.update(demo=demo, trialInstanceId=instance_id)
if args.lifecycle:
import subprocess
import sys
def manage(action):
subprocess.run([sys.executable, str(LOCAL.parents[1] / 'scripts/robot_simulator.py'), action], check=True)
manage('create')
require(client.native('GET', '/resource/robots', query={'robotId': ROBOT_ID})['total'] == 1,
'Idempotent create duplicated robot')
checked('重复创建不重复插入')
client.native('DELETE', '/resource/robots/' + rows[0]['id'])
deadline = time.monotonic() + 10
while read_json(SETTINGS, {}).get('enabled') and time.monotonic() < deadline:
time.sleep(0.2)
require(not read_json(SETTINGS, {}).get('enabled'), 'UI archive did not disable simulator')
time.sleep(1)
require(not client.native('GET', '/resource/robots', query={'robotId': ROBOT_ID})['rows'],
'Archived robot reappeared')
checked('资源中心删除机器人后自动停止且不重建')
manage('remove')
store = ResourceStore()
try:
with store.cursor() as cursor:
cursor.execute('SELECT COUNT(*) AS n FROM iot_robot WHERE robot_id=%s', (ROBOT_ID,))
require(cursor.fetchone()['n'] == 0, 'Robot not fully removed')
cursor.execute('SELECT COUNT(*) AS n FROM iot_device WHERE robot_id=%s', (ROBOT_ID,))
require(cursor.fetchone()['n'] == 0, 'Device not fully removed')
finally:
store.connection.close()
checked('移除命令完整清理本模拟器的机器人和设备')
manage('create')
client.native('POST', '/resource/robots/' + ROBOT_ID + '/sync-runtime')
checked('显式重建后在线可用,留给用户验证')
from cleanup_verification import cleanup
report['cleanup'] = cleanup([verifier.prefix], apply=True)
(LOCAL / 'demo.json').unlink(missing_ok=True)
(LOCAL / 'verification.json').unlink(missing_ok=True)
print(json.dumps(report, ensure_ascii=False), flush=True)
if verifier._db:
verifier.db.close()
if __name__ == '__main__':
main()