|
| 1 | +from contextlib import ExitStack |
| 2 | + |
| 3 | +from ophyd_async.core import Device |
| 4 | +from ophyd_async.epics.motor import Motor |
| 5 | +from ophyd_async.testing import ( |
| 6 | + callback_on_mock_put, |
| 7 | + set_mock_value, |
| 8 | +) |
| 9 | + |
| 10 | + |
| 11 | +def patch_motor( |
| 12 | + motor: Motor, |
| 13 | + initial_position: float = 0, |
| 14 | + deadband: float = 0.001, |
| 15 | + velocity: float = 3, |
| 16 | + max_velocity: float = 5, |
| 17 | + low_limit_travel: float = float("-inf"), |
| 18 | + high_limit_travel: float = float("inf"), |
| 19 | +): |
| 20 | + """ |
| 21 | + Patch a mock motor with sensible default values so that it can still be used in |
| 22 | + tests and plans without running into errors as default values are zero. |
| 23 | +
|
| 24 | + Parameters: |
| 25 | + motor: The mock motor to set mock values with. |
| 26 | + initial_position: The default initial position of the motor to be set. |
| 27 | + deadband: The tolerance between readback value and demand setpoint which the |
| 28 | + motor is considered at position. |
| 29 | + velocity: Requested move speed when the mock motor moves. |
| 30 | + max_velocity: The maximum allowable velocity that can be set for the motor. |
| 31 | + low_limit_travel: The lower limit that the motor can move to. |
| 32 | + high_limit_travel: The higher limit that the motor can move to. |
| 33 | + """ |
| 34 | + set_mock_value(motor.user_setpoint, initial_position) |
| 35 | + set_mock_value(motor.user_readback, initial_position) |
| 36 | + set_mock_value(motor.deadband, deadband) |
| 37 | + set_mock_value(motor.motor_done_move, 1) |
| 38 | + set_mock_value(motor.velocity, velocity) |
| 39 | + set_mock_value(motor.max_velocity, max_velocity) |
| 40 | + set_mock_value(motor.low_limit_travel, low_limit_travel) |
| 41 | + set_mock_value(motor.high_limit_travel, high_limit_travel) |
| 42 | + return callback_on_mock_put( |
| 43 | + motor.user_setpoint, |
| 44 | + lambda pos, *args, **kwargs: set_mock_value(motor.user_readback, pos), |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def patch_all_motors(parent_device: Device): |
| 49 | + """ |
| 50 | + Check all children of a device and patch any motors with mock values. |
| 51 | +
|
| 52 | + Parameters: |
| 53 | + parent_device: The device that hold motor(s) as children. |
| 54 | + """ |
| 55 | + motors = [] |
| 56 | + |
| 57 | + def recursively_find_motors(device: Device): |
| 58 | + for _, child_device in device.children(): |
| 59 | + if isinstance(child_device, Motor): |
| 60 | + motors.append(child_device) |
| 61 | + recursively_find_motors(child_device) |
| 62 | + |
| 63 | + recursively_find_motors(parent_device) |
| 64 | + motor_patch_stack = ExitStack() |
| 65 | + for motor in motors: |
| 66 | + motor_patch_stack.enter_context(patch_motor(motor)) |
| 67 | + return motor_patch_stack |
0 commit comments