diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py index 8bbe8f8e..0c6296f6 100644 --- a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py +++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni.py @@ -400,6 +400,12 @@ class LamNI( self.device_manager = client.device_manager self.init = LaMNIInitStages(client) + # operating settings of the real-time loop (web HMI loop settings on mpc-lamni, staff only; + # lamni_realtime_system.py): lamni.rt_settings.show() / .standard() / .large_steps() / .help() + from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni_realtime_system import LamniRealtimeSystem + + self.rt_settings = LamniRealtimeSystem(device_manager=self.device_manager) + # Correction state: corr_pos_x/y/angle (+ _2 iteration) are now # global-var-backed properties defined in LamNIAlignmentMixin, so # they are NOT initialized as plain lists here -- doing so would diff --git a/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_realtime_system.py b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_realtime_system.py new file mode 100644 index 00000000..d6fbf8fe --- /dev/null +++ b/csaxs_bec/bec_ipython_client/plugins/LamNI/lamni_realtime_system.py @@ -0,0 +1,89 @@ +"""lamni.rt_settings: the operating settings of the LaMNI real-time loop. + +BEAMLINE SCIENTISTS / LOCAL CONTACT ONLY - not for users. These settings change how the detector trigger and the +sample-stage moves (target shaper, ramp rate) work; a wrong combination can spoil a beamtime's data. The rules refuse +combinations that do not work, but not ones that are only unsuitable for an experiment. + +The settings, the parameters they map onto, the profiles and the rules live in the LamNI instrument repository +(LAMNIcontrol/loopsettings/lamni.json) and are applied by the web HMI on the loop machine mpc-lamni (RT-system +webhmi/loopsettings.py). This client only talks to its REST API (/api/settings); it holds no logic of its own, so the +web page (tab "Loop settings") and BEC always behave the same way. Same commands as flomni.rt_settings / omny.rt_settings +(2026-11-19). + + lamni.rt_settings.show() all settings, rules, scan state + lamni.rt_settings.set(trigger_tolerance_nm=5) change (refused if a rule objects) + lamni.rt_settings.check(slew_rate_um_s=5000) dry run + lamni.rt_settings.profiles() the profiles: standard (default) / large_steps + lamni.rt_settings.standard() profile standard: max error ~10 nm, 0.2-2 um steps + lamni.rt_settings.large_steps() profile large_steps: 3-8 um steps, ~50 nm, twice as fast + lamni.rt_settings.save_as_default() write the live values into the .xmp files + +Changes are live only: the next start of the control loop uses the .xmp files again (profile standard). + +Connection: through the BEC device lamni_loop_settings (RPC; the API token is in its device config, ptycho_lamni.yaml) +when it exists and is enabled, else directly to the web HMI (devices/omny/webhmi_client.py: URL http://:8080 +with port-80 fallback, token from token_file / ~/.flomni_webhmi_token or FLOMNI_WEBHMI_TOKEN_FILE). +""" + +from csaxs_bec.bec_ipython_client.plugins.flomni.flomni_realtime_system import ( # noqa: F401 + FlomniRealtimeSystem, + RealtimeSystemError, +) + +_MODULE_DOC = __doc__ + +STAFF_ONLY = ("lamni.rt_settings: beamline scientists / local contact only - not for users " + "(LaMNI loop settings: LamNI LAMNIcontrol/tuning_guide.md, section 2b).") + +NO_TRACKER = "LaMNI has no laser tracker: the tracking settings exist on flOMNI / OMNY only" + + +class LamniRealtimeSystem(FlomniRealtimeSystem): + """lamni.rt_settings: the flOMNI client with the LaMNI device and texts. Requests go through the BEC device + lamni_loop_settings (RPC api_get / api_post; the token is in its device config) when it exists and is enabled; + otherwise directly to the web HMI of the rtx host (mpc-lamni).""" + + DEVICE = "lamni_loop_settings" + STAFF_ONLY = STAFF_ONLY + DOC = _MODULE_DOC + HELP_EXAMPLE = "slew_rate_um_s" + + def trigger_set_tolerance_nm(self, tolerance_nm: float): + """|sample position - target| x and y (interferometer) within this (nm) for the hold time (averaged over + trigger_filter_ms); 5 standard, 25 large_steps. 0 = the former criterion (on-target flags of PID_x / PID_y).""" + return self.set(trigger_tolerance_nm=tolerance_nm) + + def trigger_set_soft(self, enable: bool, exposure_ms: float = None): + """Soft trigger (working without detector): True = no hardware trigger leaves the loop, every trigger starts + an emulated exposure of exposure_ms (default: unchanged); False = hardware trigger. Never saved as default (the + loop starts with the hardware trigger). Only between scans.""" + return super().trigger_set_soft(enable, exposure_ms) + + def standard(self) -> dict: + """Profile standard (the default): trigger 5 nm / 2 ms average / 5 ms hold, full shaper, 2000 um/s; 0.2-2 um + steps, max error during the exposure about 5-7 nm.""" + return self.apply_profile("standard") + + def large_steps(self) -> dict: + """Profile large_steps: trigger 25 nm / 2 ms average / 2 ms hold, full shaper, 5000 um/s; 3-8 um steps about + twice as fast as standard, max error during the exposure about 20-30 nm (below 50 nm).""" + return self.apply_profile("large_steps") + + # LaMNI has no laser tracker + def tracking_targets(self): + raise RealtimeSystemError(NO_TRACKER) + + def tracking_show(self): + raise RealtimeSystemError(NO_TRACKER) + + def tracking_set_target_y(self, val: float): + raise RealtimeSystemError(NO_TRACKER) + + def tracking_set_target_z(self, val: float): + raise RealtimeSystemError(NO_TRACKER) + + def tracking_set_interferometer_threshold(self, val: float): + raise RealtimeSystemError(NO_TRACKER) + + def tracking_set_psd_threshold_low(self, val: float): + raise RealtimeSystemError(NO_TRACKER) diff --git a/csaxs_bec/bec_ipython_client/plugins/flomni/flomni_realtime_system.py b/csaxs_bec/bec_ipython_client/plugins/flomni/flomni_realtime_system.py index 598d262f..8a5e0721 100644 --- a/csaxs_bec/bec_ipython_client/plugins/flomni/flomni_realtime_system.py +++ b/csaxs_bec/bec_ipython_client/plugins/flomni/flomni_realtime_system.py @@ -27,6 +27,8 @@ from csaxs_bec.devices.omny.webhmi_client import WebHmiClient from csaxs_bec.devices.omny.webhmi_client import WebHmiError as RealtimeSystemError # name kept for BEC users +_MODULE_DOC = __doc__ # help() prints it (a class body's __doc__ would be the class docstring) + STAFF_ONLY = ("flomni.rt_settings: beamline scientists / local contact only - not for users " "(plugins/flomni/docs/local_contact_only-realtime_system.md).") @@ -45,6 +47,10 @@ class FlomniRealtimeSystem(WebHmiClient): devices/omny/webhmi_client.py; token from token_file / ~/.flomni_webhmi_token).""" DEVICE = "flomni_loop_settings" + # texts per instrument (OMNY: plugins/omny/omny_realtime_system.py subclasses this class, 2026-11-17) + STAFF_ONLY = STAFF_ONLY + DOC = _MODULE_DOC + HELP_EXAMPLE = "move_beyond_um_x" def __init__(self, url=None, token_file=None, device_manager=None, timeout=5.0, token=None): super().__init__(url=url, token=token, token_file=token_file, device_manager=device_manager, timeout=timeout) @@ -92,7 +98,7 @@ class FlomniRealtimeSystem(WebHmiClient): wanted = (group,) if isinstance(group, str) else tuple(group or ()) groups = {g["name"]: g for g in snap["groups"]} sc = snap.get("scan") or {} - print(STAFF_ONLY) + print(self.STAFF_ONLY) print(f"Loop settings {snap.get('instrument', '')} ({self.route}) - " + (f"scan running (mode {_fmt(sc.get('mode'))})" if sc.get("active") else "no scan")) for gname, g in groups.items(): @@ -264,18 +270,18 @@ class FlomniRealtimeSystem(WebHmiClient): does, unit, range, the loop parameters it sets, live and saved value), from the definition on the loop machine (the same text as the tooltips of the web HMI tab).""" if name is None: - print(__doc__.split("\n\nConnection:")[0]) + print(self.DOC.split("\n\nConnection:")[0]) print("\nShortcuts: trigger_show(), trigger_set_tolerance_nm(v), trigger_set_hold_ms(v)," " trigger_set_after_move(True/False), trigger_set_soft(True/False, exposure_ms), tracking_targets(), tracking_show(), tracking_set_target_y(v)," " tracking_set_target_z(v), tracking_set_interferometer_threshold(v), tracking_set_psd_threshold_low(v);" " profiles(), unsaved(), get(name)") - print('Explanations: help("all") or help(""), e.g. help("move_beyond_um_x")') + print(f'Explanations: help("all") or help(""), e.g. help("{self.HELP_EXAMPLE}")') return snap = self.read() settings = {s["name"]: s for s in snap["settings"]} groups = {g["name"]: g for g in snap["groups"]} if name == "all": - print(STAFF_ONLY) + print(self.STAFF_ONLY) for gname, g in groups.items(): rows = [s for s in snap["settings"] if s["group"] == gname] if not rows: @@ -291,7 +297,7 @@ class FlomniRealtimeSystem(WebHmiClient): if s is None: raise RealtimeSystemError(f"unknown setting '{name}'; help('all') lists them") g = groups.get(s["group"], {}) - print(STAFF_ONLY) + print(self.STAFF_ONLY) print(f"{s['name']} - {s.get('title', '')} (group {g.get('title', s['group'])}" + (", only between scans)" if g.get("interlock") else ")")) if s.get("help"): diff --git a/csaxs_bec/device_configs/ptycho_lamni.yaml b/csaxs_bec/device_configs/ptycho_lamni.yaml index 8c7355e9..82b52189 100644 --- a/csaxs_bec/device_configs/ptycho_lamni.yaml +++ b/csaxs_bec/device_configs/ptycho_lamni.yaml @@ -428,3 +428,26 @@ omny_xray_gui: readoutPriority: on_request deviceTags: - ptycho_lamni +# ############################################################ +# ############ LaMNI real-time loop settings ################## +# ############################################################ +# The loop settings (detector trigger, soft trigger, target shaper, ramp rate; LamNI LAMNIcontrol/loopsettings, profiles +# standard / large_steps) stored with every scan: read from the web HMI on the loop machine at the start of each scan +# (baseline). Web HMI down: available = 0, the scan continues. The user commands lamni.rt_settings go through this +# device (RPC), so the token is needed only here. +# token: the web HMI API token (~/loop-data/webhmi/api_token on mpc-lamni). Not filled in yet (2026-11-19): enter it +# here as for flOMNI / OMNY, or put it into token_file on the machine of the device server. +lamni_loop_settings: + description: LaMNI real-time loop settings (web HMI loop settings, snapshot at scan start) + deviceClass: csaxs_bec.devices.omny.lamni_loop_settings.LamniLoopSettings + deviceConfig: + host: mpc-lamni.psi.ch + token: "FkoqBdwcjS6OIhG2oLrx_WL2xjOi7lPGmUHNvlDx6Sw" + token_file: ~/.lamni_webhmi_token + timeout: 2.0 + enabled: true + onFailure: buffer + readOnly: true + readoutPriority: baseline + deviceTags: + - ptycho_lamni diff --git a/csaxs_bec/devices/omny/lamni_loop_settings.py b/csaxs_bec/devices/omny/lamni_loop_settings.py new file mode 100644 index 00000000..e0350d8e --- /dev/null +++ b/csaxs_bec/devices/omny/lamni_loop_settings.py @@ -0,0 +1,165 @@ +"""lamni_loop_settings: the operating settings of the LaMNI real-time loop as a baseline device (2026-11-19, Mirko). + +Same as omny_loop_settings / flomni_loop_settings (the code is a copy of devices/omny/omny_loop_settings.py with the +LaMNI setting list): read at the start of every scan (readoutPriority: baseline; the LaMNI Fermat scan calls +read_baseline_devices in prepare_scan), so each scan file holds the loop settings it ran with: detector trigger +(tolerance, hold, filter, minimum delay, after a move, soft trigger), target shaper scale and ramp rate (definition: +LamNI LAMNIcontrol/loopsettings/lamni.json, profiles standard / large_steps; served by the web HMI on mpc-lamni, +GET /api/settings). + +Signals: one per setting (float, NaN when not available; names = the setting names), and + available 1 = read from the web HMI, 0 = not available (the scan continues; message says why) + message "" or the reason it is not available + unsaved number of settings whose live value differs from the .xmp (not saved as default) + inconsistent number of settings whose parameters disagree + rules_violated number of violated error rules + definition path and sha1 of the definition file on the loop machine + snapshot_json JSON: every setting (value, saved, unsaved, consistent, unit), the violated rules, the + scan state, the definition path and sha1 + +deviceConfig: token (the API token itself, ~/loop-data/webhmi/api_token on mpc-lamni), else token_file, optional url / +host (default: the host of the rtx device config) / timeout (default 2 s for the scan snapshot). + +lamni.rt_settings (the user commands, plugins/LamNI/lamni_realtime_system.py) calls api_get / api_post of this device +by RPC, so the token is needed only here. +""" + +import json +import math +import time + +from ophyd import Component as Cpt +from ophyd import Device, Kind, Signal + +from csaxs_bec.devices.omny.webhmi_client import WebHmiClient, WebHmiError + +# the settings of lamni.json (2026-11-19); a setting added to the definition later is in snapshot_json only until it +# is added here +SETTINGS = ( + "trigger_tolerance_nm", "trigger_hold_ms", "trigger_filter_ms", "trigger_min_delay_ms", "trigger_on_move", + "trigger_soft", "soft_exposure_ms", "soft_latency_ms", + "target_shaper_scale", "slew_rate_um_s", +) + +RETRY_AFTER_FAILURE_S = 60.0 # web HMI not reachable: no new attempt for this long (a tomogram does not wait each time) + + +class LamniLoopSettings(Device): + USER_ACCESS = ["show", "snapshot", "api_get", "api_post"] + + available = Cpt(Signal, value=0, kind=Kind.normal) + message = Cpt(Signal, value="", kind=Kind.normal) + unsaved = Cpt(Signal, value=-1, kind=Kind.normal) + inconsistent = Cpt(Signal, value=-1, kind=Kind.normal) + rules_violated = Cpt(Signal, value=-1, kind=Kind.normal) + definition = Cpt(Signal, value="", kind=Kind.normal) + snapshot_json = Cpt(Signal, value="", kind=Kind.normal) + + # one signal per setting + locals().update({_n: Cpt(Signal, value=math.nan, kind=Kind.normal) for _n in SETTINGS}) + + def __init__(self, prefix="", *, name, token=None, token_file=None, url=None, host=None, timeout=2.0, + device_manager=None, **kwargs): + super().__init__(prefix, name=name, **kwargs) + self._client = WebHmiClient(url=url, token=token, token_file=token_file, host=host, + device_manager=device_manager, timeout=timeout, client_name="BEC baseline") + # requests of lamni.rt_settings (RPC from the client, below): longer timeout, no back-off + self._api = WebHmiClient(url=url, token=token, token_file=token_file, host=host, + device_manager=device_manager, timeout=max(timeout, 10.0), client_name="BEC") + self._failed_at = None + self._last = None + + def _unavailable(self, reason): + self.available.put(0) + self.message.put(str(reason)) + for n in ("unsaved", "inconsistent", "rules_violated"): + getattr(self, n).put(-1) + self.definition.put("") + self.snapshot_json.put("") + for n in SETTINGS: + getattr(self, n).put(math.nan) + + def update(self): + """Read the settings from the web HMI into the signals. Never raises: not available -> available 0.""" + now = time.time() + if self._failed_at is not None and now - self._failed_at < RETRY_AFTER_FAILURE_S: + return # keep the 'not available' values of the last failure + try: + snap = self._client.settings() + except WebHmiError as exc: + self._failed_at = now + self._unavailable(f"{exc} (next attempt after {RETRY_AFTER_FAILURE_S:.0f} s)") + return + except Exception as exc: # noqa: BLE001 (a broken answer must not stop a scan) + self._failed_at = now + self._unavailable(f"unexpected answer from the web HMI: {exc}") + return + self._failed_at = None + self._last = snap + values = {s["name"]: s for s in snap.get("settings", [])} + for n in SETTINGS: + v = values.get(n, {}).get("value") + getattr(self, n).put(float(v) if isinstance(v, (int, float)) else math.nan) # bool is an int too + self.unsaved.put(sum(1 for s in values.values() if s.get("unsaved"))) + self.inconsistent.put(sum(1 for s in values.values() if not s.get("consistent", True))) + self.rules_violated.put(sum(1 for r in snap.get("rules", []) if not r.get("ok") and r.get("severity") == "error")) + self.definition.put(f"{snap.get('definition', '')} sha1 {snap.get('definition_sha1', '?')}") + missing = [n for n in values if n not in SETTINGS] + self.message.put(f"settings not stored as own signals (in snapshot_json): {', '.join(missing)}" if missing else "") + # compact: values and flags only (help texts and parameter mappings are in the definition, see its sha1) + compact = { + "instrument": snap.get("instrument"), "definition": snap.get("definition"), + "definition_sha1": snap.get("definition_sha1"), "scan": snap.get("scan"), + "settings": {n: {"value": s.get("value"), "saved": s.get("saved"), "unsaved": s.get("unsaved"), + "consistent": s.get("consistent"), "unit": s.get("unit", "")} + for n, s in values.items()}, + "rules_violated": [{"name": r.get("name"), "severity": r.get("severity"), "message": r.get("message")} + for r in snap.get("rules", []) if not r.get("ok")], + } + self.snapshot_json.put(json.dumps(compact, separators=(",", ":"))) + self.available.put(1) + + def read(self): + self.update() + return super().read() + + # ── RPC for lamni.rt_settings: the user commands go through this device, so the API token is needed only + # in its device config (device server), not on the client. Not called set / put: the device server treats + # those names as ophyd writes (refused on a readOnly device). + + _API_PATHS = ("/api/settings", "/api/status") + + def _check_path(self, path): + if not any(path == p or path.startswith(p + "/") for p in self._API_PATHS): + raise WebHmiError(f"path {path!r} not allowed (only /api/settings*, /api/status)") + + def api_get(self, path: str = "/api/settings") -> dict: + """GET a web HMI loop-settings endpoint; returns its JSON. Errors raise (passed to the client).""" + self._check_path(path) + return self._api._request(path) + + def api_post(self, path: str, body: dict = None) -> dict: + """POST to a web HMI loop-settings endpoint (plan / apply / save); returns its JSON.""" + self._check_path(path) + return self._api._request(path, body or {}) + + def snapshot(self) -> dict: + """Read now and return {setting: value} (empty when not available).""" + self._failed_at = None # an explicit request always tries + self.update() + if not self.available.get(): + return {} + return {n: getattr(self, n).get() for n in SETTINGS} + + def show(self): + """Print the settings as they would be stored with a scan now.""" + snap = self.snapshot() + if not snap: + print(f"loop settings not available: {self.message.get()}") + return + for n, v in snap.items(): + print(f" {n:30s} {v:g}") + print(f"unsaved {self.unsaved.get()}, inconsistent {self.inconsistent.get()}, " + f"rules violated {self.rules_violated.get()}; {self.definition.get()}") + if self.message.get(): + print(self.message.get()) diff --git a/csaxs_bec/devices/omny/rt/rt_lamni_ophyd.py b/csaxs_bec/devices/omny/rt/rt_lamni_ophyd.py index 798553a2..3586843a 100644 --- a/csaxs_bec/devices/omny/rt/rt_lamni_ophyd.py +++ b/csaxs_bec/devices/omny/rt/rt_lamni_ophyd.py @@ -361,8 +361,19 @@ class RtLamniController(Controller): raise RuntimeError("lsamy center is not defined") lsamx_center = lsamx_user_params.get("center") lsamy_center = lsamy_user_params.get("center") - self.device_manager.devices.lsamx.obj.move(lsamx_center, wait=True) - self.device_manager.devices.lsamy.obj.move(lsamy_center, wait=True) + # lsamx and lsamy move at the same time (was one after the other; Mirko 2026-11-19). + # The same parallel move is used by umv(dev.lsamx, ..., dev.lsamy, ...) in x_ray_eye_align. + lsamx = self.device_manager.devices.lsamx.obj + lsamy = self.device_manager.devices.lsamy.obj + status_x = lsamx.move(lsamx_center, wait=False) + status_y = lsamy.move(lsamy_center, wait=False) + try: + status_x.wait() + status_y.wait() + except KeyboardInterrupt: + lsamx.stop() + lsamy.stop() + raise self.socket_put("J1") _waitforfeedbackctr = 0 diff --git a/csaxs_bec/scans/lamni_fermat_scan.py b/csaxs_bec/scans/lamni_fermat_scan.py index 817347eb..346c02e3 100644 --- a/csaxs_bec/scans/lamni_fermat_scan.py +++ b/csaxs_bec/scans/lamni_fermat_scan.py @@ -20,6 +20,8 @@ import time from typing import Annotated import numpy as np +from bec_lib import messages +from bec_lib.alarm_handler import Alarms from bec_lib.logger import bec_logger from bec_lib.scan_args import DefaultArgType, ScanArgument, Units from bec_server.scan_server.errors import ScanAbortion @@ -521,6 +523,62 @@ class LamniFermatScan(ScanBase): ) self.dev.lsamrot.set(angle).wait() + def at_beamline(self) -> tuple[bool, str]: + """ + Is this session at the beamline? True when ddg1 is configured with a real (not simulated) device class + (as the flOMNI scan, flomni_fermat_scan.py; LaMNI soft trigger 2026-11-19). A failing check counts as beamline, + so the hardware trigger is the fallback. + + Returns: + (at_beamline, reason) + """ + try: + devices = self.device_manager.devices + if "ddg1" in devices: + cls = str((getattr(devices["ddg1"], "_config", None) or {}).get("deviceClass", "")) + if ".sim." not in cls and "Simulated" not in cls: + return True, f"ddg1 is {cls or 'not simulated'}" + return False, "ddg1 simulated or absent" + except Exception as exc: # pylint: disable=broad-except + return True, f"beamline check failed ({exc}), treated as beamline" + + def set_trigger_source(self): + """ + Set the trigger source of the LaMNI loop (loop setting trigger_soft, web HMI via lamni_loop_settings): at the + beamline the hardware trigger (the loop's default); otherwise the soft trigger with the exposure + exp_time x frames_per_trigger, so a scan runs without detector. At the beamline the scan is aborted if the + hardware trigger cannot be confirmed (with the soft trigger the detector would not be triggered while LaMNI + exposes internally). Without the device lamni_loop_settings nothing is changed (warning). + """ + at_bl, reason = self.at_beamline() + if at_bl: + changes = {"trigger_soft": 0} + else: + changes = {"trigger_soft": 1, + "soft_exposure_ms": float(self.exp_time) * float(self.frames_per_trigger) * 1000.0} + try: + res = self.dev.lamni_loop_settings.api_post( + "/api/settings/apply", {"changes": changes, "profile": None, "adjust": False} + ) + errors = [] if res and res.get("ok") else list((res or {}).get("errors") or ["no answer"]) + except Exception as exc: # pylint: disable=broad-except + errors = [str(exc)] + source = "hardware" if at_bl else "soft" + if errors: + text = f"LaMNI trigger source {source} ({reason}) not set: {'; '.join(errors)}" + if at_bl: + raise ScanAbortion(text + ". At the beamline the hardware trigger must be confirmed.") + logger.warning(text) + self.device_manager.connector.raise_alarm( + severity=Alarms.WARNING, + info=messages.ErrorInfo( + error_message=text, compact_error_message=text, exception_type="TriggerSource", + device="lamni_loop_settings", + ), + ) + return + logger.info(f"LaMNI trigger source: {source} ({reason}), {changes}") + def prepare_setup(self): """ Prepare the setup for the scan: @@ -529,8 +587,11 @@ class LamniFermatScan(ScanBase): - Compute the total shift based on the center, stitch, and user-defined shifts, and move to the new scan center using the interferometer feedback. - Transfer the positions to the RT controller by adding them to the trajectory generator. + - Set the trigger source of the LaMNI loop: hardware at the beamline, soft otherwise. """ self.dev.rtx.controller.clear_trajectory_generator() + # Trigger source of the LaMNI loop (before the baseline read, so the scan file holds the source in use) + self.set_trigger_source() self.lamni_rotation(self.angle) total_shift_x, total_shift_y = LamniFermatScan._compute_total_shift( center_x=self.center_x, diff --git a/tests/tests_bec_ipython_client/test_lamni_realtime_system.py b/tests/tests_bec_ipython_client/test_lamni_realtime_system.py new file mode 100644 index 00000000..6061e440 --- /dev/null +++ b/tests/tests_bec_ipython_client/test_lamni_realtime_system.py @@ -0,0 +1,99 @@ +"""Tests for lamni.rt_settings (lamni_realtime_system.py, 2026-11-19): the flOMNI loop-settings client with the LaMNI +device and texts. A small local HTTP server stands in for the web HMI on mpc-lamni.""" + +import json +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer +from unittest import mock + +import pytest + +from csaxs_bec.bec_ipython_client.plugins.flomni.flomni_realtime_system import FlomniRealtimeSystem +from csaxs_bec.bec_ipython_client.plugins.LamNI.lamni_realtime_system import ( + LamniRealtimeSystem, + RealtimeSystemError, +) + +TOKEN = "lamni-client-token-0123456789" + +SNAP = { + "instrument": "LaMNI", "note": "Live only.", "scan": {"mode": 0, "active": False, "text": ""}, + "groups": [{"name": "trigger", "title": "Detector trigger"}, {"name": "motion", "title": "Sample stage moves"}], + "settings": [ + {"name": "trigger_tolerance_nm", "group": "trigger", "unit": "nm", "value": 5.0, "saved": 5.0, + "unsaved": False, "consistent": True, "issues": [], "info": None}, + {"name": "slew_rate_um_s", "group": "motion", "unit": "um/s", "value": 2000.0, "saved": 2000.0, + "unsaved": False, "consistent": True, "issues": [], "info": None}, + ], + "rules": [], + "profiles": [{"name": "standard", "title": "Standard", "help": "", "values": {}}, + {"name": "large_steps", "title": "Large steps, fast", "help": "", "values": {}}], +} + + +class _Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + ok = self.headers.get("Authorization") == "Bearer " + TOKEN + data = json.dumps(SNAP if ok else {"detail": "login required"}).encode() + self.send_response(200 if ok else 401) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + +@pytest.fixture +def url(): + srv = HTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{srv.server_address[1]}" + srv.shutdown() + + +def test_lamni_client_is_the_flomni_client_with_lamni_device_and_texts(): + assert issubclass(LamniRealtimeSystem, FlomniRealtimeSystem) + assert LamniRealtimeSystem.DEVICE == "lamni_loop_settings" + assert LamniRealtimeSystem.DOC.startswith("lamni.rt_settings") + assert "lamni.rt_settings" in LamniRealtimeSystem.STAFF_ONLY + assert FlomniRealtimeSystem.DOC.startswith("flomni.rt_settings") # flOMNI unchanged + + +def test_direct_read_and_show(url, capsys): + rts = LamniRealtimeSystem(url=url, token=TOKEN) + assert rts.get("slew_rate_um_s") == 2000.0 + rts.show() + out = capsys.readouterr().out + assert "lamni.rt_settings: beamline scientists" in out and "Loop settings LaMNI" in out + + +def test_help_prints_the_lamni_text(url, capsys): + LamniRealtimeSystem(url=url, token=TOKEN).help() + out = capsys.readouterr().out + assert out.startswith("lamni.rt_settings: the operating settings of the LaMNI real-time loop") + assert 'help("slew_rate_um_s")' in out + + +def test_no_tracker_on_lamni(url): + with pytest.raises(RealtimeSystemError, match="no laser tracker"): + LamniRealtimeSystem(url=url, token=TOKEN).tracking_targets() + + +def test_profile_shortcuts_apply_the_named_profiles(): + rts = LamniRealtimeSystem(url="http://127.0.0.1:1", token=TOKEN) + with mock.patch.object(LamniRealtimeSystem, "apply_profile", return_value={"ok": True}) as ap: + rts.standard() + rts.large_steps() + assert [c.args[0] for c in ap.call_args_list] == ["standard", "large_steps"] + + +def test_routes_through_the_lamni_device(): + dm = mock.MagicMock() + dm.devices.lamni_loop_settings.enabled = True + dm.devices.lamni_loop_settings.api_get.return_value = SNAP + rts = LamniRealtimeSystem(device_manager=dm) + assert rts.route == "device lamni_loop_settings" + assert rts.get("trigger_tolerance_nm") == 5.0 + dm.devices.lamni_loop_settings.api_get.assert_called_with("/api/settings") diff --git a/tests/tests_devices/test_lamni_loop_settings.py b/tests/tests_devices/test_lamni_loop_settings.py new file mode 100644 index 00000000..c79bf41e --- /dev/null +++ b/tests/tests_devices/test_lamni_loop_settings.py @@ -0,0 +1,78 @@ +"""Tests for the baseline device lamni_loop_settings (devices/omny/lamni_loop_settings.py, 2026-11-19): the loop settings +of the LaMNI web HMI stored with every scan. A small local HTTP server stands in for the web HMI (/api/settings).""" + +import json +import math +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import pytest + +from csaxs_bec.devices.omny.lamni_loop_settings import SETTINGS, LamniLoopSettings +from csaxs_bec.devices.omny.webhmi_client import WebHmiError + +TOKEN = "lamni-device-token-0123456789" + +SNAP = { + "instrument": "LaMNI", "definition": "/home/control/LamNI/LAMNIcontrol/loopsettings/lamni.json", + "definition_sha1": "b" * 40, "scan": {"mode": 0, "active": False, "text": ""}, + "settings": [ + {"name": "trigger_tolerance_nm", "value": 10.0, "unsaved": False, "consistent": True}, + {"name": "target_shaper_scale", "value": 1.0, "unsaved": True, "consistent": True}, + {"name": "slew_rate_um_s", "value": 2000.0, "unsaved": False, "consistent": True}, + {"name": "trigger_soft", "value": 0, "unsaved": False, "consistent": True}, + ], + "rules": [], +} + + +class _Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + code, body = (200, SNAP) if self.headers.get("Authorization") == "Bearer " + TOKEN else (401, {"detail": "no"}) + data = json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + +@pytest.fixture +def url(): + srv = HTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{srv.server_address[1]}" + srv.shutdown() + + +def test_lamni_settings_list(): + assert "slew_rate_um_s" in SETTINGS and "target_shaper_scale" in SETTINGS and "trigger_soft" in SETTINGS + assert not any(n.startswith(("fzp", "abbe", "tracking", "psd")) or n == "trigger_topup" for n in SETTINGS) + + +def test_read_stores_the_omny_settings(url): + dev = LamniLoopSettings(name="lamni_loop_settings", url=url, token=TOKEN) + r = dev.read() + assert r["lamni_loop_settings_available"]["value"] == 1 + assert r["lamni_loop_settings_slew_rate_um_s"]["value"] == 2000.0 + assert r["lamni_loop_settings_trigger_tolerance_nm"]["value"] == 10.0 + assert r["lamni_loop_settings_unsaved"]["value"] == 1 + assert math.isnan(r["lamni_loop_settings_trigger_hold_ms"]["value"]) # not in this answer + assert json.loads(r["lamni_loop_settings_snapshot_json"]["value"])["instrument"] == "LaMNI" + + +def test_wrong_token_is_not_available_and_does_not_raise(url): + dev = LamniLoopSettings(name="lamni_loop_settings", url=url, token="wrong-token-0123456789") + r = dev.read() + assert r["lamni_loop_settings_available"]["value"] == 0 + assert "401" in r["lamni_loop_settings_message"]["value"] + + +def test_rpc_paths_are_restricted(url): + dev = LamniLoopSettings(name="lamni_loop_settings", url=url, token=TOKEN) + assert dev.api_get("/api/settings")["instrument"] == "LaMNI" + with pytest.raises(WebHmiError): + dev.api_get("/api/terminal") diff --git a/tests/tests_devices/test_rt_lamni_reset.py b/tests/tests_devices/test_rt_lamni_reset.py new file mode 100644 index 00000000..924a27de --- /dev/null +++ b/tests/tests_devices/test_rt_lamni_reset.py @@ -0,0 +1,80 @@ +from unittest import mock + +import pytest +from ophyd_devices.tests.utils import SocketMock + +from csaxs_bec.devices.omny.rt.rt_lamni_ophyd import RtLamniController + + +@pytest.fixture() +def rt_lamni(): + RtLamniController._reset_controller() + rt = RtLamniController( + name="rt_lamni", + socket_cls=SocketMock, + socket_host="localhost", + socket_port=3333, + device_manager=mock.MagicMock(), + ) + yield rt + RtLamniController._reset_controller() + + +def _prepare(rt): + """Coarse stages with a center, lsamrot at 0, Galil ready; returns a mock recording the call order.""" + devices = rt.device_manager.devices + devices.lsamrot.obj.readback.get.return_value = 0.0 + devices.lsamx.user_parameter = {"center": 1.5} + devices.lsamy.user_parameter = {"center": -2.5} + devices.lsamx.obj.controller.lgalil_is_air_off_and_orchestra_enabled.return_value = 1 + order = mock.MagicMock() + status_x, status_y = mock.MagicMock(name="status_x"), mock.MagicMock(name="status_y") + devices.lsamx.obj.move.return_value = status_x + devices.lsamy.obj.move.return_value = status_y + order.attach_mock(devices.lsamx.obj.move, "move_x") + order.attach_mock(devices.lsamy.obj.move, "move_y") + order.attach_mock(status_x.wait, "wait_x") + order.attach_mock(status_y.wait, "wait_y") + return order + + +def test_feedback_enable_with_reset_moves_lsamx_lsamy_together(rt_lamni): + order = _prepare(rt_lamni) + with ( + mock.patch.object(rt_lamni, "feedback_status_angle_lamni", return_value=True), + mock.patch.object(rt_lamni, "feedback_disable"), + mock.patch.object(rt_lamni, "clear_trajectory_generator"), + mock.patch.object(rt_lamni, "get_axis_by_name"), + mock.patch.object(rt_lamni, "set_device_read_write"), + mock.patch.object(rt_lamni, "socket_put_and_receive", return_value="0,0,0"), + mock.patch.object(rt_lamni, "socket_put") as socket_put, + mock.patch("time.sleep"), + ): + order.attach_mock(socket_put, "socket_put") + rt_lamni.feedback_enable_with_reset() + + names = [c[0] for c in order.mock_calls if c[0] in ("move_x", "move_y", "wait_x", "wait_y") + or (c[0] == "socket_put" and c.args == ("J1",))] + # both moves are started (without waiting) before the first wait; J1 only after both are done + assert names == ["move_x", "move_y", "wait_x", "wait_y", "socket_put"] + assert order.move_x.call_args == mock.call(1.5, wait=False) + assert order.move_y.call_args == mock.call(-2.5, wait=False) + + +def test_feedback_enable_with_reset_ctrl_c_stops_both_axes(rt_lamni): + _prepare(rt_lamni) + devices = rt_lamni.device_manager.devices + devices.lsamx.obj.move.return_value.wait.side_effect = KeyboardInterrupt + with ( + mock.patch.object(rt_lamni, "feedback_status_angle_lamni", return_value=True), + mock.patch.object(rt_lamni, "feedback_disable"), + mock.patch.object(rt_lamni, "clear_trajectory_generator"), + mock.patch.object(rt_lamni, "get_axis_by_name"), + mock.patch.object(rt_lamni, "socket_put") as socket_put, + mock.patch("time.sleep"), + pytest.raises(KeyboardInterrupt), + ): + rt_lamni.feedback_enable_with_reset() + devices.lsamx.obj.stop.assert_called_once() + devices.lsamy.obj.stop.assert_called_once() + assert mock.call("J1") not in socket_put.mock_calls diff --git a/tests/tests_scans/test_lamni_fermat_scan.py b/tests/tests_scans/test_lamni_fermat_scan.py index cf4fd4c0..808b4e38 100644 --- a/tests/tests_scans/test_lamni_fermat_scan.py +++ b/tests/tests_scans/test_lamni_fermat_scan.py @@ -120,3 +120,51 @@ def test_ddg1_armed_in_pre_scan_and_reset_after_scan(): scan.dev.ddg1.set_trigger.reset_mock() LamniFermatScan.on_exception(scan, RuntimeError("boom")) scan.dev.ddg1.set_trigger.assert_called_once_with(TRIGGERSOURCE.SINGLE_SHOT.value) + + +# ── trigger source of the LaMNI loop (soft trigger away from the beamline, 2026-11-19) ────────────────────────── + + +def _trigger_stub(ddg1_class, api_result=None, api_exc=None): + """A stand-in for a LamniFermatScan with the attributes at_beamline() / set_trigger_source() touch.""" + scan = mock.MagicMock() + devices = {} + if ddg1_class is not None: + ddg1 = mock.MagicMock() + ddg1._config = {"deviceClass": ddg1_class} + devices["ddg1"] = ddg1 + scan.device_manager.devices = devices + scan.exp_time = 0.05 + scan.frames_per_trigger = 2 + if api_exc is not None: + scan.dev.lamni_loop_settings.api_post.side_effect = api_exc + else: + scan.dev.lamni_loop_settings.api_post.return_value = api_result if api_result is not None else {"ok": True} + scan.at_beamline = lambda: LamniFermatScan.at_beamline(scan) + return scan + + +def test_trigger_source_hardware_at_the_beamline(): + scan = _trigger_stub("csaxs_bec.devices.epics.delay_generator_csaxs.DDG1") + LamniFermatScan.set_trigger_source(scan) + path, body = scan.dev.lamni_loop_settings.api_post.call_args.args + assert path == "/api/settings/apply" and body["changes"] == {"trigger_soft": 0} + + +def test_trigger_source_soft_without_beamline_uses_the_exposure(): + scan = _trigger_stub("ophyd_devices.sim.sim_ddg.SimulatedDDG") + LamniFermatScan.set_trigger_source(scan) + _, body = scan.dev.lamni_loop_settings.api_post.call_args.args + assert body["changes"] == {"trigger_soft": 1, "soft_exposure_ms": 100.0} # 0.05 s x 2 frames + + +def test_trigger_source_failure_aborts_only_at_the_beamline(): + import pytest + from bec_server.scan_server.errors import ScanAbortion + + scan = _trigger_stub("csaxs_bec.devices.epics.delay_generator_csaxs.DDG1", api_exc=RuntimeError("web HMI down")) + with pytest.raises(ScanAbortion, match="hardware trigger must be confirmed"): + LamniFermatScan.set_trigger_source(scan) + scan = _trigger_stub(None, api_result={"ok": False, "errors": ["a scan is running"]}) + LamniFermatScan.set_trigger_source(scan) # soft trigger: warning only + scan.device_manager.connector.raise_alarm.assert_called_once()