fix(devices): hold the laser delay hardware lock while calibrating
This commit is contained in:
1 parent
3d8b8c97cb
commit
f6887e757c
2 files changed
+80
-5
No files matched your search
@@ -38,6 +38,7 @@ interrupted move.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import functools
|
||||
import math
|
||||
import threading
|
||||
@@ -486,7 +487,10 @@ class LaserDelay(PSIDeviceBase, PositionerBase):
|
||||
raise ValueError(
|
||||
f"{self.name}: scope reading must be finite, got {scope_xray_minus_laser!r}"
|
||||
)
|
||||
self._require_idle("calibrate")
|
||||
with self._exclusive_hardware("calibrate"):
|
||||
return self._calibrate(s)
|
||||
|
||||
def _calibrate(self, s: float) -> dict[str, float]:
|
||||
constants = self._constants()
|
||||
# Same reading order as the script: EVR, DELAY, FINE, V1, V2.
|
||||
laser_period = 1000 * self.evr_period.get()
|
||||
@@ -557,10 +561,10 @@ class LaserDelay(PSIDeviceBase, PositionerBase):
|
||||
raise ValueError(f"{self.name}: {key} must be finite, got {value!r}")
|
||||
if float(laser_period) <= 0:
|
||||
raise ValueError(f"{self.name}: laser_period must be positive, got {laser_period!r}")
|
||||
self._require_idle("set_calibration")
|
||||
calibration = LaserDelayCalibration(**{key: float(val) for key, val in values.items()})
|
||||
delay = math.nan if current_delay is None else float(current_delay)
|
||||
self._store_calibration(calibration, current_delay=delay)
|
||||
with self._exclusive_hardware("set_calibration"):
|
||||
self._store_calibration(calibration, current_delay=delay)
|
||||
logger.info(f"{self.name}: calibration set to {calibration.as_dict()}")
|
||||
return calibration.as_dict()
|
||||
|
||||
@@ -677,9 +681,24 @@ class LaserDelay(PSIDeviceBase, PositionerBase):
|
||||
)
|
||||
return calibration
|
||||
|
||||
def _require_idle(self, action: str) -> None:
|
||||
if self.moving:
|
||||
@contextlib.contextmanager
|
||||
def _exclusive_hardware(self, action: str):
|
||||
"""Hold the hardware lock for a calibration, refusing if a move runs or is queued.
|
||||
|
||||
BEC's device server handles instructions on a thread pool, so a ``set`` can arrive while
|
||||
``calibrate`` reads the PVs. Holding the lock keeps a move from writing the PVs that are
|
||||
being read, and makes a move that arrives meanwhile run after the calibration, with it.
|
||||
"""
|
||||
if not self._hw_lock.acquire(blocking=False):
|
||||
raise LaserDelayBusyError(f"{self.name}: cannot {action} while a move is running.")
|
||||
try:
|
||||
with self._move_lock:
|
||||
pending = self._move_status is not None and not self._move_status.done
|
||||
if pending:
|
||||
raise LaserDelayBusyError(f"{self.name}: cannot {action} while a move is running.")
|
||||
yield
|
||||
finally:
|
||||
self._hw_lock.release()
|
||||
|
||||
def _store_calibration(self, calibration: LaserDelayCalibration, current_delay: float) -> None:
|
||||
self.laser_period.put(calibration.laser_period, internal=True)
|
||||
|
||||
@@ -26,6 +26,7 @@ from superxas_bec.devices.laser_delay import (
|
||||
LaserDelayBusyError,
|
||||
LaserDelayNotCalibratedError,
|
||||
SimLaserDelay,
|
||||
delay_card_setting,
|
||||
phase_from_voltages,
|
||||
phase_ramp_offsets,
|
||||
voltages_for_phase,
|
||||
@@ -357,6 +358,61 @@ def test_move_does_not_block_and_reports_moving(calibrated):
|
||||
assert moving[:1] == [1] and moving[-1] == 0
|
||||
|
||||
|
||||
def test_move_requested_during_calibration_runs_after_it(calibrated):
|
||||
"""BEC's device server runs instructions on a thread pool, so a set can arrive while calibrate()
|
||||
reads the PVs. The move must not write while the calibration reads, and must then use the new
|
||||
calibration."""
|
||||
reading, release = threading.Event(), threading.Event()
|
||||
original_get = calibrated.delay_fine.get
|
||||
|
||||
def slow_get(*args, **kwargs):
|
||||
reading.set()
|
||||
release.wait(timeout=5)
|
||||
return original_get(*args, **kwargs)
|
||||
|
||||
set_hardware(calibrated, coarse=160, fine=12) # the hardware was moved by hand since
|
||||
log = record_puts(calibrated)
|
||||
result = {}
|
||||
with mock.patch.object(calibrated.delay_fine, "get", side_effect=slow_get):
|
||||
thread = threading.Thread(target=lambda: result.update(cal=calibrated.calibrate(2.5)))
|
||||
thread.start()
|
||||
assert reading.wait(timeout=5)
|
||||
status = calibrated.set(1.0)
|
||||
time.sleep(0.1)
|
||||
assert log == [], "the move wrote PVs while calibrate() was reading them"
|
||||
release.set()
|
||||
thread.join(timeout=5)
|
||||
status.wait(timeout=10)
|
||||
assert status.success
|
||||
cal = result["cal"]
|
||||
assert cal["offset_t"] == pytest.approx(-(2.0 * 160 + 0.01 * 12) - 2.5)
|
||||
assert (log[0][1], log[1][1]) == delay_card_setting(-cal["offset_t"] - 1.0, cal["laser_period"])
|
||||
assert calibrated.read()["laser_delay"]["value"] == 1.0
|
||||
|
||||
|
||||
def test_calibration_refused_while_a_stopped_move_finishes_its_step(calibrated):
|
||||
calibrated.step_sleep.put(0.05)
|
||||
blocker = threading.Event()
|
||||
original_put = calibrated.phase_v1._write_pv.put
|
||||
|
||||
def blocking_put(value, *args, **kwargs):
|
||||
blocker.wait(timeout=5) # a slow CA put
|
||||
return original_put(value, *args, **kwargs)
|
||||
|
||||
calibrated.phase_v1._write_pv.put = blocking_put
|
||||
status = calibrated.set(-4.9)
|
||||
assert wait_until(calibrated._hw_lock.locked)
|
||||
calibrated.stop()
|
||||
assert status.done and not status.success
|
||||
with pytest.raises(LaserDelayBusyError):
|
||||
calibrated.calibrate(SCOPE)
|
||||
with pytest.raises(LaserDelayBusyError):
|
||||
calibrated.set_calibration(2000.2, 1.0, 1.0, 1.0)
|
||||
blocker.set()
|
||||
assert wait_until(lambda: not calibrated.moving)
|
||||
calibrated.calibrate(SCOPE)
|
||||
|
||||
|
||||
def test_stop_mid_ramp_keeps_last_step_and_fails_status(calibrated):
|
||||
calibrated.step_sleep.put(0.05)
|
||||
log = record_puts(calibrated)
|
||||
|
||||
Reference in new issue
Block a user