forwarded auth support and widgets #45

Merged
perl_d merged 2 commits from feat/forwarded_auth into main 2026-12-03 13:58:08 +01:00
17 changed files with 214 additions and 269 deletions

No files matched your search

+36
View File
@@ -14,6 +14,8 @@ logger = bec_logger.logger
_Widgets = {
"PxIIIActorConfigWidget": "PxIIIActorConfigWidget",
"PxIIIAutomationPermissionWidget": "PxIIIAutomationPermissionWidget",
"PxIIICurrentSampleWidget": "PxIIICurrentSampleWidget",
"PxIIISampleQueueWidget": "PxIIISampleQueueWidget",
"PxIIISpreadsheetDisplay": "PxIIISpreadsheetDisplay",
"PxIIITaskPanel": "PxIIITaskPanel",
@@ -32,6 +34,40 @@ class PxIIIActorConfigWidget(RPCBase):
"""
class PxIIIAutomationPermissionWidget(RPCBase):
_IMPORT_MODULE = "pxiii_bec.bec_widgets.widgets.imported"
@rpc_call
def grant_permission(self):
"""
Get a token for the current user from AareDAQ and forward it to the AareBec service.
Returns at once; the outcome is shown in the widget.
"""
@rpc_call
def refresh(self):
"""
Reload the permission status from Redis.
"""
class PxIIICurrentSampleWidget(RPCBase):
_IMPORT_MODULE = "pxiii_bec.bec_widgets.widgets.imported"
@rpc_call
def refresh(self):
"""
Show the sample which was mounted last, as announced by the AareBec service.
"""
@rpc_call
def show_sample(self, sample_id: "int"):
"""
Fetch the record of the sample with this database id from AareDAQ and show it.
Returns at once; the record, or why it could not be fetched, appears in the widget.
"""
class PxIIISampleQueueWidget(RPCBase):
_IMPORT_MODULE = "pxiii_bec.bec_widgets.widgets.imported"
@@ -6,6 +6,14 @@ from __future__ import annotations
designer_plugins = {
"PxIIIActorConfigWidget": ("pxiii_bec.bec_widgets.widgets.imported", "PxIIIActorConfigWidget"),
"PxIIIAutomationPermissionWidget": (
"pxiii_bec.bec_widgets.widgets.imported",
"PxIIIAutomationPermissionWidget",
),
"PxIIICurrentSampleWidget": (
"pxiii_bec.bec_widgets.widgets.imported",
"PxIIICurrentSampleWidget",
),
"PxIIISampleQueueWidget": ("pxiii_bec.bec_widgets.widgets.imported", "PxIIISampleQueueWidget"),
"PxIIISpreadsheetDisplay": (
"pxiii_bec.bec_widgets.widgets.imported",
@@ -18,6 +26,8 @@ designer_plugins = {
widget_icons = {
"PxIIIActorConfigWidget": "format_list_bulleted",
"PxIIIAutomationPermissionWidget": "key",
"PxIIICurrentSampleWidget": "science",
"PxIIISampleQueueWidget": "pending_actions",
"PxIIISpreadsheetDisplay": "format_list_bulleted",
"PxIIITaskPanel": "play_arrow",
@@ -1,5 +1,7 @@
from mx_bec.bec_widgets.widgets.aare_bec import (
MxActorConfigWidget,
MxAutomationPermissionWidget,
MxCurrentSampleWidget,
MxTaskPanel,
MxTaskQueueWidget,
SampleQueueWidget,
@@ -20,3 +22,9 @@ class PxIIITaskPanel(MxTaskPanel): ...
class PxIIISpreadsheetDisplay(SampleSpreadsheetDisplay): ...
class PxIIIAutomationPermissionWidget(MxAutomationPermissionWidget): ...
class PxIIICurrentSampleWidget(MxCurrentSampleWidget): ...
@@ -0,0 +1 @@
{'files': ['imported.py']}
@@ -0,0 +1,57 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from qtpy.QtDesigner import QDesignerCustomWidgetInterface
from qtpy.QtWidgets import QWidget
from bec_widgets.utils.bec_designer import designer_material_icon
from pxiii_bec.bec_widgets.widgets.imported import PxIIIAutomationPermissionWidget
DOM_XML = """
<ui language='c++'>
<widget class='PxIIIAutomationPermissionWidget' name='px_iii_automation_permission_widget'>
</widget>
</ui>
"""
class PxIIIAutomationPermissionWidgetPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
def __init__(self):
super().__init__()
self._form_editor = None
def createWidget(self, parent):
if parent is None:
return QWidget()
t = PxIIIAutomationPermissionWidget(parent)
return t
def domXml(self):
return DOM_XML
def group(self):
return ""
def icon(self):
return designer_material_icon(PxIIIAutomationPermissionWidget.ICON_NAME)
def includeFile(self):
return "px_iii_automation_permission_widget"
def initialize(self, form_editor):
self._form_editor = form_editor
def isContainer(self):
return False
def isInitialized(self):
return self._form_editor is not None
def name(self):
return "PxIIIAutomationPermissionWidget"
def toolTip(self):
return "PxIIIAutomationPermissionWidget"
def whatsThis(self):
return self.toolTip()
@@ -0,0 +1 @@
{'files': ['imported.py']}
@@ -0,0 +1,57 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from qtpy.QtDesigner import QDesignerCustomWidgetInterface
from qtpy.QtWidgets import QWidget
from bec_widgets.utils.bec_designer import designer_material_icon
from pxiii_bec.bec_widgets.widgets.imported import PxIIICurrentSampleWidget
DOM_XML = """
<ui language='c++'>
<widget class='PxIIICurrentSampleWidget' name='px_iii_current_sample_widget'>
</widget>
</ui>
"""
class PxIIICurrentSampleWidgetPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
def __init__(self):
super().__init__()
self._form_editor = None
def createWidget(self, parent):
if parent is None:
return QWidget()
t = PxIIICurrentSampleWidget(parent)
return t
def domXml(self):
return DOM_XML
def group(self):
return ""
def icon(self):
return designer_material_icon(PxIIICurrentSampleWidget.ICON_NAME)
def includeFile(self):
return "px_iii_current_sample_widget"
def initialize(self, form_editor):
self._form_editor = form_editor
def isContainer(self):
return False
def isInitialized(self):
return self._form_editor is not None
def name(self):
return "PxIIICurrentSampleWidget"
def toolTip(self):
return "PxIIICurrentSampleWidget"
def whatsThis(self):
return self.toolTip()
@@ -0,0 +1,15 @@
def main(): # pragma: no cover
from qtpy import PYSIDE6
if not PYSIDE6:
print("PYSIDE6 is not available in the environment. Cannot patch designer.")
return
from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection
from pxiii_bec.bec_widgets.widgets.px_iii_automation_permission_widget_plugin import PxIIIAutomationPermissionWidgetPlugin
QPyDesignerCustomWidgetCollection.addCustomWidget(PxIIIAutomationPermissionWidgetPlugin())
if __name__ == "__main__": # pragma: no cover
main()
@@ -0,0 +1,15 @@
def main(): # pragma: no cover
from qtpy import PYSIDE6
if not PYSIDE6:
print("PYSIDE6 is not available in the environment. Cannot patch designer.")
return
from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection
from pxiii_bec.bec_widgets.widgets.px_iii_current_sample_widget_plugin import PxIIICurrentSampleWidgetPlugin
QPyDesignerCustomWidgetCollection.addCustomWidget(PxIIICurrentSampleWidgetPlugin())
if __name__ == "__main__": # pragma: no cover
main()
@@ -5,7 +5,7 @@ base_config:
smargon:
description: REST-based device which connects to Smargopolo
deviceClass: pxiii_bec.devices.smargopolo_smargon.Smargon
deviceClass: pxiii_bec.devices.Smargon
deviceConfig: {prefix: 'http://x06da-smargopolo.psi.ch:3000'}
onFailure: buffer
enabled: True
@@ -18,7 +18,7 @@ smargon:
aerotech:
description: REST-based device which connects to AareScan and Aerotech
deviceClass: pxiii_bec.devices.aerotech.Aerotech
deviceClass: pxiii_bec.devices.Aerotech
deviceConfig: {prefix: 'http://mx-x06da-queue-01:5234'}
onFailure: buffer
enabled: True
+2 -2
View File
@@ -51,7 +51,7 @@
aerotech:
description: REST-based device which connects to AareScan and Aerotech
deviceClass: pxiii_bec.devices.aerotech.Aerotech
deviceClass: pxiii_bec.devices.Aerotech
deviceConfig:
prefix: http://mx-x06da-queue-01:5234
deviceTags:
@@ -1061,7 +1061,7 @@ sls_current:
readoutPriority: monitored
smargon:
description: REST-based device which connects to Smargopolo
deviceClass: pxiii_bec.devices.smargopolo_smargon.Smargon
deviceClass: pxiii_bec.devices.Smargon
deviceConfig:
prefix: http://x06da-smargopolo.psi.ch:3000
deviceTags:
@@ -51,7 +51,7 @@
aerotech:
description: REST-based device which connects to AareScan and Aerotech
deviceClass: pxiii_bec.devices.aerotech.Aerotech
deviceClass: pxiii_bec.devices.Aerotech
deviceConfig:
prefix: http://mx-x06da-queue-01:5234
deviceTags:
@@ -1061,7 +1061,7 @@ sls_current:
readoutPriority: monitored
smargon:
description: REST-based device which connects to Smargopolo
deviceClass: pxiii_bec.devices.smargopolo_smargon.Smargon
deviceClass: pxiii_bec.devices.Smargon
deviceConfig:
prefix: http://x06da-smargopolo.psi.ch:3000
deviceTags:
+2
View File
@@ -5,10 +5,12 @@ Ophyd devices for the PX III beamline, including the MX specific Aerotech A3200
@author: mohacsi_i
"""
from mx_bec.devices.aerotech import Aerotech
from mx_bec.devices.beam_profile import CentroidBeamProfile, GaussianBeamProfile
from mx_bec.devices.beam_steering import BeamSteerer
from mx_bec.devices.sim_sample_changer import SimSampleChanger
from mx_bec.devices.sim_stages import SimAerotechStage, SimGoniometer
from mx_bec.devices.smargopolo_smargon import Smargon
from .A3200 import AerotechAbrStage
from .A3200utils import A3200Axis
-43
View File
@@ -1,43 +0,0 @@
from ophyd import Component as Cpt
from .http import TIMESTAMP_ID, HttpDeviceController, HttpDeviceSignal, HttpOphydDevice
class AerotechController(HttpDeviceController):
_readback_endpoint = "/status"
_target_endpoint = "/position"
def __init__(self, *, prefix, **kwargs):
self._readbacks: dict[str, dict[str, float | bool]] = {}
super().__init__(prefix=prefix, **kwargs)
def put(self, axis: str, val: float):
self._rest_post(body={axis: val})
def get_readback(self, axis_id: str) -> tuple[float, float] | None:
with self._readback_lock:
if axis_id not in self._readbacks or TIMESTAMP_ID not in self._readbacks:
return None
return self._readbacks.get(axis_id)["pos"], self._readbacks.get(TIMESTAMP_ID) # type: ignore
class Aerotech(HttpOphydDevice):
controller_class = AerotechController
x = Cpt(HttpDeviceSignal, axis_identifier="x", tolerance=0.01)
y = Cpt(HttpDeviceSignal, axis_identifier="y", tolerance=0.01)
z = Cpt(HttpDeviceSignal, axis_identifier="z", tolerance=0.01)
u = Cpt(HttpDeviceSignal, axis_identifier="u", tolerance=0.01)
vel_u_deg_s = Cpt(HttpDeviceSignal, axis_identifier="vel_u_deg_s", tolerance=0.01)
def _test():
a = Aerotech(name="aerotech", prefix="http://mx-x06da-queue-01:5234")
a.wait_for_connection()
return a
if __name__ == "__main__":
aerotech = _test()
print(aerotech.read())
aerotech.stop()
-178
View File
@@ -1,178 +0,0 @@
import time
from abc import ABC, abstractmethod
from threading import Event, RLock, Thread
from typing import Any
from ophyd import OphydObject
from ophyd_devices import PSIDeviceBase
from ophyd_devices.utils.socket import SocketSignal
from requests import Response, Session
TIMESTAMP_ID = "__timestamp"
_POLL_INTERVAL_SLOW = 0.1
class HttpRestError(Exception):
"""Error for rest calls from a HttpRestSignal."""
def __init__(self, resp: Response, *args: object, value: Any | None = None) -> None:
method, url = resp.request.method, resp.request.url
data = f"{str(value)} to " if value is not None else ""
super().__init__(
f"Could not {method} {data}{url}. Code: {resp.status_code}. Reason: {resp.reason}.",
*args,
)
class HttpDeviceController(OphydObject, ABC):
"""Controller to consolidate polling loops and other REST calls for devices which communicate
with HTTP REST interfaces"""
_readback_endpoint: str
_target_endpoint: str
def __init__(self, *, prefix, **kwargs):
self._readbacks: dict
self._session = Session()
self._prefix = prefix
self._targets = {}
self._signal_registry: set[str] = set()
self._readback_poll_interval: float = _POLL_INTERVAL_SLOW
super().__init__(**kwargs)
self._setup_readback()
def _setup_readback(self):
self._stop_monitor_readback_event = Event()
self._readback_lock = RLock()
self._monitor_readback_thread = Thread(
target=self._monitor,
args=[
self._readback_endpoint,
self._stop_monitor_readback_event,
self._readback_lock,
self._readbacks,
],
)
def manual_update(self):
self._update_reading(self._readback_endpoint, self._readback_lock, self._readbacks)
def _update_reading(self, endpoint: str, lock: RLock, buffer: dict):
data = self._rest_get(endpoint)
timestamp = time.monotonic()
with lock:
buffer.update(data)
buffer["__timestamp"] = timestamp
def _monitor(self, endpoint: str, event: Event, lock: RLock, buffer: dict):
while not event.is_set():
self._update_reading(endpoint, lock, buffer)
time.sleep(self._readback_poll_interval)
def _clean_monitor(self):
if self._monitor_readback_thread.is_alive():
self._stop_monitor_readback_event.set()
self._monitor_readback_thread.join(timeout=2)
if self._monitor_readback_thread.is_alive():
raise RuntimeError("Failed to clean up Aerotech monitor thread.")
def register(self, axis_id: str):
self._signal_registry.add(axis_id)
def _rest_get(self, endpoint):
resp = self._session.get(self._prefix + endpoint)
if not resp.ok:
raise HttpRestError(resp)
return resp.json()
def _rest_put(self, params: dict | None = None, body: dict | None = None):
resp = self._session.put(self._prefix + self._target_endpoint, params=params, json=body)
if not resp.ok:
raise HttpRestError(resp, value=params)
def _rest_post(self, params: dict | None = None, body: dict | None = None):
resp = self._session.post(self._prefix + self._target_endpoint, params=params, json=body)
if not resp.ok:
raise HttpRestError(resp, value=params)
def start_monitor(self):
"""Start or restart the automonitor thread."""
self._clean_monitor()
self._setup_readback()
self._monitor_readback_thread.start()
def monitor_stopped(self):
return not self._monitor_readback_thread.is_alive()
def put(self, axis: str, val: float):
self._rest_put({axis: val})
@abstractmethod
def get_readback(self, axis_id: str) -> tuple[float, float] | None:
"""Return a tuple (reading, timestamp) if the axis_id exists"""
def stop(self):
# There doesn't appear to be a stop endpoint on the server
# Best effort: set the target to the current position
pass
# TODO: self._rest_put(self._readbacks)
class HttpDeviceSignal(SocketSignal):
"""Ophyd signal which gets and puts to a REST API rather than EPICS PVs, mediated through the Aerotech
Controller"""
def __init__(self, *args, axis_identifier: str, **kwargs):
super().__init__(*args, **kwargs)
controller: HttpDeviceController | None = getattr(self.root, "controller", None)
if controller is None:
raise TypeError("HttpDeviceSignal must be used in a device with a HttpDeviceController")
self._controller = controller
self._axis_id = axis_identifier
self._controller.register(self._axis_id)
def _socket_get(self): # type: ignore
self._readback, self.metadata["timestamp"] = self._controller.get_readback(
self._axis_id
) or (0.0, 0.0)
return self._readback
def _socket_set(self, val: float):
self._controller.put(self._axis_id, val)
def get(self, **kwargs):
if self._controller.monitor_stopped():
self._controller.start_monitor()
return super().get(**kwargs)
class HttpOphydDevice(PSIDeviceBase):
controller_class: type[HttpDeviceController]
def __init__(
self,
*,
name: str,
prefix: str = "",
scan_info=None,
device_manager=None,
**kwargs,
):
self.controller = self.controller_class(prefix=prefix)
super().__init__(
name=name,
prefix=prefix,
scan_info=scan_info,
device_manager=device_manager,
**kwargs,
)
def wait_for_connection(self, **kwargs): # type: ignore
self.controller.start_monitor()
self.controller.manual_update()
return super().wait_for_connection(**kwargs)
def stop(self, *, success: bool = False) -> None:
self.controller.stop()
return super().stop(success=success)
-42
View File
@@ -1,42 +0,0 @@
from ophyd import Component as Cpt
from ophyd_devices import PSIDeviceBase
from .http import HttpDeviceController, HttpDeviceSignal, HttpOphydDevice
_TIMESTAMP_ID = "__timestamp"
_POLL_INTERVAL_SLOW = 0.1
class SmargonController(HttpDeviceController):
"""Controller to consolidate polling loops and other REST calls for the smargon"""
_readback_endpoint = "/readbackSCS"
_target_endpoint = "/targetSCS"
def __init__(self, *, prefix, **kwargs):
self._readbacks: dict[str, float] = {}
super().__init__(prefix=prefix, **kwargs)
def get_readback(self, axis_id: str) -> tuple[float, float] | None:
with self._readback_lock:
if axis_id not in self._readbacks or _TIMESTAMP_ID not in self._readbacks:
return None
return self._readbacks.get(axis_id), self._readbacks.get(_TIMESTAMP_ID) # type: ignore
def put(self, axis: str, val: float):
self._rest_put(params={axis: val})
def stop(self):
# There doesn't appear to be a stop endpoint on the server
# Best effort: set the target to the current position
self._rest_put(params=self._readbacks)
class Smargon(HttpOphydDevice):
controller_class = SmargonController
x = Cpt(HttpDeviceSignal, axis_identifier="SHX", tolerance=0.01)
y = Cpt(HttpDeviceSignal, axis_identifier="SHY", tolerance=0.01)
z = Cpt(HttpDeviceSignal, axis_identifier="SHZ", tolerance=0.01)
phi = Cpt(HttpDeviceSignal, axis_identifier="PHI", tolerance=0.01)
chi = Cpt(HttpDeviceSignal, axis_identifier="CHI", tolerance=0.01)
+6
View File
@@ -2,6 +2,9 @@
find them through the `bec.messages` entry point registered by this package."""
from mx_bec.messages import (
MXAutomationPermissionMessage,
MXAutomationPermissionStatusMessage,
MXForwardedAuthPublicKeyMessage,
MXMeasurementSequenceMessage,
MXQueueChangedMessage,
MXSampleExecutionMessage,
@@ -10,6 +13,9 @@ from mx_bec.messages import (
)
__all__ = [
"MXAutomationPermissionMessage",
"MXAutomationPermissionStatusMessage",
"MXForwardedAuthPublicKeyMessage",
"MXMeasurementSequenceMessage",
"MXTaskExecutionMessage",
"MXSampleExecutionMessage",