Changes for AareBec (#29)
CI for pxii_bec / test (push) Successful in 1m11s

Re-export necessary components for mx_bec

Co-authored-by: David Perl <david.perl@psi.ch>
This commit was merged in pull request #29.
This commit is contained in:
perl_d authored and perl_d committed 2026-11-24 14:49:03 +01:00
1 parent df82ebc0d2
commit 7dcba666a2
31 files changed
+808 -618

No files matched your search

+32 -2
View File
@@ -24,6 +24,11 @@ on:
required: false
type: string
default: "main"
MX_BEC_REPO_BRANCH:
description: "Branch of the mx_bec core repo to install"
required: false
type: string
default: "main"
PYTHON_VERSION:
description: "Python version to use"
required: false
@@ -46,6 +51,29 @@ jobs:
with:
python-version: "${{ inputs.PYTHON_VERSION || '3.12' }}"
# Use the same-named branch of mx_bec if it exists (e.g. a feature developed in both repos), otherwise main.
- name: Resolve mx_bec branch
id: mx_bec
shell: bash
run: |
ref="${{ inputs.MX_BEC_REPO_BRANCH || github.head_ref || github.ref_name }}"
auth="$(printf 'x-access-token:%s' '${{ github.token }}' | base64 -w0)"
if git -c "http.extraheader=Authorization: Basic ${auth}" ls-remote --exit-code --heads \
"${{ github.server_url }}/bec/mx_bec.git" "refs/heads/${ref}" >/dev/null; then
echo "Using mx_bec branch '${ref}'"
else
echo "mx_bec has no branch '${ref}', using main"
ref=main
fi
echo "ref=${ref}" >> "$GITHUB_OUTPUT"
- name: Checkout MX BEC Repository
uses: actions/checkout@v4
with:
repository: bec/mx_bec
ref: "${{ steps.mx_bec.outputs.ref }}"
path: ./mx_bec
- name: Checkout BEC Plugin Repository
uses: actions/checkout@v4
with:
@@ -94,8 +122,10 @@ jobs:
uv pip install --system -e ./bec/bec_lib[dev]
uv pip install --system -e ./bec/bec_ipython_client
uv pip install --system -e ./bec/bec_server[dev]
uv pip install --system -e ./bec_widgets[dev,pyside6]
uv pip install --system -e ./pxii_bec[dev]
uv pip install --system -e ./bec_widgets[dev]
# MX-internal dependencies (aarecommon, aare_config, jfjoch_client, ...) come from gitea
uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec[dev]
uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./pxii_bec[dev]
- name: Run Tests with Coverage
id: coverage
+5
View File
@@ -0,0 +1,5 @@
from mx_bec.bec_widgets.widgets.aare_bec.actors_config import MxActorConfigWidget
from mx_bec.bec_widgets.widgets.aare_bec.task_panel import MxTaskPanel
from mx_bec.bec_widgets.widgets.aare_bec.task_queue import MxTaskQueueWidget
__all__ = ["MxActorConfigWidget", "MxTaskPanel", "MxTaskQueueWidget"]
+79
View File
@@ -13,10 +13,89 @@ logger = bec_logger.logger
_Widgets = {
"PxIIActorConfigWiget": "PxIIActorConfigWiget",
"PxIISampleQueueWidget": "PxIISampleQueueWidget",
"PxIISpreadsheetDisplay": "PxIISpreadsheetDisplay",
"PxIITaskPanel": "PxIITaskPanel",
"PxIITaskQueueWidget": "PxIITaskQueueWidget",
"ScanHistory": "ScanHistory",
}
class PxIIActorConfigWiget(RPCBase):
_IMPORT_MODULE = "pxii_bec.bec_widgets.widgets.imported"
@rpc_call
def refresh(self):
"""
Reset the layout for currently loaded actors
"""
class PxIISampleQueueWidget(RPCBase):
_IMPORT_MODULE = "pxii_bec.bec_widgets.widgets.imported"
@rpc_call
def refresh(self):
"""
Reload the queued samples from Redis.
"""
@rpc_call
def clear_queue(self):
"""
Delete the queue contents
"""
class PxIISpreadsheetDisplay(RPCBase):
_IMPORT_MODULE = "pxii_bec.bec_widgets.widgets.imported"
@rpc_call
def remove(self):
"""
Cleanup the BECConnector
"""
@rpc_call
def attach(self):
"""
None
"""
@rpc_call
def detach(self):
"""
Detach the widget from its parent dock widget (if widget is in the dock), making it a floating widget.
"""
class PxIITaskPanel(RPCBase):
_IMPORT_MODULE = "pxii_bec.bec_widgets.widgets.imported"
@rpc_call
def request_task(self, name: "str", *args, **kwargs):
"""
Submit a task request to the AareBec service.
"""
class PxIITaskQueueWidget(RPCBase):
_IMPORT_MODULE = "pxii_bec.bec_widgets.widgets.imported"
@rpc_call
def refresh(self):
"""
Reload the queued tasks from Redis.
"""
@rpc_call
def clear_queue(self):
"""
Delete the queue contents
"""
class ScanHistory(RPCBase):
_IMPORT_MODULE = "pxii_bec.bec_widgets.widgets.scan_history.scan_history"
@@ -5,9 +5,19 @@ from __future__ import annotations
# pylint: skip-file
designer_plugins = {
"PxIIActorConfigWiget": ("pxii_bec.bec_widgets.widgets.imported", "PxIIActorConfigWiget"),
"PxIISampleQueueWidget": ("pxii_bec.bec_widgets.widgets.imported", "PxIISampleQueueWidget"),
"PxIISpreadsheetDisplay": ("pxii_bec.bec_widgets.widgets.imported", "PxIISpreadsheetDisplay"),
"PxIITaskPanel": ("pxii_bec.bec_widgets.widgets.imported", "PxIITaskPanel"),
"PxIITaskQueueWidget": ("pxii_bec.bec_widgets.widgets.imported", "PxIITaskQueueWidget"),
"ScanHistory": ("pxii_bec.bec_widgets.widgets.scan_history.scan_history", "ScanHistory"),
}
widget_icons = {
"PxIIActorConfigWiget": "format_list_bulleted",
"PxIISampleQueueWidget": "pending_actions",
"PxIISpreadsheetDisplay": "format_list_bulleted",
"PxIITaskPanel": "play_arrow",
"PxIITaskQueueWidget": "pending_actions",
"ScanHistory": "widgets",
}
+22
View File
@@ -0,0 +1,22 @@
from mx_bec.bec_widgets.widgets.aare_bec import (
MxActorConfigWidget,
MxTaskPanel,
MxTaskQueueWidget,
SampleQueueWidget,
SampleSpreadsheetDisplay,
)
class PxIIActorConfigWiget(MxActorConfigWidget): ...
class PxIITaskQueueWidget(MxTaskQueueWidget): ...
class PxIISampleQueueWidget(SampleQueueWidget): ...
class PxIITaskPanel(MxTaskPanel): ...
class PxIISpreadsheetDisplay(SampleSpreadsheetDisplay): ...
@@ -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 pxii_bec.bec_widgets.widgets.imported import PxIIActorConfigWiget
DOM_XML = """
<ui language='c++'>
<widget class='PxIIActorConfigWiget' name='px_ii_actor_config_wiget'>
</widget>
</ui>
"""
class PxIIActorConfigWigetPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
def __init__(self):
super().__init__()
self._form_editor = None
def createWidget(self, parent):
if parent is None:
return QWidget()
t = PxIIActorConfigWiget(parent)
return t
def domXml(self):
return DOM_XML
def group(self):
return ""
def icon(self):
return designer_material_icon(PxIIActorConfigWiget.ICON_NAME)
def includeFile(self):
return "px_ii_actor_config_wiget"
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 "PxIIActorConfigWiget"
def toolTip(self):
return "PxIIActorConfigWiget"
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 pxii_bec.bec_widgets.widgets.imported import PxIISampleQueueWidget
DOM_XML = """
<ui language='c++'>
<widget class='PxIISampleQueueWidget' name='px_ii_sample_queue_widget'>
</widget>
</ui>
"""
class PxIISampleQueueWidgetPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
def __init__(self):
super().__init__()
self._form_editor = None
def createWidget(self, parent):
if parent is None:
return QWidget()
t = PxIISampleQueueWidget(parent)
return t
def domXml(self):
return DOM_XML
def group(self):
return ""
def icon(self):
return designer_material_icon(PxIISampleQueueWidget.ICON_NAME)
def includeFile(self):
return "px_ii_sample_queue_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 "PxIISampleQueueWidget"
def toolTip(self):
return "PxIISampleQueueWidget"
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 pxii_bec.bec_widgets.widgets.imported import PxIISpreadsheetDisplay
DOM_XML = """
<ui language='c++'>
<widget class='PxIISpreadsheetDisplay' name='px_ii_spreadsheet_display'>
</widget>
</ui>
"""
class PxIISpreadsheetDisplayPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
def __init__(self):
super().__init__()
self._form_editor = None
def createWidget(self, parent):
if parent is None:
return QWidget()
t = PxIISpreadsheetDisplay(parent)
return t
def domXml(self):
return DOM_XML
def group(self):
return ""
def icon(self):
return designer_material_icon(PxIISpreadsheetDisplay.ICON_NAME)
def includeFile(self):
return "px_ii_spreadsheet_display"
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 "PxIISpreadsheetDisplay"
def toolTip(self):
return "PxIISpreadsheetDisplay"
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 pxii_bec.bec_widgets.widgets.imported import PxIITaskPanel
DOM_XML = """
<ui language='c++'>
<widget class='PxIITaskPanel' name='px_ii_task_panel'>
</widget>
</ui>
"""
class PxIITaskPanelPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
def __init__(self):
super().__init__()
self._form_editor = None
def createWidget(self, parent):
if parent is None:
return QWidget()
t = PxIITaskPanel(parent)
return t
def domXml(self):
return DOM_XML
def group(self):
return ""
def icon(self):
return designer_material_icon(PxIITaskPanel.ICON_NAME)
def includeFile(self):
return "px_ii_task_panel"
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 "PxIITaskPanel"
def toolTip(self):
return "PxIITaskPanel"
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 pxii_bec.bec_widgets.widgets.imported import PxIITaskQueueWidget
DOM_XML = """
<ui language='c++'>
<widget class='PxIITaskQueueWidget' name='px_ii_task_queue_widget'>
</widget>
</ui>
"""
class PxIITaskQueueWidgetPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
def __init__(self):
super().__init__()
self._form_editor = None
def createWidget(self, parent):
if parent is None:
return QWidget()
t = PxIITaskQueueWidget(parent)
return t
def domXml(self):
return DOM_XML
def group(self):
return ""
def icon(self):
return designer_material_icon(PxIITaskQueueWidget.ICON_NAME)
def includeFile(self):
return "px_ii_task_queue_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 "PxIITaskQueueWidget"
def toolTip(self):
return "PxIITaskQueueWidget"
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 pxii_bec.bec_widgets.widgets.px_ii_actor_config_wiget_plugin import PxIIActorConfigWigetPlugin
QPyDesignerCustomWidgetCollection.addCustomWidget(PxIIActorConfigWigetPlugin())
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 pxii_bec.bec_widgets.widgets.px_ii_sample_queue_widget_plugin import PxIISampleQueueWidgetPlugin
QPyDesignerCustomWidgetCollection.addCustomWidget(PxIISampleQueueWidgetPlugin())
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 pxii_bec.bec_widgets.widgets.px_ii_spreadsheet_display_plugin import PxIISpreadsheetDisplayPlugin
QPyDesignerCustomWidgetCollection.addCustomWidget(PxIISpreadsheetDisplayPlugin())
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 pxii_bec.bec_widgets.widgets.px_ii_task_panel_plugin import PxIITaskPanelPlugin
QPyDesignerCustomWidgetCollection.addCustomWidget(PxIITaskPanelPlugin())
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 pxii_bec.bec_widgets.widgets.px_ii_task_queue_widget_plugin import PxIITaskQueueWidgetPlugin
QPyDesignerCustomWidgetCollection.addCustomWidget(PxIITaskQueueWidgetPlugin())
if __name__ == "__main__": # pragma: no cover
main()
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
from mx_bec.devices.aerotech import Aerotech
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
__all__ = ["Aerotech", "SimAerotechStage", "SimGoniometer", "SimSampleChanger", "Smargon"]
-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-x10sa-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)
+18
View File
@@ -0,0 +1,18 @@
"""Message types of the MX plugins, re-exported from mx_bec so that BEC's message decoder can
find them through the `bec.messages` entry point registered by this package."""
from mx_bec.messages import (
MXMeasurementSequenceMessage,
MXQueueChangedMessage,
MXSampleExecutionMessage,
MXTaskExecutionMessage,
OpticalPredictionMessage,
)
__all__ = [
"MXMeasurementSequenceMessage",
"MXTaskExecutionMessage",
"MXSampleExecutionMessage",
"MXQueueChangedMessage",
"OpticalPredictionMessage",
]
+7 -2
View File
@@ -1,10 +1,15 @@
"""Initialise sample environment devices and beamline states."""
import os
import importlib
import os
from dataclasses import dataclass
from pathlib import Path
from pxii_bec.macros.beamline_planner import StateChangePlanner
from pxii_bec.macros.beamline_state_manager import DefineStatesManager
from pxii_bec.macros.dependencies import planner_deps
from pxii_bec.macros.devices_manager import DeviceManager
@dataclass
class Environment:
@@ -39,7 +44,7 @@ class Environment:
if self.beamline not in self.beamline_configs:
raise ValueError(
f"Unknown beamline '{self.beamline}'. " f"Choose from {list(self.beamline_configs)}"
f"Unknown beamline '{self.beamline}'. Choose from {list(self.beamline_configs)}"
)
cfg = self.beamline_configs[self.beamline]
+7 -1
View File
@@ -12,7 +12,7 @@ classifiers = [
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering",
]
dependencies = ["pandas~=2.0", "matplotlib"]
dependencies = ["mx_bec", "pandas~=2.0", "matplotlib"]
[project.optional-dependencies]
dev = [
@@ -59,6 +59,12 @@ plugin_widgets_update = "pxii_bec.bec_widgets.auto_updates"
[project.entry-points."bec.widgets.user_widgets"]
plugin_widgets = "pxii_bec.bec_widgets.widgets"
[project.entry-points."bec.messages"]
plugin_messages = "pxii_bec.messages"
[project.entry-points."bec.bl_states"]
plugin_bl_states = "pxii_bec.states"
[tool.hatch.build.targets.wheel]
include = ["*"]
-110
View File
@@ -1,110 +0,0 @@
"""A mock smargopolo REST interface with mock motoers, for testing devices against"""
import asyncio
import random
import time
from contextlib import asynccontextmanager
from typing import Iterable
import uvicorn
from fastapi import FastAPI, HTTPException, Query, Request
from pydantic import BaseModel
AXES = ["SHX", "SHY", "SHZ", "PHI", "CHI"]
class Motor:
def __init__(self, velocity: float = 1.0):
self.position = 0.0
self.target = 0.0
self.velocity = velocity
self.moving = False
self._last_update = time.monotonic()
def update(self):
now = time.monotonic()
dt = now - self._last_update
self._last_update = now
if not self.moving:
return
jitter_factor = random.random() * 0.05 - 0.025 # +- 2.5% jitter in step
distance = self.target - self.position
direction = 1 if distance > 0 else -1
step = direction * self.velocity * dt
if abs(step) >= abs(distance):
self.position = self.target + (step * jitter_factor)
self.moving = False
else:
self.position += step * (1 + jitter_factor)
motors: dict[str, Motor] = {
"SHX": Motor(velocity=3),
"SHY": Motor(velocity=2.5),
"SHZ": Motor(velocity=2),
"PHI": Motor(velocity=1.0),
"CHI": Motor(velocity=0.7),
}
class MoveRequest(BaseModel):
target: float
@asynccontextmanager
async def lifespan(app: FastAPI):
async def updater():
while True:
for motor in motors.values():
motor.update()
await asyncio.sleep(0.02) # 50 Hz update loop
task = asyncio.create_task(updater())
yield
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
app = FastAPI(lifespan=lifespan)
def validate_axes(axes: Iterable[str] | None) -> list[str]:
if axes is None:
return AXES
for a in axes:
if a not in AXES:
raise HTTPException(status_code=404, detail=f"Unknown axis: {a}")
return list(axes)
@app.get("/readbackSCS")
async def readback_scs(axis: list[str] | None = Query(None)):
selected_axes = validate_axes(axis)
return {ax: motors[ax].position for ax in selected_axes}
@app.put("/targetSCS")
async def target_scs(req: Request):
targets = {ax: float(t) for ax, t in req.query_params.items()}
if targets is None:
return {}
selected_axes = validate_axes(targets.keys())
for a in selected_axes:
motor = motors[a]
motor.update()
motor.target = targets[a]
motor.moving = True
return {"targets": targets, "message": "Move started"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000, reload=False)
+39 -33
View File
@@ -1,58 +1,64 @@
"""Smoke tests of the Aerotech device as re-exported by pxii_bec; the device itself is tested in
mx_bec."""
from copy import copy
from threading import RLock
from unittest.mock import ANY
import pytest
from mx_bec.devices.aerotech import Aerotech as MxAerotech
from pxii_bec.devices import Aerotech
AXES = ("x", "y", "z", "u")
class MockServer:
"""Just enough of the AareScan REST API for reading and moving axes."""
def __init__(self) -> None:
self.lock = RLock()
self.mock_data = {
"x": {"pos": 1.0},
"y": {"pos": 1.0},
"z": {"pos": 1.0},
"u": {"pos": 1.0},
"vel_u_deg_s": {"pos": 1.0},
}
self.mock_data = {axis: {"pos": 1.0} for axis in AXES}
def get(self, endpoint):
with self.lock:
return copy(self.mock_data)
def put(self, params: dict | None = None, body: dict | None = None):
def post(self, params: dict | None = None, body: dict | None = None, endpoint=None):
with self.lock:
assert body is not None
for k, v in body.items():
self.mock_data[k]["pos"] = v
for axis, value in body.items():
if axis in self.mock_data: # the body also carries the velocity parameter
self.mock_data[axis]["pos"] = value
@pytest.fixture
def aerotech():
mock_server = MockServer()
from pxii_bec.devices.aerotech import Aerotech
s = Aerotech(name="aerotech", prefix="http://test-aerotech.psi.ch")
s.controller._rest_get = mock_server.get
s.controller._rest_post = mock_server.put
yield s
s.controller._stop_monitor_readback_event.set()
device = Aerotech(name="aerotech", prefix="http://test-aerotech.psi.ch")
device.controller._rest_get = mock_server.get
device.controller._rest_post = mock_server.post
device.controller.validate = lambda endpoint, body: (True, "")
yield device
device.controller._stop_monitor_readback_event.set()
device.destroy()
class TestAerotech:
def test_aerotech_read(self, aerotech):
aerotech.wait_for_connection()
reading = aerotech.read()
assert dict(reading) == {
"aerotech_x": {"value": 1.0, "timestamp": ANY},
"aerotech_y": {"value": 1.0, "timestamp": ANY},
"aerotech_z": {"value": 1.0, "timestamp": ANY},
"aerotech_u": {"value": 1.0, "timestamp": ANY},
"aerotech_vel_u_deg_s": {"value": 1.0, "timestamp": ANY},
}
def test_is_the_mx_bec_device():
assert Aerotech is MxAerotech
def test_aerotech_set_with_status(self, aerotech):
aerotech.wait_for_connection()
st = aerotech.x.set(5.0)
st.wait(timeout=1)
assert aerotech.x.get() == 5.0
def test_aerotech_read(aerotech):
aerotech.wait_for_connection()
reading = dict(aerotech.read())
# besides the axes, read() reports the valid/message state of the scan parameter groups
assert {k: v for k, v in reading.items() if k.removeprefix("aerotech_") in AXES} == {
f"aerotech_{axis}": {"value": 1.0, "timestamp": ANY} for axis in AXES
}
assert reading["aerotech_gridscan_config_valid"]["value"] is True
def test_aerotech_set_with_status(aerotech):
aerotech.wait_for_connection()
aerotech.x.set(5.0).wait(timeout=1)
assert aerotech.x.get() == 5.0
+33 -24
View File
@@ -1,14 +1,24 @@
"""Smoke tests of the Smargon device as re-exported by pxii_bec; the device itself is tested in
mx_bec against a mock smargopolo server."""
from copy import copy
from threading import RLock
from unittest.mock import ANY
import pytest
from mx_bec.devices.smargopolo_smargon import Smargon as MxSmargon
from pxii_bec.devices import Smargon
AXES = ("SHX", "SHY", "SHZ", "PHI", "CHI")
class MockServer:
"""Just enough of the smargopolo REST API for reading and moving axes."""
def __init__(self) -> None:
self.lock = RLock()
self.mock_data = {"SHX": 1.0, "SHY": 1.0, "SHZ": 1.0, "PHI": 1.0, "CHI": 1.0}
self.mock_data = {axis: 1.0 for axis in AXES}
def get(self, endpoint):
with self.lock:
@@ -23,29 +33,28 @@ class MockServer:
@pytest.fixture
def smargon():
mock_server = MockServer()
from pxii_bec.devices.smargopolo_smargon import Smargon
s = Smargon(name="smargon", prefix="http://test-smargopolo.psi.ch")
s.controller._rest_get = mock_server.get
s.controller._rest_put = mock_server.put
yield s
s.controller._stop_monitor_readback_event.set()
device = Smargon(name="smargon", prefix="http://test-smargopolo.psi.ch")
device.controller._rest_get = mock_server.get
device.controller._rest_put = mock_server.put
yield device
device.controller._stop_monitor_readback_event.set()
device.destroy()
class TestSmargon:
def test_smargon_read(self, smargon):
smargon.wait_for_connection()
reading = smargon.read()
assert dict(reading) == {
"smargon_x": {"value": 1.0, "timestamp": ANY},
"smargon_y": {"value": 1.0, "timestamp": ANY},
"smargon_z": {"value": 1.0, "timestamp": ANY},
"smargon_phi": {"value": 1.0, "timestamp": ANY},
"smargon_chi": {"value": 1.0, "timestamp": ANY},
}
def test_is_the_mx_bec_device():
assert Smargon is MxSmargon
def test_smargon_set_with_status(self, smargon):
smargon.wait_for_connection()
st = smargon.x.set(5.0)
st.wait(timeout=1)
assert smargon.x.get() == 5.0
def test_smargon_read(smargon):
smargon.wait_for_connection()
reading = smargon.read()
assert dict(reading) == {
f"smargon_{axis}": {"value": 1.0, "timestamp": ANY}
for axis in ("x", "y", "z", "phi", "chi")
}
def test_smargon_set_with_status(smargon):
smargon.wait_for_connection()
smargon.x.set(5.0).wait(timeout=1)
assert smargon.x.get() == 5.0