diff --git a/ophyd_devices/__init__.py b/ophyd_devices/__init__.py index 06afa26..f932dc7 100644 --- a/ophyd_devices/__init__.py +++ b/ophyd_devices/__init__.py @@ -1,3 +1,5 @@ +# First we import our own EpicsSignal, EpicsSignalRO, EpicsSignalWithRBV, Signal, SignalRO classes from the devices.epics_signals module. +from .devices.epics_signals import EpicsSignal, EpicsSignalRO, EpicsSignalWithRBV, Signal, SignalRO from .devices.sls_devices import SLSInfo, SLSOperatorMessages from .sim.sim_camera import SimCamera from .sim.sim_monitor import SimMonitor, SimMonitorAsync @@ -16,7 +18,7 @@ from .sim.sim_signals import ReadOnlySignal from .sim.sim_waveform import SimWaveform SynSignalRO = ReadOnlySignal -from .devices.epics_signals import EpicsSignal, EpicsSignalRO, EpicsSignalWithRBV + from .devices.psi_motor import EpicsMotor, EpicsMotorEC, EpicsUserMotorVME from .devices.softpositioner import SoftPositioner from .interfaces.base_classes.psi_device_base import PSIDeviceBase diff --git a/ophyd_devices/devices/epics_signals.py b/ophyd_devices/devices/epics_signals.py index 232179e..3de5e4d 100644 --- a/ophyd_devices/devices/epics_signals.py +++ b/ophyd_devices/devices/epics_signals.py @@ -1,14 +1,197 @@ +""" +This module contains thin wrappers around the ophyd EpicsSignal and EpicsSignalWithRBV classes +that use the StatusBase object from ophyd_devices to improve handling of timeout errors during +set calls. +""" + +import threading +import time +from typing import Any + +import numpy as np from ophyd import EpicsSignal as EpicsSignal_ -from ophyd import EpicsSignalRO -from ophyd import EpicsSignalWithRBV as EpicsSignalWithRBV_ +from ophyd import EpicsSignalRO # Keep import for EpicsSignalRO be able to import from this module +from ophyd import SignalRO # Keep import for EpicsSignalRO be able to import from this module +from ophyd import Signal as Signal_ from ophyd.signal import DEFAULT_WRITE_TIMEOUT +from ophyd.utils.epics_pvs import _compare_maybe_enum from ophyd_devices.utils.psi_device_base_utils import StatusBase +# Custom methods for set calls on signals. +def _wait_for_value( + signal: Signal_, + val: Any, + status: StatusBase, # Custom addition to allow for external finishing + logger=None, # Custom addition to allow for logging using logger from the signal object + poll_time: float = 0.01, + rtol: float | None = None, + atol: float | None = None, +): + """ + Overwrite of the wait method for set commands on signals. Timeouts are handled by the StatusBase object + together with any externally initialized abort of the set command. We check the status object for + external finishing of the set command and break the wait loop if the status is done. This allows for + more robust handling of timeouts or any other external finishing of the set command. + + Args: + signal (Signal_): The signal to wait on. + val (Any): The value to wait for. + status (StatusBase): The status object of the set command. + poll_time (float): The time to wait between polls. + rtol (float | None): The relative tolerance for the value comparison. + atol (float | None): The absolute tolerance for the value comparison. + + """ + # CUSTOM PART: Removed previous timeout logic here. + + # OPHYD SECTION: copied from OPHYD source code + get_kwargs = {} + if isinstance(val, (list, np.ndarray, tuple)): + get_kwargs["count"] = len(val) + current_value = signal.get(**get_kwargs) + + if atol is None and hasattr(signal, "tolerance"): + atol = signal.tolerance + if rtol is None and hasattr(signal, "rtolerance"): + rtol = signal.rtolerance + + try: + enum_strings = signal.enum_strs + except AttributeError: + enum_strings = () + + if atol is not None: + within_str = [f"within {atol!r}"] + else: + within_str = [] + + if rtol is not None: + within_str.append(f"(relative tolerance of {rtol!r})") + + if within_str: + within_str = " ".join([""] + within_str) + else: + within_str = "" + + while (val is not None and current_value is None) or not _compare_maybe_enum( + val, current_value, enum_strings, atol, rtol + ): + # CUSTOM PART: break if status indicates that it is done. + if status.done is True: + break + + # OPHYD SECTION: copied from OPHYD source code + time.sleep(poll_time) + if poll_time < 0.1: + poll_time *= 2 # logarithmic back-off + current_value = signal.get(**get_kwargs) + # CUSTOM PART: removed previous timeout logic here. + + +def _set_and_wait( + signal: Signal_, + val: Any, + status: StatusBase, # Custom addition to allow for external finishing + logger=None, # Custom addition to allow for logging using logger from the signal object + poll_time: float = 0.01, + rtol: float | None = None, + atol: float | None = None, + **kwargs, +): + """ + Custom method to put a value to a signal, + and wait for the value to be set using the custom _wait_for_value method. + """ + signal.put(val, **kwargs) + _wait_for_value( + signal, val, status=status, logger=logger, poll_time=poll_time, rtol=rtol, atol=atol + ) + + +def shared_set_thread( + signal: Signal_, + value: Any, + thread_done_event: threading.Event, + status: StatusBase | None = None, + **kwargs, +): + """ + Shared set thread method for the signal wrapper classes of this module. + It is used for example by the Signal.set() method to avoid code duplication. + + Args: + signal (Signal_): The signal to set. + value (Any): The value to set the signal to. + timeout (float | None): The timeout for the operation. If not specified, it will use the default write timeout. + status (StatusBase | None): The status object of the set command. If provided, the method will check if the status has externally finished. + **kwargs: Additional keyword arguments to pass to the _set_and_wait method. + """ + try: + _set_and_wait( + signal, + value, + status=status, + logger=signal.log, + atol=signal.tolerance, + rtol=signal.rtolerance, + **kwargs, + ) + except Exception as e: # pylint: disable=broad-except + if not status.done: + status.set_exception(e) + else: + if not status.done: + status.set_finished() + finally: + thread_done_event.clear() + + +class Signal(Signal_): + """ + Custom Signal class to avoid running into a potential deadlock when + using the set method with a timeout. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._set_thread_event: threading.Event = threading.Event() + + def set(self, value, *, timeout=None, settle_time=None, **kwargs): + """ + Custom set method for Signal using the shared_set_thread function to improve error + and timeout handling and avoid potential deadlocks. Further also improve, + """ + + if self._set_thread_event.is_set(): + raise RuntimeError(f"Another set() call is still in progress for {self.name}") + + status = StatusBase( + obj=self, + timeout=timeout, + settle_time=settle_time, + description=f"Trying to set signal '{self.name}' to value: {value}.", + ) + + _set_thread = self.cl.thread_class( + target=shared_set_thread, + args=(self, value), + kwargs={"status": status, "thread_done_event": self._set_thread_event, **kwargs}, + ) + _set_thread.daemon = True + self._set_thread_event.set() # Signal that a set operation is in progress + _set_thread.start() + return status + + class EpicsSignal(EpicsSignal_): """Custom EpicsSignal class that uses the StatusBase object from ophyd_devices.""" + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._set_thread_event: threading.Event = threading.Event() + def set(self, value, *, timeout=DEFAULT_WRITE_TIMEOUT, settle_time=None): """ Custom set method for EpicsSignal that uses the StatusBase object from @@ -28,61 +211,41 @@ class EpicsSignal(EpicsSignal_): if timeout is DEFAULT_WRITE_TIMEOUT: timeout = self.write_timeout - if not self._put_complete: - return super().set(value, timeout=timeout, settle_time=settle_time) + if self._set_thread_event.is_set(): + raise RuntimeError(f"Another set() call is still in progress for {self.name}") - # using put completion: - # timeout and settle time is handled by the status object. - st = StatusBase( + status = StatusBase( obj=self, timeout=timeout, settle_time=settle_time, description=f"Trying to set signal '{self.name}' to value: {value}.", ) + if not self._put_complete: + # Logic basically from Signal.set(), just duplicated due to inheritance + + _set_thread = self.cl.thread_class( + target=shared_set_thread, + args=(self, value), + kwargs={"status": status, "thread_done_event": self._set_thread_event}, + ) + _set_thread.daemon = True + _set_thread.start() + return status + def put_callback(**kwargs): - st._finished(success=True) + # Only call set_finished if the status is not already done, to avoid potential race conditions. + if status.done is False: + status.set_finished() + self._set_thread_event.clear() # Signal that the set operation is complete + self._set_thread_event.set() # Signal that a set operation is in progress self.put(value, use_complete=True, callback=put_callback) - return st + return status -class EpicsSignalWithRBV(EpicsSignalWithRBV_): +class EpicsSignalWithRBV(EpicsSignal): """Custom EpicsSignal class that uses the StatusBase object from ophyd_devices.""" - def set(self, value, *, timeout=DEFAULT_WRITE_TIMEOUT, settle_time=None): - """ - Custom set method for EpicsSignal that uses the StatusBase object from - ophyd_devices. - - Args: - value: The value to set the signal to. - timeout: The timeout for the operation. If not specified, it will - use the default write timeout. - settle_time: The time to wait after the put operation before - considering it complete. If not specified, it will use the - default settle time. - Returns: - A StatusBase object that can be used to monitor the progress of the - operation. - """ - if timeout is DEFAULT_WRITE_TIMEOUT: - timeout = self.write_timeout - - if not self._put_complete: - return super().set(value, timeout=timeout, settle_time=settle_time) - - # using put completion: - # timeout and settle time is handled by the status object. - st = StatusBase( - obj=self, - timeout=timeout, - settle_time=settle_time, - description=f"Trying to set signal '{self.name}' to value: {value}.", - ) - - def put_callback(**kwargs): - st._finished(success=True) - - self.put(value, use_complete=True, callback=put_callback) - return st + def __init__(self, prefix, **kwargs): + super().__init__(prefix + "_RBV", write_pv=prefix, **kwargs) diff --git a/ophyd_devices/utils/bec_processed_signal.py b/ophyd_devices/utils/bec_processed_signal.py index abcbe50..0a40767 100644 --- a/ophyd_devices/utils/bec_processed_signal.py +++ b/ophyd_devices/utils/bec_processed_signal.py @@ -16,9 +16,11 @@ import inspect import time from typing import TYPE_CHECKING, Any, Callable, Literal, Self -from ophyd import Component, Device, Signal, SignalRO +from ophyd import Component, Device from pydantic import BaseModel, model_validator +from ophyd_devices.devices.epics_signals import Signal, SignalRO + if TYPE_CHECKING: # pragma: no cover from bec_server.device_server.devices.devicemanager import DeviceManagerDS, DSDevice @@ -44,6 +46,9 @@ def find_device_config_in_session(name: str, device_manager: DeviceManagerDS) -> return config +__all__ = ["ProcessedSignalModel", "BECProcessedSignal"] + + class ProcessedSignalModel(BaseModel): """Configuration model for :class:`BECProcessedSignal`. diff --git a/ophyd_devices/utils/bec_signals.py b/ophyd_devices/utils/bec_signals.py index 60da779..a0070da 100644 --- a/ophyd_devices/utils/bec_signals.py +++ b/ophyd_devices/utils/bec_signals.py @@ -9,10 +9,12 @@ from typing import Any, Callable, Literal, Type import numpy as np from bec_lib import messages from bec_lib.logger import bec_logger -from ophyd import DeviceStatus, Kind, Signal +from ophyd import DeviceStatus, Kind from pydantic import BaseModel, Field, ValidationError from typeguard import typechecked +from ophyd_devices.devices.epics_signals import Signal + logger = bec_logger.logger # pylint: disable=arguments-differ # pylint: disable=arguments-renamed diff --git a/ophyd_devices/utils/dynamic_pseudo.py b/ophyd_devices/utils/dynamic_pseudo.py index aace960..c7a07ca 100644 --- a/ophyd_devices/utils/dynamic_pseudo.py +++ b/ophyd_devices/utils/dynamic_pseudo.py @@ -10,9 +10,10 @@ from typing import Callable import numpy as np import scipy as sp from bec_lib import bec_logger -from ophyd import Signal, SignalRO from ophyd.ophydobj import Kind +from ophyd_devices import Signal, SignalRO + logger = bec_logger.logger _FIRST_DEF = re.compile(r"(^|\\n)\s*def", re.MULTILINE) diff --git a/tests/test_epics_signals_wrapper.py b/tests/test_epics_signals_wrapper.py new file mode 100644 index 0000000..854890c --- /dev/null +++ b/tests/test_epics_signals_wrapper.py @@ -0,0 +1,176 @@ +""" +Tests for the ophyd_devices Signal wrapper. +""" + +import threading +from functools import partial +from unittest import mock + +import ophyd +import pytest + +from ophyd_devices import EpicsSignal, EpicsSignalWithRBV, Signal +from ophyd_devices.tests.utils import MockPV +from ophyd_devices.utils.psi_device_base_utils import StatusTimeoutErrorWithErrorInfo + + +@pytest.fixture +def signal() -> Signal: + """ + Fixture to create a Signal instance for testing. + Returns: + Signal: An instance of the Signal class. + """ + return Signal(name="test_signal", value=0) + + +@pytest.fixture +def patched_epics_signal() -> EpicsSignal: + """ + Fixture to create a patched EpicsSignal instance for testing. + Returns: + EpicsSignal: An instance of the EpicsSignal class with patched methods. + """ + pv = "test_epics_signal" + with mock.patch.object(ophyd, "cl") as mock_cl: + mock_cl.get_pv = partial(MockPV, _mock_pv_initial_value=1) + mock_cl.thread_class = threading.Thread + sig = EpicsSignal(pv) + return sig + + +@pytest.fixture +def patched_epics_signal_with_rbv() -> EpicsSignalWithRBV: + """ + Fixture to create a patched EpicsSignalWithRBV instance for testing. + Returns: + EpicsSignalWithRBV: An instance of the EpicsSignalWithRBV class with patched methods. + """ + pv = "test_epics_signal" + with mock.patch.object(ophyd, "cl") as mock_cl: + mock_cl.get_pv = partial(MockPV, _mock_pv_initial_value=1) + mock_cl.thread_class = threading.Thread + sig = EpicsSignalWithRBV(pv) + if sig._read_pv.pvname != sig._write_pv.pvname: + sig._read_pv = sig._write_pv + return sig + + +def test_signal_set(signal: Signal): + """ + Test the set method of the Signal class.""" + # Test setting the signal to a new value + sig = signal + status = sig.set(10) + status.wait() + assert status.done is True + assert sig.get() == 10 + + status = sig.set(3) + status.wait() + assert status.done is True + assert sig.get() == 3 + + with mock.patch.object(sig, "put"): + # Test setting the sig to the same value (should not call put) + status = sig.set(5) + assert status.done is False + sig._readback = 5 # Simulate that the readback value has changed to 5 + status.wait(timeout=5) # Wait for the status to complete + assert sig.get() == 5 + assert status.done is True + status = sig.set(5) # Setting to the same value again + status.wait(timeout=5) # Wait for the status to complete + assert sig.get() == 5 + assert status.done is True + + +def test_signal_subsequent_set_calls(signal: Signal): + """ + Test that subsequent set calls raise a RuntimeError if a set is already in progress. + """ + sig = signal + with mock.patch.object(sig, "put"): + status = sig.set(20) + with pytest.raises(RuntimeError): + status2 = sig.set(30) + + +def test_signal_set_with_timeout(signal: Signal): + """ + Test the set method with a specified timeout. + """ + sig = signal + with mock.patch.object(sig, "put"): + status = sig.set(15, timeout=1) + with pytest.raises(StatusTimeoutErrorWithErrorInfo): + status.wait(timeout=2) + + +def test_epics_signal_set_with_timeout(patched_epics_signal: EpicsSignal): + """ + Test the set method of the EpicsSignal class with a specified timeout. + """ + sig = patched_epics_signal + with mock.patch.object(sig, "put"): + status = sig.set(25, timeout=1) + with pytest.raises(StatusTimeoutErrorWithErrorInfo): + status.wait(timeout=2) + + +def test_epics_signal_set(patched_epics_signal: EpicsSignal): + """ + Test the set method of the EpicsSignal class. + """ + sig = patched_epics_signal + status = sig.set(10) + status.wait() + assert status.done is True + assert sig.get() == 10 + + +def test_epics_signal_with_rbv_set_with_timeout(patched_epics_signal_with_rbv: EpicsSignalWithRBV): + """ + Test the set method of the EpicsSignalWithRBV class with a specified timeout. + """ + sig = patched_epics_signal_with_rbv + with mock.patch.object(sig, "put"): + status = sig.set(35, timeout=1) + with pytest.raises(StatusTimeoutErrorWithErrorInfo): + status.wait(timeout=2) + + +def test_epics_signal_with_rbv_set(patched_epics_signal_with_rbv: EpicsSignalWithRBV): + """ + Test the set method of the EpicsSignalWithRBV class. + """ + sig = patched_epics_signal_with_rbv + status = sig.set(20) + status.wait() + assert status.done is True + assert sig.get() == 20 + + +def test_epics_signal_with_put_complete(patched_epics_signal: EpicsSignal): + """ + Test the set method of the EpicsSignal class with use_complete=True. + """ + sig = patched_epics_signal + sig._put_complete = True # Simulate that the put operation is complete + + with mock.patch.object(sig, "put") as mock_put: + status = sig.set(50) + assert status.done is False + mock_put.assert_called_once_with(50, use_complete=True, callback=mock.ANY) + with pytest.raises(RuntimeError): + sig.set(60) # Attempting to set while another set is in progress + + mock_put.call_args[1]["callback"](pvname=sig.name) # Simulate the callback being called + status.wait(timeout=5) # Wait for the status to complete + assert status.done is True + assert status.success is True + + # Test that now we can set again after the previous set has completed + status2 = sig.set(70) + assert status2.done is False + mock_put.assert_called_with(70, use_complete=True, callback=mock.ANY)