Skip to content

Commit

Permalink
Merge pull request #88 from ISISComputingGroup/global_moving_flag
Browse files Browse the repository at this point in the history
Add option to wait for global moving flag
  • Loading branch information
rerpha authored Dec 2, 2024
2 parents 9e2ea16 + 8f791bc commit e48d253
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 3 deletions.
6 changes: 5 additions & 1 deletion doc/devices/blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,16 @@ from ibex_bluesky_core.devices.block import block_mot
mot_block = block_mot("motor_block")
```

A motor block does not need an explicit write config: it always waits for the requested motion
to complete. See {py:obj}`ibex_bluesky_core.devices.block.BlockMot` for a detailed mapping of
the usual write-configuration options and how these are instead achieved by a motor block.

## Configuring block write behaviour

`BlockRw` and `BlockRwRbv` both take a `write_config` argument, which can be used to configure
the behaviour on writing to a block, for example tolerances and settle times.

See the docstring on `ibex_bluesky_core.devices.block.BlockWriteConfig` for a detailed
See {py:class}`ibex_bluesky_core.devices.block.BlockWriteConfig` for a detailed
description of all the options which are available.

## Run control
Expand Down
39 changes: 38 additions & 1 deletion src/ibex_bluesky_core/devices/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
StandardReadable,
StandardReadableFormat,
observe_value,
wait_for_value,
)
from ophyd_async.epics.core import epics_signal_r, epics_signal_rw
from ophyd_async.epics.motor import Motor
Expand All @@ -39,8 +40,13 @@
"block_rw_rbv",
]

# When using the global moving flag, we want to give IOCs enough time to update the
# global flag before checking it. This is an amount of time always applied before
# looking at the global moving flag.
GLOBAL_MOVING_FLAG_PRE_WAIT = 0.1

@dataclass(kw_only=True)

@dataclass(kw_only=True, frozen=True)
class BlockWriteConfig(Generic[T]):
"""Configuration settings for writing to blocks.
Expand Down Expand Up @@ -77,12 +83,19 @@ def check(setpoint: T, actual: T) -> bool:
A wait time, in seconds, which is unconditionally applied just before the set
status is marked as complete. Defaults to zero.
use_global_moving_flag:
Whether to wait for the IBEX global moving indicator to return "stationary". This is useful
for compound moves, where changing a single block may cause multiple underlying axes to
move, and all movement needs to be complete before the set is considered complete. Defaults
to False.
"""

use_completion_callback: bool = True
set_success_func: Callable[[T, T], bool] | None = None
set_timeout_s: float | None = None
settle_time_s: float = 0.0
use_global_moving_flag: bool = False


class RunControl(StandardReadable):
Expand Down Expand Up @@ -185,6 +198,11 @@ def __init__(

self._write_config: BlockWriteConfig[T] = write_config or BlockWriteConfig()

if self._write_config.use_global_moving_flag:
# Misleading PV name... says it's a str but it's really a bi record.
# Only link to this if we need to (i.e. if use_global_moving_flag was requested)
self.global_moving = epics_signal_r(bool, f"{prefix}CS:MOT:MOVING:STR")

super().__init__(datatype=datatype, prefix=prefix, block_name=block_name)

@AsyncStatus.wrap
Expand All @@ -198,6 +216,21 @@ async def do_set(setpoint: T) -> None:
)
logger.info("Got completion callback from setting block %s to %s", self.name, setpoint)

if self._write_config.use_global_moving_flag:
logger.info(
"Waiting for global moving flag on setting block %s to %s", self.name, setpoint
)
# Paranoid sleep - ensure that the global flag has had a chance to go into moving,
# otherwise there could be a race condition where we check the flag before the move
# has even started.
await asyncio.sleep(GLOBAL_MOVING_FLAG_PRE_WAIT)
await wait_for_value(self.global_moving, False, timeout=None)
logger.info(
"Done wait for global moving flag on setting block %s to %s",
self.name,
setpoint,
)

# Wait for the _set_success_func to return true.
# This uses an "async for" to loop over items from observe_value, which is an async
# generator. See documentation on "observe_value" or python "async for" for more details
Expand Down Expand Up @@ -282,6 +315,7 @@ def __init__(
"""Create a new motor-record block.
The 'BlockMot' object supports motion-specific functionality such as:
- Stopping if a scan is aborted (supports the bluesky 'Stoppable' protocol)
- Limit checking (before a move starts - supports the bluesky 'Checkable' protocol)
- Automatic calculation of move timeouts based on motor velocity
Expand All @@ -308,6 +342,9 @@ def __init__(
keyword-argument on set().
settle_time_s:
Use .DLY on the motor record to configure this.
use_global_moving_flag:
This is unnecessary for a single motor block, as a completion callback will always be
used instead to detect when a single move has finished.
"""
self.run_control = RunControl(f"{prefix}CS:SB:{block_name}:RC:")

Expand Down
36 changes: 35 additions & 1 deletion tests/devices/test_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

import asyncio
import sys
from unittest.mock import ANY, MagicMock, patch
from unittest.mock import ANY, MagicMock, call, patch

import bluesky.plan_stubs as bps
import bluesky.plans as bp
import pytest
from ophyd_async.core import get_mock_put, set_mock_value

from ibex_bluesky_core.devices.block import (
GLOBAL_MOVING_FLAG_PRE_WAIT,
BlockMot,
BlockR,
BlockRw,
Expand Down Expand Up @@ -205,6 +206,39 @@ async def test_block_set_with_settle_time_longer_than_timeout():
mock_aio_sleep.assert_called_once_with(30)


async def test_block_set_waiting_for_global_moving_flag():
block = await _block_with_write_config(
BlockWriteConfig(use_global_moving_flag=True, set_timeout_s=0.1)
)

set_mock_value(block.global_moving, False)
with patch("ibex_bluesky_core.devices.block.asyncio.sleep") as mock_aio_sleep:
await block.set(10)
# Only check first call, as wait_for_value from ophyd_async gives us a few more...
assert mock_aio_sleep.mock_calls[0] == call(GLOBAL_MOVING_FLAG_PRE_WAIT)


async def test_block_set_waiting_for_global_moving_flag_timeout():
block = await _block_with_write_config(
BlockWriteConfig(use_global_moving_flag=True, set_timeout_s=0.1)
)

set_mock_value(block.global_moving, True)
with patch("ibex_bluesky_core.devices.block.asyncio.sleep") as mock_aio_sleep:
with pytest.raises(aio_timeout_error):
await block.set(10)
# Only check first call, as wait_for_value from ophyd_async gives us a few more...
assert mock_aio_sleep.mock_calls[0] == call(GLOBAL_MOVING_FLAG_PRE_WAIT)


async def test_block_without_use_global_moving_flag_does_not_refer_to_global_moving_pv():
block_without = await _block_with_write_config(BlockWriteConfig(use_global_moving_flag=False))
block_with = await _block_with_write_config(BlockWriteConfig(use_global_moving_flag=True))

assert not hasattr(block_without, "global_moving")
assert hasattr(block_with, "global_moving")


@pytest.mark.parametrize(
("func", "args"),
[
Expand Down

0 comments on commit e48d253

Please sign in to comment.