Files
mx_bec/tests/unit/mock_smargopolo.py
perl_dandx10sa d18c33f3b6
CI for mx_bec / e2e tests with pxi_bec (push) Failing after 1m4s
CI for mx_bec / e2e tests with pxii_bec (push) Failing after 1m17s
CI for mx_bec / e2e tests with pxiii_bec (push) Failing after 1m17s
CI for mx_bec / unit tests with pxiii_bec (push) Failing after 1m47s
CI for mx_bec / unit tests with pxii_bec (push) Failing after 1m55s
CI for mx_bec / unit tests with pxi_bec (push) Failing after 1m55s
AareBec task service (#2)
# MX task architecture: AareBec service, tasks, queues and widgets

Brings the AareBec task architecture into `mx_bec`

## Components

- **AareBec service** (`service.py`, `main.py`): custom BEC client that owns the task queue,
  the actor manager and the external API clients.
- **Task framework** (`tasks/core.py`): `@task` decorator and `TaskManager` with `Server` and
  `Client` roles. The server runs tasks one at a time and pauses the queue on failure; clients
  request tasks over Redis. `MxTaskQueue` works off the execution list.
- **MX tasks** (`tasks/mx_tasks.py`): sample mount, optical centering, raster and multi-raster
  scans, X-ray centering, rotation data collection, beamline state change and cleanup.
- **Automation actors** (`actors/`, `actor_manager.py`): actors that react to sequence
  milestones and queue the next task, each switchable through a Redis config value.
- **External clients**: `AareDaq` REST client (Kerberos token, baton handling), `JFJoch`
  raster client, `OpticalPrediction` (AareLC). The `AareDaq` client is to be replaced with native BEC
  implementations.
- **Devices** (`devices/`): Aerotech, Smargon (smargopolo), HTTP device base, simulated stages
  and sample changer, plus a demo config.
- **Widgets** (`bec_widgets/widgets/aare_bec/`): actor config, task queue, task panel, sample
  queue and sample spreadsheet display - for development and admin use.
- **Endpoints and messages** for task requests, the execution list, queue-change
  notifications and sequence state.

## Notes

- BEC-driven optical centering was removed; it will be reimplemented from scratch.
- The sample spreadsheet is copied between Redis instances by a hack in the service, to be
  replaced by the sample database connection module.
- CI installs from the MX Gitea package index (`jfjoch_client` is pre-release only).

---------

Co-authored-by: x10sa <x10sa@psi.ch>
Reviewed-on: #2
Co-authored-by: David Perl <david.perl@psi.ch>
2026-11-24 14:41:31 +01:00

161 lines
4.3 KiB
Python

"""A mock smargopolo REST interface with mock motors, for testing devices against.
Adapted from pxii_bec/tests/tests_devices/mock_smargopolo.py.
Run it standalone with `python mock_smargopolo.py` or in-process via `run_in_thread()`.
"""
import asyncio
import random
import socket
import time
from collections.abc import Iterable
from contextlib import asynccontextmanager
from threading import Thread
from typing import Annotated
import uvicorn
from fastapi import FastAPI, HTTPException, Query, Request
AxisQuery = Annotated[list[str] | None, Query()]
AXES = ["SHX", "SHY", "SHZ", "PHI", "CHI"]
class Motor:
def __init__(self, velocity: float = 1.0, position: float = 0.0):
self.position = position
self.target = position
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)
def make_motors() -> dict[str, Motor]:
return {
"SHX": Motor(velocity=3),
"SHY": Motor(velocity=2.5),
"SHZ": Motor(velocity=2),
"PHI": Motor(velocity=1.0),
"CHI": Motor(velocity=0.7),
}
motors: dict[str, Motor] = make_motors()
@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: AxisQuery = None):
selected_axes = validate_axes(axis)
return {ax: motors[ax].position for ax in selected_axes}
@app.get("/targetSCS")
async def get_target_scs(axis: AxisQuery = None):
selected_axes = validate_axes(axis)
return {ax: motors[ax].target 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()}
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"}
def free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
class MockSmargopolo:
"""The mock server running in a background thread, for use in tests."""
def __init__(self, port: int | None = None):
self.port = port if port is not None else free_port()
self.url = f"http://127.0.0.1:{self.port}"
self._server = uvicorn.Server(
uvicorn.Config(app, host="127.0.0.1", port=self.port, log_level="warning")
)
self._thread = Thread(target=self._server.run, daemon=True)
def start(self, timeout: float = 5.0):
motors.clear()
motors.update(make_motors())
self._thread.start()
deadline = time.monotonic() + timeout
while not self._server.started:
if time.monotonic() > deadline:
raise TimeoutError("Mock smargopolo did not start")
time.sleep(0.01)
return self
def stop(self):
self._server.should_exit = True
self._thread.join(timeout=5)
def __enter__(self):
return self.start()
def __exit__(self, *exc):
self.stop()
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000, reload=False)