feat(client): set default beamline states for LamNI, OMNY and flOMNI sessions
Read the Docs Deploy Trigger / trigger-rtd-webhook (push) Successful in 2s
CI for csaxs_bec / test (push) Successful in 3m47s

The scan interlock of the tomography scans watches the beamline states.
At client startup of the lamni, omny and flomni sessions the states are
made exactly the defaults (ring current >= 380, idgap <= 8, shutter,
ofb and shutter_es >= 0.5, tolerance 0.1): if they differ, all states
are deleted and the defaults added.

- states are global: if they already match, nothing is touched, so a
  client started during a running scan does not disturb the interlock
- if a device of the defaults is not loaded, the existing states are
  kept
- never raises; problems are printed and logged, startup continues

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M8zoDzRrboFFDabqB9bLNZ
This commit was merged in pull request #357.
This commit is contained in:
x12saandClaude Opus 5.5 authored and holler committed 2026-11-17 15:29:15 +01:00
1 parent e193727c10
commit 660532db79
3 files changed
+218 -1

No files matched your search

@@ -0,0 +1,120 @@
"""
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,
),
]
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) -> bool:
"""
Make the beamline states in BEC exactly `states` (default: DEFAULT_BEAMLINE_STATES).
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).
"""
states = DEFAULT_BEAMLINE_STATES if states is None else states
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
@@ -144,4 +144,9 @@ def _check_account_mismatch():
if _args.session.lower() == "lamni" or _args.session.lower() == "flomni" or _args.session.lower() == "omny":
_check_account_mismatch()
_check_account_mismatch()
# DEFAULT BEAMLINE STATES (watched by the scan interlock of the tomography scans)
from csaxs_bec.bec_ipython_client.startup.beamline_states import set_default_beamline_states
set_default_beamline_states(bec)
@@ -0,0 +1,92 @@
from types import SimpleNamespace
from bec_lib.bl_states import DeviceWithinLimitsStateConfig
from csaxs_bec.bec_ipython_client.startup.beamline_states import (
DEFAULT_BEAMLINE_STATES,
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())