From 1a63842cafdb5e85da634e7e2593cd4ecf8ed438 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 14:49:32 +0100 Subject: [PATCH] re-export new features from mx_bec --- pxiii_bec/bec_widgets/widgets/client.py | 18 ++ .../bec_widgets/widgets/designer_plugins.py | 5 + pxiii_bec/bec_widgets/widgets/imported.py | 4 + ...iii_automation_permission_widget.pyproject | 1 + ...iii_automation_permission_widget_plugin.py | 57 ++++++ ...ter_px_iii_automation_permission_widget.py | 15 ++ .../old/x06da_device_config.yaml | 4 +- pxiii_bec/device_configs/pxiii-devices.yaml | 4 +- .../device_configs/temp/pxiii-devices.yaml | 4 +- pxiii_bec/devices/__init__.py | 2 + pxiii_bec/devices/aerotech.py | 43 ----- pxiii_bec/devices/http.py | 178 ------------------ pxiii_bec/devices/smargopolo_smargon.py | 42 ----- pxiii_bec/messages.py | 6 + 14 files changed, 114 insertions(+), 269 deletions(-) create mode 100644 pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget.pyproject create mode 100644 pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget_plugin.py create mode 100644 pxiii_bec/bec_widgets/widgets/register_px_iii_automation_permission_widget.py delete mode 100644 pxiii_bec/devices/aerotech.py delete mode 100644 pxiii_bec/devices/http.py delete mode 100644 pxiii_bec/devices/smargopolo_smargon.py diff --git a/pxiii_bec/bec_widgets/widgets/client.py b/pxiii_bec/bec_widgets/widgets/client.py index 079f7d3..666d6db 100644 --- a/pxiii_bec/bec_widgets/widgets/client.py +++ b/pxiii_bec/bec_widgets/widgets/client.py @@ -14,6 +14,7 @@ logger = bec_logger.logger _Widgets = { "PxIIIActorConfigWidget": "PxIIIActorConfigWidget", + "PxIIIAutomationPermissionWidget": "PxIIIAutomationPermissionWidget", "PxIIISampleQueueWidget": "PxIIISampleQueueWidget", "PxIIISpreadsheetDisplay": "PxIIISpreadsheetDisplay", "PxIIITaskPanel": "PxIIITaskPanel", @@ -32,6 +33,23 @@ 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 PxIIISampleQueueWidget(RPCBase): _IMPORT_MODULE = "pxiii_bec.bec_widgets.widgets.imported" diff --git a/pxiii_bec/bec_widgets/widgets/designer_plugins.py b/pxiii_bec/bec_widgets/widgets/designer_plugins.py index f3868ee..7b1e2f7 100644 --- a/pxiii_bec/bec_widgets/widgets/designer_plugins.py +++ b/pxiii_bec/bec_widgets/widgets/designer_plugins.py @@ -6,6 +6,10 @@ from __future__ import annotations designer_plugins = { "PxIIIActorConfigWidget": ("pxiii_bec.bec_widgets.widgets.imported", "PxIIIActorConfigWidget"), + "PxIIIAutomationPermissionWidget": ( + "pxiii_bec.bec_widgets.widgets.imported", + "PxIIIAutomationPermissionWidget", + ), "PxIIISampleQueueWidget": ("pxiii_bec.bec_widgets.widgets.imported", "PxIIISampleQueueWidget"), "PxIIISpreadsheetDisplay": ( "pxiii_bec.bec_widgets.widgets.imported", @@ -18,6 +22,7 @@ designer_plugins = { widget_icons = { "PxIIIActorConfigWidget": "format_list_bulleted", + "PxIIIAutomationPermissionWidget": "key", "PxIIISampleQueueWidget": "pending_actions", "PxIIISpreadsheetDisplay": "format_list_bulleted", "PxIIITaskPanel": "play_arrow", diff --git a/pxiii_bec/bec_widgets/widgets/imported.py b/pxiii_bec/bec_widgets/widgets/imported.py index 3a61cd0..aebf76e 100644 --- a/pxiii_bec/bec_widgets/widgets/imported.py +++ b/pxiii_bec/bec_widgets/widgets/imported.py @@ -1,5 +1,6 @@ from mx_bec.bec_widgets.widgets.aare_bec import ( MxActorConfigWidget, + MxAutomationPermissionWidget, MxTaskPanel, MxTaskQueueWidget, SampleQueueWidget, @@ -20,3 +21,6 @@ class PxIIITaskPanel(MxTaskPanel): ... class PxIIISpreadsheetDisplay(SampleSpreadsheetDisplay): ... + + +class PxIIIAutomationPermissionWidget(MxAutomationPermissionWidget): ... diff --git a/pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget.pyproject b/pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget.pyproject new file mode 100644 index 0000000..4cbb48d --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget.pyproject @@ -0,0 +1 @@ +{'files': ['imported.py']} \ No newline at end of file diff --git a/pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget_plugin.py b/pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget_plugin.py new file mode 100644 index 0000000..5a54c37 --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/px_iii_automation_permission_widget_plugin.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 = """ + + + + +""" + + +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() diff --git a/pxiii_bec/bec_widgets/widgets/register_px_iii_automation_permission_widget.py b/pxiii_bec/bec_widgets/widgets/register_px_iii_automation_permission_widget.py new file mode 100644 index 0000000..b3c0c5f --- /dev/null +++ b/pxiii_bec/bec_widgets/widgets/register_px_iii_automation_permission_widget.py @@ -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() diff --git a/pxiii_bec/device_configs/old/x06da_device_config.yaml b/pxiii_bec/device_configs/old/x06da_device_config.yaml index 19cfc62..cc05ec8 100644 --- a/pxiii_bec/device_configs/old/x06da_device_config.yaml +++ b/pxiii_bec/device_configs/old/x06da_device_config.yaml @@ -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 diff --git a/pxiii_bec/device_configs/pxiii-devices.yaml b/pxiii_bec/device_configs/pxiii-devices.yaml index 39d9282..ccf7f8e 100755 --- a/pxiii_bec/device_configs/pxiii-devices.yaml +++ b/pxiii_bec/device_configs/pxiii-devices.yaml @@ -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: diff --git a/pxiii_bec/device_configs/temp/pxiii-devices.yaml b/pxiii_bec/device_configs/temp/pxiii-devices.yaml index 39d9282..ccf7f8e 100644 --- a/pxiii_bec/device_configs/temp/pxiii-devices.yaml +++ b/pxiii_bec/device_configs/temp/pxiii-devices.yaml @@ -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: diff --git a/pxiii_bec/devices/__init__.py b/pxiii_bec/devices/__init__.py index 3909b30..e10590b 100644 --- a/pxiii_bec/devices/__init__.py +++ b/pxiii_bec/devices/__init__.py @@ -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 diff --git a/pxiii_bec/devices/aerotech.py b/pxiii_bec/devices/aerotech.py deleted file mode 100644 index 3189733..0000000 --- a/pxiii_bec/devices/aerotech.py +++ /dev/null @@ -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() diff --git a/pxiii_bec/devices/http.py b/pxiii_bec/devices/http.py deleted file mode 100644 index 38b612a..0000000 --- a/pxiii_bec/devices/http.py +++ /dev/null @@ -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) diff --git a/pxiii_bec/devices/smargopolo_smargon.py b/pxiii_bec/devices/smargopolo_smargon.py deleted file mode 100644 index a7c4618..0000000 --- a/pxiii_bec/devices/smargopolo_smargon.py +++ /dev/null @@ -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) diff --git a/pxiii_bec/messages.py b/pxiii_bec/messages.py index 5cefdde..dfcb5f0 100644 --- a/pxiii_bec/messages.py +++ b/pxiii_bec/messages.py @@ -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",