diff --git a/pyproject.toml b/pyproject.toml index f4846991f..18757f8d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ classifiers = [ ] description = "Lightweight bluesky-as-a-service wrapper application. Also usable as a library." dependencies = [ - "bluesky[plotting]>=1.14.0", # plotting includes matplotlib, required for BestEffortCallback in run plans + "bluesky[plotting]>=1.16.0", # plotting includes matplotlib, required for BestEffortCallback in run plans "ophyd-async>=0.13.5", "pydantic>=2.0", "pydantic-settings", @@ -20,8 +20,8 @@ dependencies = [ "PyYAML>=6.0.2", "click>=8.2.0", "requests", - "GitPython>=3.1.58", #security base min https://github.com/advisories/GHSA-4gmw-gg2m-w46p - used by the server's /python_environment endpoint and the CLI's scratch setup - "event-model==1.24.0", # https://github.com/DiamondLightSource/blueapi/issues/684 + "GitPython>=3.1.58", #security base min https://github.com/advisories/GHSA-4gmw-gg2m-w46p - used by the server's /python_environment endpoint and the CLI's scratch setup + "event-model==1.24.0", # https://github.com/DiamondLightSource/blueapi/issues/684 "bluesky-stomp>=0.1.6", "opentelemetry-distro>=0.48b0", "observability-utils>=0.1.4", @@ -29,6 +29,7 @@ dependencies = [ "websockets", "tqdm", "packaging", + "bluesky-tiled-plugins>=2.0.11", ] dynamic = ["version"] license.file = "LICENSE" @@ -60,7 +61,7 @@ dev = [ "prek", "pydata-sphinx-theme>=0.15.4", "pytest", - "pyright!=1.1.407", # https://github.com/bluesky/scanspec/issues/190 + "pyright!=1.1.407", # https://github.com/bluesky/scanspec/issues/190 "pytest-cov", "pytest-asyncio", "pytest-httpx>=0.35.0", diff --git a/src/blueapi/core/bluesky_types.py b/src/blueapi/core/bluesky_types.py index 674c28e2a..ba32aa23a 100644 --- a/src/blueapi/core/bluesky_types.py +++ b/src/blueapi/core/bluesky_types.py @@ -1,6 +1,6 @@ import inspect from collections.abc import Callable, Generator, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import ( Any, Protocol, @@ -136,10 +136,13 @@ def watch(self, __func: Callable) -> None: @dataclass class BlueapiDevice: """Wrapper around Device held in the context. - Also contains find_component function to look up child devices. - At the moment this just holds the Device but will later hold child device trees""" + Also hold child device tree which is a nested dictionary and find_component + function to look up child devices.""" + name: str device: Device + parent: "BlueapiDevice | None" = field(default=None, repr=False, compare=False) + children: dict[str, "BlueapiDevice"] = field(default_factory=dict) def find_component(self, addr: list[str]) -> Device | None: dev = self.device diff --git a/src/blueapi/core/context.py b/src/blueapi/core/context.py index e4ec6331c..dd088b486 100644 --- a/src/blueapi/core/context.py +++ b/src/blueapi/core/context.py @@ -1,5 +1,6 @@ import logging import sys +from collections import deque from collections.abc import Callable from dataclasses import InitVar, dataclass, field, fields, is_dataclass from importlib import import_module, metadata @@ -193,7 +194,7 @@ def find_device(self, addr: str | list[str]) -> Device | None: def with_config(self, config: EnvironmentConfig) -> None: if config.metadata is not None: - self.run_engine.md |= config.metadata.model_dump() + self.run_engine.md.update(config.metadata.model_dump()) package_map = metadata.packages_distributions() packages = {src.module.split(".")[0] for src in config.sources} @@ -221,6 +222,7 @@ def with_config(self, config: EnvironmentConfig) -> None: f"{name} in module {mod} is not a device manager" ) self.with_device_manager(manager, mock) + if not self.devices: LOGGER.warning( "Context had no devices after loading environment - are all modules " @@ -265,8 +267,15 @@ def with_device_manager(self, manager: DeviceManager, mock: bool = False): fixtures = {"path_provider": self.path_provider} if self.path_provider else {} build_result = manager.build_and_connect(mock=mock, fixtures=fixtures) - for device in build_result.devices.values(): - self.register_device(device) + registered_devices = [] + for name, device in build_result.devices.items(): + name = getattr(device, "name", name) + self.register_device( + device, name, include_children=False + ) # include_children=False so only register top-level devices not children + registered_devices.append(name) + + self._register_children(*(self.devices[name] for name in registered_devices)) if errs := build_result.build_errors: LOGGER.warning( @@ -325,7 +334,9 @@ def my_plan(a: int, b: str): ) return plan - def register_device(self, device: Device, name: str | None = None) -> None: + def register_device( + self, device: Device, name: str | None = None, include_children: bool = True + ) -> None: """ Register an device in the context. The device needs to be registered with a name. If the device is Readable, Movable or Flyable it has a `name` @@ -333,19 +344,21 @@ def register_device(self, device: Device, name: str | None = None) -> None: `name` parameter here. If the device conforms to a different protocol then the parameter must be used to name it. - Children of ophyd-async devices, including signals, are also registered - under their own names, e.g. registering "stage" also registers "stage-x" - and "stage-x-velocity". If a name is already in use, the existing device - is kept and the new one and its children are not registered. + The include_children flag has been set to True so child devices are also + registered. This function will therefore register for example the top-level + device 'stage' and its children 'stage-x' 'stage-x-velocity'. If a name is + already in use, the existing device is kept and the new one and its children + are not registered. Args: device (Device): The device to register name (Optional[str], optional): A name for the device. Defaults to None. + include_children: Flag to decide if child devices should be registered Raises: KeyError: If no name is found/supplied + ValueError: If the device specified has already been registered. """ - if not is_bluesky_compatible_device(device): raise TypeError(f"{device} is not a Bluesky compatible device") @@ -355,24 +368,31 @@ def register_device(self, device: Device, name: str | None = None) -> None: else: raise KeyError(f"Must supply a name for this device: {device}") - if self._add_device(name, device): - self._register_children(device) - - def _register_children(self, device: Device) -> None: - """Register the children of an ophyd-async device under their own names.""" - - if not isinstance(device, AsyncDevice): - return - - for _, child in device.children(): - if child.name and self._add_device(child.name, child): - self._register_children(child) - - def _add_device(self, name: str, device: Device) -> bool: + if added_device := self._add_device(name, device): + if include_children: + self._register_children(added_device) + else: + raise ValueError(f"Device name already registered: {name}") + + def _register_children(self, *devices: BlueapiDevice) -> None: + """Register the children of every top-level device, + once they are all registered.""" + buffer = deque(devices) + while buffer: + parent = buffer.popleft() + if not isinstance(parent.device, AsyncDevice): + continue + for attr, device in parent.device.children(): + if device.name and (child := self._add_device(device.name, device)): + child.parent = parent + parent.children[attr] = child + buffer.append(child) + + def _add_device(self, name: str, device: Device) -> BlueapiDevice | None: """Add a device unless a different one is already registered as name.""" - existing = self.devices.setdefault(name, BlueapiDevice(device)) - if existing.device is not device: + wrapped = self.devices.setdefault(name, BlueapiDevice(name, device)) + if wrapped.device is not device: # Expected for e.g. a motor's user_readback, which has the motor's name. # The caller skips its children too, as their names start with this one if not self._warned_name_clash: @@ -386,8 +406,8 @@ def _add_device(self, name: str, device: Device) -> bool: device, name, ) - return False - return True + return None + return wrapped def unregister_all_devices(self): """Unregister all devices from the context.""" diff --git a/src/blueapi/service/interface.py b/src/blueapi/service/interface.py index be6267886..f347ec6d2 100644 --- a/src/blueapi/service/interface.py +++ b/src/blueapi/service/interface.py @@ -7,6 +7,7 @@ from typing import Any from bluesky.callbacks.tiled_writer import TiledWriter +from bluesky.run_engine import RunEngineMetadata from bluesky_stomp.messaging import StompClient from bluesky_stomp.models import Broker, DestinationBase, MessageTopic from fastapi import status @@ -63,7 +64,7 @@ def context() -> BlueskyContext: ctx = BlueskyContext(config()) if (nt_conf := config().numtracker) is not None and (nt := numtracker()): - async def _update_scan_num(md: dict[str, Any]) -> int: + async def _update_scan_num(md: RunEngineMetadata) -> int: scan = await nt.create_scan(md["instrument_session"], md["instrument"]) md["data_session_directory"] = str(scan.scan.directory.path) md["detector_file_template"] = nt_conf.detector_file_template diff --git a/tests/unit_tests/core/test_context.py b/tests/unit_tests/core/test_context.py index 79c26678c..0539dfb3a 100644 --- a/tests/unit_tests/core/test_context.py +++ b/tests/unit_tests/core/test_context.py @@ -321,7 +321,7 @@ def __init__(self, name: str = "") -> None: super().__init__(name=name) -def test_register_device_registers_children_recursively( +def test_register_children_registers_children_recursively( empty_context: BlueskyContext, ): table = Table(name="table") @@ -372,7 +372,9 @@ def __init__(self, name: str = "") -> None: super().__init__(name=name) -def test_device_vector_children_are_registered(empty_context: BlueskyContext): +def test_device_vector_children_are_registered( + empty_context: BlueskyContext, +): bank = AxisBank(name="bank") empty_context.register_device(bank) @@ -418,10 +420,13 @@ def test_top_level_name_collision_keeps_existing_device_and_logs( caplog.set_level(logging.DEBUG) motor = SimMotor(name="stage-x") - empty_context.register_device(motor) + with pytest.raises(ValueError, match="Device name already registered: stage-x"): + empty_context.register_device(motor) assert empty_context.devices["stage-x"].device is stage.x - assert motor.velocity not in empty_context.devices.values() + assert not any( + wrapped.device is motor.velocity for wrapped in empty_context.devices.values() + ) assert any("stage-x" in record.message for record in caplog.get_records("call")) @@ -446,6 +451,55 @@ def test_register_device_skips_unnamed_children(empty_context: BlueskyContext): assert empty_context.devices.keys() == {"stage"} +def test_register_device_does_register_children(empty_context: BlueskyContext): + stage = Stage(name="stage") + empty_context.register_device(stage) + assert empty_context.devices.keys() == { + "stage", + "stage-x", + "stage-theta", + "stage-x-motor_egu", + "stage-x-motor_resolution", + "stage-x-steps_per_revolution", + "stage-x-units_per_revolution", + "stage-x-encoder_resolution", + "stage-x-velocity", + "stage-x-offset", + "stage-x-user_setpoint", + "stage-x-max_velocity", + "stage-x-acceleration_time", + "stage-x-precision", + "stage-x-deadband", + "stage-x-motor_done_move", + "stage-x-low_limit_travel", + "stage-x-high_limit_travel", + "stage-x-dial_low_limit_travel", + "stage-x-dial_high_limit_travel", + "stage-x-offset_freeze_switch", + "stage-x-high_limit_switch", + "stage-x-low_limit_switch", + "stage-x-output_link", + "stage-x-set_use_switch", + "stage-x-motor_stop", + "stage-theta-motor_egu", + } + + +def test_register_device_only_registers_top_level_device(empty_context: BlueskyContext): + stage = Stage(name="stage") + motor = SimMotor(name="motor") + empty_context.register_device(stage, include_children=False) + empty_context.register_device(motor, include_children=False) + assert empty_context.devices.keys() == { + "stage", + "motor", + } + + +# def_tree_structure +# def test top level devices get registsered first + + def test_child_device_usable_as_plan_argument(empty_context: BlueskyContext): stage = Stage(name="stage") empty_context.register_device(stage) @@ -660,7 +714,7 @@ class ConcreteStoppable(Stoppable): def name(self) -> str: return "Concrete" - def stop(self, success: bool = True): + def stop(self, *, success: bool = True): pass @@ -894,7 +948,7 @@ def test_single_device_manager(empty_context: BlueskyContext): sdm = StaticDeviceManager(devices={"foo": foo}) empty_context.with_device_manager(sdm) - assert empty_context.devices == {"foo": BlueapiDevice(foo)} + assert empty_context.devices == {"foo": BlueapiDevice("foo", foo)} def test_device_manager_build_error(empty_context: BlueskyContext): @@ -964,7 +1018,7 @@ def test_device_manager_environment_source(empty_context: BlueskyContext): with patch("blueapi.core.context.import_module") as imp_mod: imp_mod.side_effect = lambda mod: dev_mod if mod == "foo.bar" else None empty_context.with_config(env) - assert empty_context.devices == {"foo": BlueapiDevice(foo)} + assert empty_context.devices == {"foo": BlueapiDevice("foo", foo)} def test_non_device_manager_errors(empty_context: BlueskyContext): diff --git a/tests/unit_tests/service/test_interface.py b/tests/unit_tests/service/test_interface.py index f00adff69..e88024185 100644 --- a/tests/unit_tests/service/test_interface.py +++ b/tests/unit_tests/service/test_interface.py @@ -146,7 +146,7 @@ def test_get_plan(context_mock: MagicMock): class MyDevice(Stoppable): name: str - def stop(self, success: bool = True) -> None: + def stop(self, *, success: bool = True) -> None: pass diff --git a/tests/unit_tests/service/test_rest_api.py b/tests/unit_tests/service/test_rest_api.py index 278d3864d..7c305bbe4 100644 --- a/tests/unit_tests/service/test_rest_api.py +++ b/tests/unit_tests/service/test_rest_api.py @@ -157,7 +157,7 @@ def pytest_generate_tests(metafunc: pytest.Metafunc): class MinimalDevice(Stoppable): name: str - def stop(self, success: bool = True): + def stop(self, *, success: bool = True): pass diff --git a/uv.lock b/uv.lock index b023f2f7e..ec1e84a40 100644 --- a/uv.lock +++ b/uv.lock @@ -403,6 +403,7 @@ source = { editable = "." } dependencies = [ { name = "bluesky", extra = ["plotting"] }, { name = "bluesky-stomp" }, + { name = "bluesky-tiled-plugins" }, { name = "click" }, { name = "event-model" }, { name = "gitpython" }, @@ -483,8 +484,9 @@ dev = [ requires-dist = [ { name = "aioca", marker = "extra == 'server'" }, { name = "aiohttp", marker = "extra == 'server'", specifier = ">=3.13.5" }, - { name = "bluesky", extras = ["plotting"], specifier = ">=1.14.0" }, + { name = "bluesky", extras = ["plotting"], specifier = ">=1.16.0" }, { name = "bluesky-stomp", specifier = ">=0.1.6" }, + { name = "bluesky-tiled-plugins", specifier = ">=2.0.11" }, { name = "click", specifier = ">=8.2.0" }, { name = "dls-dodal", marker = "extra == 'demo'", specifier = ">=3.0.2" }, { name = "event-model", specifier = "==1.24.0" }, @@ -556,7 +558,7 @@ dev = [ [[package]] name = "bluesky" -version = "1.15.1" +version = "1.16.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cycler" }, @@ -570,9 +572,9 @@ dependencies = [ { name = "tqdm" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e4/83/2e5d1956a1c4cd3d4f0bb34605cc2b11f2ce33e48249773292b27e6bba88/bluesky-1.15.1.tar.gz", hash = "sha256:956e161a8f34f698af28edcd501db118fa793a6c43241001e30ed8c6aaabd95c", size = 513978, upload-time = "2026-05-06T14:06:40.116Z" } +sdist = { url = "https://files.pythonhosted.org/packages/24/fb/9d72f62bb19fa10fad013a6039e51162ebaac84713a06a167083c4b68775/bluesky-1.16.0.tar.gz", hash = "sha256:e89884e5eb4e4e502d4f1e929f6862ed6827ad48272a928583bf67d2f1745261", size = 516370, upload-time = "2026-10-29T17:13:07.145Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8e/99/cc217b2a727fdf730d0c0064bc8c03473dfe5d0528f2bd0c4f59fdab4179/bluesky-1.15.1-py3-none-any.whl", hash = "sha256:7b3a0f04cf2bb0a7907771e014e59fe6fced777347df8df84adec7239f6c3d2a", size = 372701, upload-time = "2026-05-06T14:06:38.618Z" }, + { url = "https://files.pythonhosted.org/packages/da/ca/ad113309c25d01d2166a0ed17fcdcfa453dbf267147d9e9530928dda82a6/bluesky-1.16.0-py3-none-any.whl", hash = "sha256:674b6547bcab7f4dcaf5d403ce2225d52711cbfa363853ce5e2cf5119b802d60", size = 369254, upload-time = "2026-10-29T17:13:05.466Z" }, ] [package.optional-dependencies] @@ -596,6 +598,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/39/4d/d3069d2e0675ad5037c583b8819e5df6fa07ac1814930ed18644191fa232/bluesky_stomp-0.2.0-py3-none-any.whl", hash = "sha256:b6c01504839717c2953b9efdc714f63db3cd1f2e0b2d0221f0b4f51415d7a0f2", size = 19255, upload-time = "2025-10-14T13:15:56.524Z" }, ] +[[package]] +name = "bluesky-tiled-plugins" +version = "2.0.11" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dask" }, + { name = "event-model" }, + { name = "mongoquery" }, + { name = "pytz" }, + { name = "tiled", extra = ["client"] }, + { name = "tzlocal" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d3/74/09a8e31991eeb72d369142a7e02f8947ba182321e70b1cf9f8ca0de4289a/bluesky_tiled_plugins-2.0.11.tar.gz", hash = "sha256:1a9acac4c40fa9d2740a1f1cdf63a98cc598a6208267a71b9ab428927403d24d", size = 105156, upload-time = "2026-09-09T17:09:09.003Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1f/12/3c5928bd530b339f73e670ec41a80dcfe76b3d531b3a3cbe74e18e9de1ba/bluesky_tiled_plugins-2.0.11-py3-none-any.whl", hash = "sha256:a40f850e7ae7bec8a28b99e3bf260f6e9bedae04c109285bcd10b6acb579af4a", size = 65758, upload-time = "2026-09-09T17:09:07.746Z" }, +] + [[package]] name = "cachebox" version = "5.2.3" @@ -2700,6 +2719,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/bd/d9/617e6af809bf3a1d468e0d58c3997b1dc219a9a9202e650d30c2fc85d481/mock-5.2.0-py3-none-any.whl", hash = "sha256:7ba87f72ca0e915175596069dbbcc7c75af7b5e9b9bc107ad6349ede0819982f", size = 31617, upload-time = "2025-03-03T12:31:41.518Z" }, ] +[[package]] +name = "mongoquery" +version = "1.4.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/ec/8e0ddb347c6c5b94e0147b2b9ea1fd9dbfda5d222d0e529996445c30faaa/mongoquery-1.4.3.tar.gz", hash = "sha256:e901f86ee5af7ef6eda2f2c26f4bd2cfe8380d81f178b7e3607dbbcdcee97239", size = 8199, upload-time = "2025-09-16T10:56:06.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ce/33/7ce3f09d91a0ca5db7cca67671d865b7c8310b8b59eff287a711919641f0/mongoquery-1.4.3-py3-none-any.whl", hash = "sha256:8be47635c5e361c9f363b7a901a2b86649687491b7aaca2d12601eff41cb6128", size = 6421, upload-time = "2025-09-16T10:56:05.412Z" }, +] + [[package]] name = "msgpack" version = "1.2.4" @@ -4341,6 +4372,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" }, ] +[[package]] +name = "pytz" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/b0/168030b0bfcc334cf09fa3313afdb888d892c8a0027324683d1de0ec277e/pytz-2026.6.tar.gz", hash = "sha256:3b0fc2727707663d6e517936f444fd8a8b240f1fc32f4bf7ee03274245945284", size = 318520, upload-time = "2026-10-29T09:05:47.011Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/25/564f3fc5b70c1398d706c51f2b1470d0ea0b1b2f96fee67877b6f5bdf3b6/pytz-2026.6-py2.py3-none-any.whl", hash = "sha256:7fed3fee8fd6bd4a2b7b75a8d56021d0624127bf69bd5691f115db929ac570b3", size = 506321, upload-time = "2026-10-29T09:05:45.14Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -5343,6 +5383,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/94/21/1e5995a1c920cce14e4bffae20c665ec10e7ed03ab25e006cd741092b718/tzdata-2026.5-py2.py3-none-any.whl", hash = "sha256:b683bd1b6659ddcd810ff02ad09ba821d4bf1065072805063eb35c49617905ac", size = 347996, upload-time = "2026-10-03T09:23:12.535Z" }, ] +[[package]] +name = "tzlocal" +version = "5.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d8/89/2bd035df331499589fc92e59375c17c6cea6a500453b2c5f6a6ec9572825/tzlocal-5.4.5.tar.gz", hash = "sha256:ba976898bad27945178c9ca25c222c19e322b30c10342b9f40b46714f70d2d5f", size = 31483, upload-time = "2026-10-22T09:09:26.38Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/c1/9be4e1a8a30db8729a86628073910e56f85aaf8a659e053f376a2e6ea5a8/tzlocal-5.4.5-py3-none-any.whl", hash = "sha256:ecab534f6d65d9deb4c4ea52c121ab6dd5958e9b878e71dcb102578269752454", size = 18215, upload-time = "2026-10-22T09:09:24.447Z" }, +] + [[package]] name = "urllib3" version = "2.8.0"