diff --git a/csaxs_bec/bec_ipython_client/startup/beamline_states.py b/csaxs_bec/bec_ipython_client/startup/beamline_states.py new file mode 100644 index 00000000..d16130fa --- /dev/null +++ b/csaxs_bec/bec_ipython_client/startup/beamline_states.py @@ -0,0 +1,184 @@ +""" +Default beamline states for the tomography sessions (LamNI, OMNY, flOMNI). + +The scan interlock of these sessions (`bec.builtin_actors.scan_interlock`) watches the beamline +states. set_default_beamline_states() makes the defined states exactly DEFAULT_BEAMLINE_STATES: +if the states in BEC differ, all of them are deleted and the defaults are added again. + +Beamline states are global (stored in Redis), not per client. If they already match, nothing +is changed, so starting another client, e.g. during a running tomography scan, does not +touch the states the interlock is watching. +""" + +from __future__ import annotations + +import time + +from bec_lib import bec_logger +from bec_lib.bl_states import DeviceWithinLimitsStateConfig + +logger = bec_logger.logger + +DEFAULT_BEAMLINE_STATES = [ + DeviceWithinLimitsStateConfig( + name="curr_device_within_limits_state", + device="curr", + signal="curr", + low_limit=380.0, + tolerance=0.1, + ), + DeviceWithinLimitsStateConfig( + name="idgap_device_within_limits_state", + device="idgap", + signal="idgap", + high_limit=8.0, + tolerance=0.1, + ), + DeviceWithinLimitsStateConfig( + name="shutter_device_within_limits_state", + device="shutter", + signal="shutter", + low_limit=0.5, + tolerance=0.1, + ), + DeviceWithinLimitsStateConfig( + name="ofb_device_within_limits_state", + device="ofb", + signal="ofb", + low_limit=0.5, + tolerance=0.1, + ), + DeviceWithinLimitsStateConfig( + name="shutter_es_device_within_limits_state", + device="shutter_es", + signal="shutter_es", + low_limit=0.5, + tolerance=0.1, + ), +] + + +# Extra states per session (added to the defaults). The scan interlock watches them only in their +# session: set_default_beamline_states() adds them to the interlock there and removes them from it +# in the other sessions, so a flOMNI/LamNI session is never locked by a state that does not exist. +SESSION_BEAMLINE_STATES = { + # OMNY vacuum (csaxs_bec.devices.omny.omny_vcs, Mirko 2026-11-17): measurement_ok = 1 when the + # vacuum PLC is alive, EXPVG1 + EXPVG2 OPEN and WI2VG1 CLOSED; without it the measurement stops. + "omny": [ + DeviceWithinLimitsStateConfig( + name="omny_vacuum", + device="omny_vcs", + signal="omny_vcs_measurement_ok", + low_limit=0.5, + high_limit=1.5, + tolerance=0.1, + ), + ], +} +SESSION_STATE_NAMES = {state.name for states in SESSION_BEAMLINE_STATES.values() for state in states} + + +def beamline_states_for_session(session: str | None, devices=None) -> list: + """DEFAULT_BEAMLINE_STATES + the session's extra states (only those whose device is loaded, + when `devices` is given).""" + extra = SESSION_BEAMLINE_STATES.get((session or "").lower(), []) + if devices is not None: + skipped = [state.name for state in extra if state.device not in devices] + if skipped: + print(f"Beamline states {', '.join(skipped)} skipped: their device is not loaded.") + extra = [state for state in extra if state.device in devices] + return list(DEFAULT_BEAMLINE_STATES) + extra + + +def _sync_interlock(bec, states) -> None: + """Session states in the scan interlock: watched (required "valid") when defined, removed + from the watch list when not. The default states' interlock entries are not touched.""" + try: + actors = getattr(bec, "builtin_actors", None) + interlock = getattr(actors, "scan_interlock", None) if actors is not None else None + if interlock is None: + return + watched = interlock.states_watched or {} + active = {state.name for state in states} + for name in sorted(SESSION_STATE_NAMES): + if name in active and name not in watched: + interlock.add_state_to_interlock(name, "valid") + logger.info(f"Beamline state {name} added to the scan interlock.") + elif name not in active and name in watched: + interlock.remove_state_from_interlock(name) + logger.info(f"Beamline state {name} removed from the scan interlock.") + except Exception as exc: # pylint: disable=broad-except + logger.warning(f"Scan interlock not updated: {exc}") + + +def _definition(state) -> tuple: + return (state.state_type, tuple(sorted(state.model_dump().items(), key=lambda kv: kv[0]))) + + +def set_default_beamline_states(bec, states=None, ready_timeout: float = 5.0, session: str | None = None) -> bool: + """ + Make the beamline states in BEC exactly `states` (default: DEFAULT_BEAMLINE_STATES plus the + session's extra states, SESSION_BEAMLINE_STATES), then keep the session states' scan interlock + entries in step (_sync_interlock). + + Never raises: problems are logged and printed, so the client startup always continues. + + Returns: + True if the states match the defaults afterwards (changed or already correct). + """ + if states is None: + devices = getattr(getattr(bec, "device_manager", None), "devices", None) + states = beamline_states_for_session(session, devices) + ok = _apply_states(bec, states, ready_timeout) + if ok: + _sync_interlock(bec, states) + return ok + + +def _apply_states(bec, states, ready_timeout: float) -> bool: + try: + manager = getattr(bec, "beamline_states", None) + if manager is None: + logger.warning("Beamline states are not available in this BEC client.") + return False + + deadline = time.monotonic() + ready_timeout + while not manager.ready and time.monotonic() < deadline: + time.sleep(0.05) + if not manager.ready: + logger.warning("Beamline states were not loaded from Redis; defaults not applied.") + return False + + # pylint: disable=protected-access + current = {_definition(state) for state in manager._states.values()} + if current == {_definition(state) for state in states}: + logger.info("Beamline states already match the defaults.") + return True + + devices = bec.device_manager.devices + missing = [state.name for state in states if state.device not in devices] + if missing: + # do not clear the existing states if the defaults cannot all be added + print( + "Beamline states not changed: the devices of" + f" {', '.join(missing)} are not loaded in this configuration." + ) + return False + + for name in list(manager._states): + manager.delete(name) + failed = [] + for state in states: + try: + manager.add(state) + except Exception as exc: # pylint: disable=broad-except + failed.append(f"{state.name}: {exc}") + if failed: + print("Failed to add beamline states:\n " + "\n ".join(failed)) + return False + logger.success(f"Beamline states set to the {len(states)} defaults.") + return True + except Exception as exc: # pylint: disable=broad-except + logger.warning(f"Setting the default beamline states failed: {exc}") + print(f"Setting the default beamline states failed: {exc}") + return False diff --git a/csaxs_bec/bec_ipython_client/startup/post_startup.py b/csaxs_bec/bec_ipython_client/startup/post_startup.py index 16aff438..3414d35b 100644 --- a/csaxs_bec/bec_ipython_client/startup/post_startup.py +++ b/csaxs_bec/bec_ipython_client/startup/post_startup.py @@ -144,4 +144,10 @@ def _check_account_mismatch(): if _args.session.lower() == "lamni" or _args.session.lower() == "flomni" or _args.session.lower() == "omny": - _check_account_mismatch() \ No newline at end of file + _check_account_mismatch() + + # DEFAULT BEAMLINE STATES (watched by the scan interlock of the tomography scans), + # plus the session's own states (OMNY: omny_vacuum) + from csaxs_bec.bec_ipython_client.startup.beamline_states import set_default_beamline_states + + set_default_beamline_states(bec, session=_args.session.lower()) \ No newline at end of file diff --git a/tests/tests_bec_ipython_client/test_default_beamline_states.py b/tests/tests_bec_ipython_client/test_default_beamline_states.py new file mode 100644 index 00000000..dabb4758 --- /dev/null +++ b/tests/tests_bec_ipython_client/test_default_beamline_states.py @@ -0,0 +1,147 @@ +from types import SimpleNamespace + +from bec_lib.bl_states import DeviceWithinLimitsStateConfig + +from csaxs_bec.bec_ipython_client.startup.beamline_states import ( + DEFAULT_BEAMLINE_STATES, + beamline_states_for_session, + set_default_beamline_states, +) + +DEFAULT_DEVICES = {"curr", "idgap", "shutter", "ofb", "shutter_es"} + + +class FakeStateManager: + def __init__(self, states=(), ready=True, fail_on=()): + self._states = {state.name: state for state in states} + self.ready = ready + self.fail_on = set(fail_on) + self.calls = [] + + def delete(self, name): + self.calls.append(("delete", name)) + self._states.pop(name, None) + + def add(self, state): + self.calls.append(("add", state.name)) + if state.name in self.fail_on: + raise TimeoutError("no initial status") + self._states[state.name] = state + + +def _bec(manager, devices=DEFAULT_DEVICES): + return SimpleNamespace( + beamline_states=manager, device_manager=SimpleNamespace(devices=set(devices)) + ) + + +def _names(manager): + return set(manager._states) + + +def test_defaults_match_the_beamline_setup(): + by_name = {state.name: state.model_dump() for state in DEFAULT_BEAMLINE_STATES} + assert by_name["curr_device_within_limits_state"]["low_limit"] == 380.0 + assert by_name["idgap_device_within_limits_state"]["high_limit"] == 8.0 + assert {state.device for state in DEFAULT_BEAMLINE_STATES} == DEFAULT_DEVICES + assert all(state.tolerance == 0.1 for state in DEFAULT_BEAMLINE_STATES) + + +def test_other_states_are_cleared_and_defaults_added(): + extra = DeviceWithinLimitsStateConfig(name="extra_state", device="curr", low_limit=1.0) + manager = FakeStateManager([extra]) + assert set_default_beamline_states(_bec(manager)) + assert _names(manager) == {state.name for state in DEFAULT_BEAMLINE_STATES} + assert manager.calls[0] == ("delete", "extra_state") + + +def test_changed_limit_is_reset(): + changed = [ + state.model_copy(update={"low_limit": 300.0}) + if state.name == "curr_device_within_limits_state" + else state + for state in DEFAULT_BEAMLINE_STATES + ] + manager = FakeStateManager(changed) + assert set_default_beamline_states(_bec(manager)) + assert manager._states["curr_device_within_limits_state"].low_limit == 380.0 + + +def test_matching_states_are_left_untouched(): + manager = FakeStateManager(DEFAULT_BEAMLINE_STATES) + assert set_default_beamline_states(_bec(manager)) + assert manager.calls == [] + + +def test_missing_device_keeps_the_existing_states(): + extra = DeviceWithinLimitsStateConfig(name="extra_state", device="curr", low_limit=1.0) + manager = FakeStateManager([extra]) + assert not set_default_beamline_states(_bec(manager, DEFAULT_DEVICES - {"idgap"})) + assert manager.calls == [] + assert _names(manager) == {"extra_state"} + + +def test_failed_add_does_not_raise(): + manager = FakeStateManager(fail_on={"ofb_device_within_limits_state"}) + assert not set_default_beamline_states(_bec(manager)) + assert "shutter_es_device_within_limits_state" in _names(manager) + + +def test_not_ready_or_unavailable_does_not_raise(): + assert not set_default_beamline_states(_bec(FakeStateManager(ready=False)), ready_timeout=0.1) + assert not set_default_beamline_states(SimpleNamespace(beamline_states=None)) + assert not set_default_beamline_states(object()) + + +# ── session states (OMNY vacuum) and their scan interlock entries ──────────────────────────── + + +class FakeInterlock: + def __init__(self, watched=None): + self.states_watched = dict(watched or {}) + + def add_state_to_interlock(self, name, required_value=None): + self.states_watched[name] = [required_value] + + def remove_state_from_interlock(self, name): + self.states_watched.pop(name, None) + + +def _bec_il(manager, interlock, devices=DEFAULT_DEVICES | {"omny_vcs"}): + b = _bec(manager, devices) + b.builtin_actors = SimpleNamespace(scan_interlock=interlock) + return b + + +def test_omny_session_adds_the_vacuum_state_and_watches_it(): + manager, il = FakeStateManager(DEFAULT_BEAMLINE_STATES), FakeInterlock({"curr_device_within_limits_state": ["valid"]}) + assert set_default_beamline_states(_bec_il(manager, il), session="omny") + vac = manager._states["omny_vacuum"] + assert (vac.device, vac.signal, vac.low_limit, vac.high_limit) == ("omny_vcs", "omny_vcs_measurement_ok", 0.5, 1.5) + assert _names(manager) == {s.name for s in DEFAULT_BEAMLINE_STATES} | {"omny_vacuum"} + assert il.states_watched["omny_vacuum"] == ["valid"] + assert il.states_watched["curr_device_within_limits_state"] == ["valid"] # default entries untouched + + +def test_other_session_removes_the_vacuum_state_from_the_interlock(): + omny = beamline_states_for_session("omny") + manager, il = FakeStateManager(omny), FakeInterlock({"omny_vacuum": ["valid"], "shutter_device_within_limits_state": ["valid"]}) + assert set_default_beamline_states(_bec_il(manager, il), session="flomni") + assert "omny_vacuum" not in _names(manager) + assert "omny_vacuum" not in il.states_watched + assert "shutter_device_within_limits_state" in il.states_watched + + +def test_omny_session_without_vcs_device_keeps_the_defaults(capsys): + manager, il = FakeStateManager(), FakeInterlock() + assert set_default_beamline_states(_bec_il(manager, il, DEFAULT_DEVICES), session="omny") + assert _names(manager) == {s.name for s in DEFAULT_BEAMLINE_STATES} + assert "omny_vacuum" not in il.states_watched + assert "skipped" in capsys.readouterr().out + + +def test_matching_omny_states_untouched_but_interlock_synced(): + manager, il = FakeStateManager(beamline_states_for_session("omny")), FakeInterlock() + assert set_default_beamline_states(_bec_il(manager, il), session="omny") + assert manager.calls == [] + assert il.states_watched == {"omny_vacuum": ["valid"]}