am-freescan/scripts/verify_arm_teaching_http.py

80 lines
5.8 KiB
Python
Raw Permalink Normal View History

"""Check teaching HTTP validation and actual read-only RPCs. Never teach, record, enable or move hardware."""
import json
from pathlib import Path
from verify_cmvr_native import Client, TargetReadOnlyDb, require
OPERATIONS = ['ENTER_TEACHING_MODE', 'START_TRAJECTORY_RECORDING', 'STOP_TRAJECTORY_RECORDING',
'EXIT_TEACHING_MODE', 'COMPLETE_TEACHING', 'LIST_RECORDED_TRAJECTORIES',
'MOVE_TO_TRAJECTORY_START', 'REPLAY_RECORDED_TRAJECTORY', 'GET_ARM_INFO', 'GET_ROBOT_STATE', 'STOP_MOTION']
CONTROLS = ['enterTeachingMode', 'startTrajectoryRecording', 'stopTrajectoryRecording', 'exitTeachingMode',
'completeTeaching', 'moveToTrajectoryStart', 'replayRecordedTrajectory', 'stopMotion']
def main():
client = Client().login()
db = TargetReadOnlyDb(client)
checks, real = [], []
base = '/api/arm/teaching'
def checked(label, condition):
require(condition, label)
checks.append(label)
def occupations():
return db.select('SELECT owner_key,resource_key,status FROM lab_resource_occupation WHERE deleted=0 ORDER BY owner_key,resource_key')
before = occupations()
try:
for op in OPERATIONS:
params = {'timeoutMs': 300000, 'fileName': 'validation-only.csv'}
checked(op + ':valid parameter contract', client.native('POST', base + '/validate', {'action': 'ARM_' + op, 'params': params})['data'] is True)
invalid = [('file path', 'START_TRAJECTORY_RECORDING', {'fileName': '../x.csv'}),
('UTF8 filename bytes', 'START_TRAJECTORY_RECORDING', {'fileName': '中' * 41}),
('non-string filename', 'START_TRAJECTORY_RECORDING', {'fileName': 123}),
('fractional low frequency', 'START_TRAJECTORY_RECORDING', {'samplingFrequencyHz': 0.5}),
('high frequency', 'START_TRAJECTORY_RECORDING', {'samplingFrequencyHz': 101}),
('low speed ratio', 'REPLAY_RECORDED_TRAJECTORY', {'speedRatio': 0.05}),
('high speed ratio', 'REPLAY_RECORDED_TRAJECTORY', {'speedRatio': 1.1}),
('string speed ratio', 'REPLAY_RECORDED_TRAJECTORY', {'speedRatio': '0.5'}),
('negative velocity', 'REPLAY_RECORDED_TRAJECTORY', {'maxVelocity': -0.1}),
('fractional timeout', 'REPLAY_RECORDED_TRAJECTORY', {'timeoutMs': 100.5}),
('too long timeout', 'REPLAY_RECORDED_TRAJECTORY', {'timeoutMs': 21600001})]
for label, op, changes in invalid:
data = client.native('POST', base + '/validate', {'action': 'ARM_' + op, 'params': {'fileName': 'validation-only.csv', **changes}}, expected=None)
checked('reject ' + label, data.get('code') not in (0, 200))
for operation in CONTROLS:
data = client.native('POST', base + '/' + operation, {}, expected=None)
checked(operation + ':missing target rejected before resource lease', data.get('code') not in (0, 200))
data = client.request('POST', '/admin-api/cmvr' + base + '/' + operation, {}, expected=None, auth=False)
checked(operation + ':unauthenticated rejected', data.get('code') == 401)
for operation in ['getArmInfo', 'getRobotState', 'listRecordedTrajectories']:
data = client.native('GET', base + '/' + operation, expected=None)
checked(operation + ':missing target rejected', data.get('code') not in (0, 200))
data = client.request('GET', '/admin-api/cmvr' + base + '/' + operation, expected=None, auth=False)
checked(operation + ':unauthenticated rejected', data.get('code') == 401)
checked('invalid parameters and reads do not create or release occupations', occupations() == before)
devices = client.native('GET', '/resource/devices', query={'deviceKind': 2, 'pageSize': 100}).get('rows', [])
for device in devices:
if str(device.get('enabled')) != '1' or str(device.get('onlineStatus')) != '1':
continue
target = {'robotId': device['robotId'], 'deviceId': device['deviceId']}
for operation in ['getArmInfo', 'getRobotState', 'listRecordedTrajectories']:
data = client.native('GET', base + '/' + operation, query=target, expected=None)
result = {'operation': operation, **target, 'passed': data.get('code') in (0, 200)}
if result['passed']:
value = data['data']
if operation == 'getArmInfo': result.update(model=value.get('model'), dof=value.get('dof'))
elif operation == 'getRobotState': result.update(connected=value.get('state', {}).get('connected'), moving=value.get('state', {}).get('moving'), controlMode=value.get('state', {}).get('controlMode'))
else: result.update(trajectoryCount=len(value.get('trajectories', [])), recording=value.get('recording'), recordedSamplesType=type(value.get('recordedSamples')).__name__)
else:
result['message'] = data.get('msg') or data.get('message')
real.append(result)
checked('real read-only queries do not change occupations', occupations() == before)
report = {'passed': True, 'scope': 'HTTP validation and authorization; live device readiness is reported separately', 'realReadOnlyPassed': bool(real) and all(item['passed'] for item in real), 'checks': checks, 'count': len(checks), 'realReadOnly': real,
'hardwareControlRequests': 0, 'businessDataCreated': False, 'existingOccupationsPreserved': True}
(Path(__file__).resolve().parents[1] / '.local/arm-teaching-http.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=True))
finally:
db.close()
if __name__ == '__main__':
main()