Files
csaxs_bec/tests/tests_devices/test_a3200.py
x01dcandClaude Opus 5.5 6e2eec9942
CI for csaxs_bec / test (push) Successful in 3m32s
feat(aerotech): progress bar from the captured lines, statistics shown without MCS
The IPython client prints client-info messages only from a scan's progress
display. With trigger_source="panda" or None the scan registered none, so the
end-of-scan statistics were sent but never shown (scan 8511). The position
capture now publishes a ProgressSignal (lines read / num_points) and the scan
uses it for the progress bar when there is no MCS card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M8zoDzDfsCTY2o5bT3J7Wv
2026-10-30 11:19:07 +01:00

516 lines
17 KiB
Python

import time
import pytest
from bec_server.device_server.tests.utils import DMMock
from ophyd.utils import LimitError
from ophyd_devices.tests.utils import SocketMock
from csaxs_bec.devices.aerotech.a3200 import (
A3200CommunicationError,
A3200Controller,
A3200Error,
A3200Motor,
decode_axis_fault,
)
from csaxs_bec.devices.sim.sim_a3200 import SimA3200Motor, SimA3200PositionCapture, SimA3200State
from csaxs_bec.devices.sim.sim_socket import SimStateRegistry
_HOST = "test-a3200.psi.ch"
_PORT = 8000
@pytest.fixture(autouse=True)
def _reset_controllers():
A3200Controller._reset_controller()
SimStateRegistry.reset()
yield
SimStateRegistry.reset()
A3200Controller._reset_controller()
@pytest.fixture
def mock_motor():
motor = A3200Motor(
"X", name="aerox", host=_HOST, port=_PORT, socket_cls=SocketMock, device_manager=DMMock()
)
motor.controller.on()
motor.controller.sock.flush_buffer()
yield motor
motor.controller.off()
def _sim_motor(axis_Id="X", axis_nr=0, **kwargs):
kwargs.setdefault("velocity", 1000.0)
kwargs.setdefault("sim_home_velocity", 1000.0)
motor = SimA3200Motor(
axis_Id,
name=f"aero{axis_Id.lower()}",
axis_nr=axis_nr,
host=_HOST,
port=_PORT,
device_manager=DMMock(),
**kwargs,
)
motor.wait_for_connection()
return motor
# --- protocol (SocketMock) ---------------------------------------------------
def test_command_returns_data_after_ack(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"%6.04.004.0016\n"]
assert mock_motor.controller.get_version() == "6.04.004.0016"
assert mock_motor.controller.sock.buffer_put == [b"~VERSION\n"]
def test_reply_split_over_several_receives(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"%1.2", b"5 4194", b"305\n"]
assert mock_motor.controller.get_status_items([("X", "A"), ("X", "B")]) == [1.25, 4194305.0]
def test_two_replies_in_one_receive_are_kept_apart(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"%\n%7.5\n"]
mock_motor.controller.enable_axis("X")
assert mock_motor.controller.get_position("X") == 7.5
def test_fault_reply_raises_with_last_error(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"#\n", b"%The axis is not enabled.\n"]
with pytest.raises(A3200Error, match="The axis is not enabled."):
mock_motor.controller.command("HOME X")
assert mock_motor.controller.sock.buffer_put == [b"HOME X\n", b"~LASTERROR\n"]
def test_invalid_reply_raises(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"!\n"]
with pytest.raises(A3200Error, match="invalid"):
mock_motor.controller.command("ENABLE")
def test_motion_command_is_not_retried(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"#\n", b"%fault\n", b"%\n", b"%\n"]
with pytest.raises(A3200Error):
mock_motor.controller.move_absolute("X", 1.0, 2.0)
assert mock_motor.controller.sock.buffer_put == [
b"MOVEABS X 1.000000 2.000000\n",
b"~LASTERROR\n",
]
def test_missing_eos_times_out(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"%"]
with pytest.raises(A3200CommunicationError, match="Always Send EOS"):
mock_motor.controller.socket_get(timeout=0.05)
def test_status_query_format(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"%1.5 4194305 1 0\n"]
status = mock_motor.controller.axis_status("X")
assert mock_motor.controller.sock.buffer_put == [
b"~STATUS (X, ProgramPositionFeedback) (X, AxisStatus) (X, DriveStatus) (X, AxisFault)\n"
]
assert status["position"] == 1.5
assert status["enabled"] and status["homed"]
assert not status["moving"]
assert status["faults"] == []
def test_decode_axis_fault():
assert decode_axis_fault(0) == []
assert decode_axis_fault((1 << 0) | (1 << 2) | (1 << 11)) == [
"PositionError",
"CwEOTLimit",
"EstopFault",
]
# --- simulated controller ----------------------------------------------------
def test_sim_move_and_readback():
motor = _sim_motor(sim_initial_position=1.0)
assert motor.readback.get() == pytest.approx(1.0)
motor.move(5.0, wait=True)
assert motor.readback.get() == pytest.approx(5.0)
assert not motor.motor_is_moving.get()
def test_sim_sign_is_applied():
motor = _sim_motor(sign=-1, sim_initial_position=2.0)
assert motor.readback.get() == pytest.approx(2.0)
motor.move(-3.0, wait=True)
assert motor.readback.get() == pytest.approx(-3.0)
state = SimStateRegistry.get(SimA3200State, _HOST, _PORT)
assert state.axis("X").position() == pytest.approx(3.0)
def test_sim_move_refused_when_disabled():
motor = _sim_motor(sim_enabled=False)
with pytest.raises(A3200Error, match="not enabled"):
motor.move(1.0, wait=True)
motor.enable()
motor.move(1.0, wait=True)
assert motor.readback.get() == pytest.approx(1.0)
def test_sim_move_refused_when_not_homed():
motor = _sim_motor(sim_homed=False, sim_initial_position=3.0)
with pytest.raises(A3200Error, match="not homed"):
motor.move(1.0, wait=True)
motor.home()
assert "[PUT]: ABORT X" not in motor.controller.command_history
assert motor.status()["homed"]
assert motor.readback.get() == pytest.approx(0.0)
motor.move(1.0, wait=True)
assert motor.readback.get() == pytest.approx(1.0)
def test_sim_unhomed_move_allowed_if_configured():
motor = _sim_motor(sim_homed=False, require_homed=False)
motor.move(2.0, wait=True)
assert motor.readback.get() == pytest.approx(2.0)
def test_sim_fault_blocks_move_until_acknowledged():
motor = _sim_motor()
SimStateRegistry.get(SimA3200State, _HOST, _PORT).axis("X").fault = 1 << 2
with pytest.raises(A3200Error, match="CwEOTLimit"):
motor.move(1.0, wait=True)
motor.fault_ack()
motor.move(1.0, wait=True)
assert motor.readback.get() == pytest.approx(1.0)
def test_sim_soft_limits():
motor = _sim_motor(limits=[-1, 1])
with pytest.raises(LimitError):
motor.move(2.0, wait=True)
def test_sim_stop_aborts_motion():
motor = _sim_motor(velocity=1.0)
status = motor.move(10.0, wait=False)
motor.stop()
with pytest.raises(Exception):
status.wait(timeout=2)
assert motor.readback.get() < 1.0
assert not motor.motor_is_moving.get()
def test_sim_two_axes_share_one_controller():
x = _sim_motor("X", axis_nr=0)
y = _sim_motor("Y", axis_nr=1)
assert x.controller is y.controller
x.move(1.0, wait=True)
y.move(2.0, wait=True)
assert x.readback.get() == pytest.approx(1.0)
assert y.readback.get() == pytest.approx(2.0)
x.controller.describe()
# --- line trigger and position capture (simulated controller) ----------------
def _sim_state():
return SimStateRegistry.get(SimA3200State, _HOST, _PORT)
def _capture_setup():
# SAXS-TT numbering: X sine encoder (MXR channel 0, emulated quadrature to PSO input 6),
# Y square wave encoder (local encoder counter 2)
x = _sim_motor("X", axis_nr=0, pso_input=6, sim_counts_per_unit=20000, sim_counter_offset=777)
y = _sim_motor("Y", axis_nr=2, pso_input=2, sim_initial_position=0.3, sim_counter_offset=-55)
capture = SimA3200PositionCapture(
name="aerocapture",
host=_HOST,
port=_PORT,
channels={6: "X", 2: "Y"},
device_manager=DMMock(),
)
capture.wait_for_connection()
return x, y, capture
def test_counts_per_unit_is_read_once():
x, _, _ = _capture_setup()
assert x.controller.counts_per_unit("X") == 20000
x.controller.command_history.clear()
assert x.controller.counts_per_unit("X") == 20000
assert not x.controller.command_history
def test_ramp_rate_is_set_before_the_move():
motor = _sim_motor(acceleration=50.0)
motor.move(1.0, wait=True)
history = list(motor.controller.command_history)
ramp = history.index("[PUT]: RAMP RATE X 50.000000")
move = next(i for i, c in enumerate(history) if c.startswith("[PUT]: MOVEABS X"))
assert ramp < move
assert _sim_state().axis("X").ramp_rate == 50.0
def test_line_trigger_window_is_relative_to_current_position():
x, _, _ = _capture_setup()
x.move(-1.0, wait=True)
x.arm_line_trigger(0.0, 1.0)
assert _sim_state().pso["range"] == (20000.0, 40000.0)
assert _sim_state().pso["armed"]
x.move(2.0, wait=True)
assert _sim_state().pso_window_entries == 1
x.disarm_line_trigger()
assert not _sim_state().pso["armed"]
def test_line_trigger_window_range_keeps_the_reference():
x, _, _ = _capture_setup()
x.move(-1.0, wait=True)
x.arm_line_trigger(0.0, 1.0)
x.move(2.0, wait=True)
x.set_line_trigger_window(-3.0, 1.5)
# relative to the position at arm (-1.0), not to the current one (2.0)
assert _sim_state().pso["range"] == (-40000.0, 50000.0)
assert "[PUT]: PSOWINDOW X 1 LOAD 0" in x.controller.command_history
assert sum("LOAD" in c for c in x.controller.command_history) == 1
def test_line_trigger_window_range_needs_armed_window():
x, _, _ = _capture_setup()
with pytest.raises(A3200Error, match="not armed"):
x.set_line_trigger_window(0.0, 1.0)
x.arm_line_trigger(0.5, 1.0)
x.disarm_line_trigger()
with pytest.raises(A3200Error, match="not armed"):
x.set_line_trigger_window(0.0, 1.0)
def test_line_trigger_uses_emulated_quadrature_divider():
u = _sim_motor(
"U", axis_nr=3, egu="deg", pso_input=7, pso_counts_divider=40, sim_counts_per_unit=560000
)
u.move(-1.0, wait=True)
u.arm_line_trigger(0.0, 1.0)
assert "[PUT]: PSOWINDOW U 1 INPUT 7" in u.controller.command_history
assert _sim_state().pso["range"] == (14000.0, 28000.0)
u.move(2.0, wait=True)
assert _sim_state().pso_window_entries == 1
def test_line_trigger_needs_pso_input():
motor = _sim_motor()
with pytest.raises(A3200Error, match="pso_input"):
motor.arm_line_trigger(0.0, 1.0)
def test_capture_calibration_removes_counter_offset():
_, _, capture = _capture_setup()
offsets = capture.calibrate()
assert offsets["enc6"] == pytest.approx(-777 / 20000)
assert offsets["enc2"] == pytest.approx(55 / 10000)
def test_capture_rpc_returns_survive_msgpack():
# an RPC return value that msgpack cannot decode leaves the scan waiting forever
from bec_lib.serialization import MsgpackSerialization
x, _, capture = _capture_setup()
returns = [capture.calibrate()]
x.move(-1.0, wait=True)
capture.arm(5)
x.move(1.0, wait=True)
returns.append(capture.read_line())
for value in returns:
assert MsgpackSerialization.loads(MsgpackSerialization.dumps(value)) == value
def test_capture_line_publishes_positions():
x, _, capture = _capture_setup()
capture.calibrate()
x.move(-1.0, wait=True)
capture.arm(5)
x.arm_line_trigger(0.0, 1.0)
x.move(2.0, wait=True)
result = capture.read_line()
assert result["enc6"] == pytest.approx([0.0, 0.2, 0.4, 0.6, 0.8])
assert result["enc2"] == pytest.approx([0.3] * 5)
msg = capture.positions.get()
assert set(msg.signals) == {
"aerocapture_positions_enc2",
"aerocapture_positions_enc6",
"aerocapture_positions_enc2_centre",
"aerocapture_positions_enc6_centre",
}
assert msg.metadata["async_update"] == {"type": "add", "max_shape": [None]}
def test_capture_reads_in_chunks():
x, _, capture = _capture_setup()
capture.controller.array_read_chunk = 3
x.move(-1.0, wait=True)
capture.arm(4)
x.arm_line_trigger(0.0, 1.0)
x.move(2.0, wait=True)
result = capture.read_line()
assert len(result["enc6"]) == 4
reads = [c for c in capture.controller.command_history if "ARRAY X READ" in c]
assert reads == [
"[PUT]: ARRAY X READ $global[0] 0 3 FAST",
"[PUT]: ARRAY X READ $global[0] 3 3 FAST",
"[PUT]: ARRAY X READ $global[0] 6 2 FAST",
]
def test_capture_needs_two_channels():
with pytest.raises(ValueError, match="two encoder channels"):
SimA3200PositionCapture(
name="aerocapture", host=_HOST, port=_PORT, channels={6: "X"}, device_manager=DMMock()
)
def test_capture_rejects_analog_sources():
with pytest.raises(ValueError, match="out of range"):
SimA3200PositionCapture(
name="aerocapture",
host=_HOST,
port=_PORT,
channels={6: "X", 12: "Y"},
device_manager=DMMock(),
)
def test_move_waits_for_position_error_within_tolerance():
motor = _sim_motor(velocity=100.0, tolerance=0.001)
axis = SimStateRegistry.get(SimA3200State, _HOST, _PORT).axis("X")
axis.settle_time = 0.3
axis.settle_error = 0.01
start = time.time()
motor.move(1.0, wait=True)
assert time.time() - start >= 0.3
assert motor.controller.position_error("X") == 0.0
def test_move_does_not_settle_on_a_zero_crossing():
# ringing after the stop: one reading within tolerance, then out again, then settled
motor = _sim_motor(velocity=100.0, tolerance=0.001, in_position_hold=0.1)
errors = iter([0.0] + [0.01] * 5)
motor.controller.position_error = lambda axis: next(errors, 0.0)
start = time.time()
status = motor.move(1.0, wait=True)
# 5 readings out of tolerance (~0.1 s), then held for 0.1 s
assert time.time() - start >= 0.2
assert status.success
def test_move_ignores_in_position_tighter_than_tolerance():
# settled within tolerance, but outside the controller's InPositionDistance
motor = _sim_motor(velocity=100.0, tolerance=0.001)
axis = SimStateRegistry.get(SimA3200State, _HOST, _PORT).axis("X")
axis.settle_time = 5.0
axis.settle_error = 2e-5
start = time.time()
status = motor.move(1.0, wait=True)
assert time.time() - start < 0.5
assert status.success
assert not motor.status()["in_position"]
def test_move_not_settled_still_finishes():
motor = _sim_motor(velocity=100.0, in_position_timeout=0.1)
axis = SimStateRegistry.get(SimA3200State, _HOST, _PORT).axis("X")
axis.settle_time = 5.0
axis.settle_error = 0.01
start = time.time()
motor.move(1.0, wait=True)
assert time.time() - start < 1.0
assert motor.readback.get() == pytest.approx(1.0)
def test_move_without_in_position_wait():
motor = _sim_motor(velocity=100.0, tolerance=1e-9)
SimStateRegistry.get(SimA3200State, _HOST, _PORT).axis("X").settle_time = 5.0
motor.wait_in_position.put(False)
start = time.time()
status = motor.move(1.0, wait=True)
assert time.time() - start < 0.5
assert status.success
def test_max_scan_velocity_defaults_to_velocity():
assert _sim_motor(velocity=5.0).max_scan_velocity.get() == 5.0
assert _sim_motor(velocity=5.0, max_scan_velocity=50.0).max_scan_velocity.get() == 50.0
def test_capture_line_centre_shift():
x, _, capture = _capture_setup()
capture.calibrate()
x.move(-1.0, wait=True)
capture.arm(5)
x.arm_line_trigger(0.0, 1.0)
x.move(2.0, wait=True)
result = capture.read_line(centre_shift=0.1)
# X moves forward: shifted forward; Y does not move: unchanged
assert result["enc6_centre"] == pytest.approx([0.1, 0.3, 0.5, 0.7, 0.9])
assert result["enc2_centre"] == pytest.approx(result["enc2"])
def test_capture_line_centre_shift_backward():
_, _, capture = _capture_setup()
capture.arm(3)
# backward line: X (channel 6) counts down, Y (channel 2) constant; interleaved 2, 6
capture.controller.read_drive_array = lambda axis, start, count: [
3000, 60000, 3000, 40000, 3000, 20000
]
result = capture.read_line(centre_shift=0.1)
assert result["enc6_centre"] == pytest.approx([x - 0.1 for x in result["enc6"]])
assert result["enc2_centre"] == pytest.approx(result["enc2"])
def test_capture_applies_the_motor_sign():
"""Captured positions are in the coordinates of the BEC motors (sign from their config)."""
x = _sim_motor("X", axis_nr=0, pso_input=6, sim_counts_per_unit=20000, sign=-1)
y = _sim_motor("Y", axis_nr=2, pso_input=2, sim_counts_per_unit=10000)
dm = DMMock()
dm.devices["aerox"] = x
dm.devices["aeroy"] = y
capture = SimA3200PositionCapture(
name="aerocapture", host=_HOST, port=_PORT, channels={6: "X", 2: "Y"}, device_manager=dm
)
capture.wait_for_connection()
capture.calibrate()
assert capture._signs == {6: -1, 2: 1}
capture._offsets = {6: 0.0, 2: 0.0}
capture.arm(3)
# forward line in user coordinates = X counts going down; interleaved channels 2, 6
capture.controller.read_drive_array = lambda axis, start, count: [
3000, -20000, 3000, -24000, 3000, -28000
]
result = capture.read_line(centre_shift=0.1)
assert result["enc6"] == pytest.approx([1.0, 1.2, 1.4])
assert result["enc6_centre"] == pytest.approx([1.1, 1.3, 1.5])
assert result["enc2"] == pytest.approx([0.3] * 3)
def test_capture_without_motor_uses_controller_coordinates():
_, _, capture = _capture_setup() # DMMock without motors
capture.calibrate()
assert capture._signs == {6: 1, 2: 1}
def test_capture_progress_counts_lines():
from types import SimpleNamespace
x, _, capture = _capture_setup()
capture.scan_info = SimpleNamespace(msg=SimpleNamespace(frames_per_trigger=5, num_points=2))
capture.on_stage()
assert capture.progress.get().value == 0 and capture.progress.get().max_value == 2
capture.calibrate()
for target in (-1.0, 1.0):
capture.arm(5)
x.move(target, wait=True)
capture.read_line()
progress = capture.progress.get()
assert progress.value == 2 and progress.done