Skip to content

Commit

Permalink
Rewrite using absolute deadlines
Browse files Browse the repository at this point in the history
  • Loading branch information
coretl committed Nov 22, 2024
1 parent 47c06d2 commit 2de6b12
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
31 changes: 15 additions & 16 deletions src/ophyd_async/sim/demo/_sim_motor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import contextlib
import time

import numpy as np
from bluesky.protocols import Movable, Stoppable

from ophyd_async.core import (
Expand Down Expand Up @@ -44,22 +45,20 @@ def __init__(self, name="", instant=True) -> None:

async def _move(self, old_position: float, new_position: float, move_time: float):
start = time.monotonic()
distance = new_position - old_position
while True:
# 10hz update loop
await asyncio.sleep(0.1)

time_elapsed = round(time.monotonic() - start, 2)

# update position based on time elapsed
if time_elapsed >= move_time:
# successfully reached our target position
self._user_readback_set(new_position)
break
else:
current_position = old_position + distance * time_elapsed / move_time

self._user_readback_set(current_position)
# Make an array of relative update times at 10Hz intervals
update_times = np.arange(0.1, move_time, 0.1)
# With the end position appended
update_times = np.concatenate((update_times, [move_time]))
# Interpolate the [old, new] position array with those update times
new_positions = np.interp(
update_times, [0, move_time], [old_position, new_position]
)
for update_time, new_position in zip(update_times, new_positions, strict=True):
# Calculate how long to wait to get there
relative_time = time.monotonic() - start
await asyncio.sleep(update_time - relative_time)
# Update the readback position
self._user_readback_set(new_position)

@WatchableAsyncStatus.wrap
async def set(self, value: float):
Expand Down
4 changes: 2 additions & 2 deletions tests/sim/demo/test_sim_motor.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async def test_negative_move():
"unit": "mm",
},
{
"current": pytest.approx(-0.1),
"current": -0.1,
"initial": 0.0,
"name": "M1",
"target": -0.19,
Expand All @@ -70,7 +70,7 @@ async def test_negative_move():
"initial": 0.0,
"name": "M1",
"target": -0.19,
"time_elapsed": pytest.approx(0.2, abs=0.05),
"time_elapsed": pytest.approx(0.19, abs=0.05),
"unit": "mm",
},
]
Expand Down

0 comments on commit 2de6b12

Please sign in to comment.