Fixes/sastt beamtime #361

Merged
holler merged 12 commits from fixes/sastt_beamtime into main 2026-11-23 17:02:55 +01:00
21 changed files with 1173 additions and 108 deletions

No files matched your search

@@ -90,7 +90,6 @@ class SAXSWidget(BECWidget, QWidget):
ROI_NAME = "SAXS ROI"
def __init__(self, parent=None, **kwargs):
kwargs.setdefault("theme_update", True)
super().__init__(parent=parent, **kwargs)
self.get_bec_shortcuts()
self._rows: list[SAXSRow] = []
+19 -19
View File
@@ -21,26 +21,12 @@
# - bl_detectors
# - eiger
eiger_1_5:
description: Eiger 1.5M in-vacuum detector
deviceClass: csaxs_bec.devices.jungfraujoch.eiger_1_5m.Eiger1_5M
deviceConfig:
detector_distance: 2200
beam_center: [870, 1203]
onFailure: raise
enabled: True
readoutPriority: async
softwareTrigger: False
deviceTags:
- bl_detectors
- eiger
# eiger_9:
# description: Eiger 9M detector
# deviceClass: csaxs_bec.devices.jungfraujoch.eiger_9m.Eiger9M
# eiger_1_5:
# description: Eiger 1.5M in-vacuum detector
# deviceClass: csaxs_bec.devices.jungfraujoch.eiger_1_5m.Eiger1_5M
# deviceConfig:
# detector_distance: 6975.225
# beam_center: [1149.71, 1450.89]
# detector_distance: 2200
# beam_center: [870, 1203]
# onFailure: raise
# enabled: True
# readoutPriority: async
@@ -49,6 +35,20 @@ eiger_1_5:
# - bl_detectors
# - eiger
eiger_9:
description: Eiger 9M detector
deviceClass: csaxs_bec.devices.jungfraujoch.eiger_9m.Eiger9M
deviceConfig:
detector_distance: 6975.225
beam_center: [1149.71, 1450.89]
onFailure: raise
enabled: True
readoutPriority: async
softwareTrigger: False
deviceTags:
- bl_detectors
- eiger
# ids_cam:
# description: IDS camera for live image acquisition
# deviceClass: csaxs_bec.devices.ids_cameras.IDSCamera
+6 -6
View File
@@ -16,8 +16,8 @@ endstation:
detectors:
- !include ./bl_detectors.yaml
# xeye:
# - !include ./xeye.yaml
xeye:
- !include ./xeye.yaml
# ssaxs:
# - !include ./ssaxs.yaml
@@ -25,8 +25,8 @@ detectors:
#sastt:
# - !include ./sastt.yaml
# sastt:
# - !include ./sastt_aerotech.yaml
sastt:
- !include ./sastt_aerotech.yaml
# flomni:
# - !include ./ptycho_flomni.yaml
@@ -34,8 +34,8 @@ detectors:
#omny:
# - !include ./ptycho_omny.yaml
lamni:
- !include ./ptycho_lamni.yaml
# lamni:
# - !include ./ptycho_lamni.yaml
# user setup:
# - !include ./user_setup.yaml
@@ -160,3 +160,24 @@ aerocapture:
readoutPriority: async
deviceTags:
- sastt_aerotech
cam_sample:
description: Camera sample
deviceClass: csaxs_bec.devices.ids_cameras.ids_camera.IDSCamera
deviceConfig:
camera_id: 1
bits_per_pixel: 24
num_rotation_90: 3
transpose: true
force_monochrome: false
m_n_colormode: 1
enabled: true
onFailure: buffer
readOnly: false
readoutPriority: async
# userParameter:
# pixel_calibration: 0.00044247787610619477 # mm/pixel (= 0.05 / 113)
smargon:
- !include ./smargon.yaml
+33 -3
View File
@@ -28,8 +28,9 @@ smargon:
# --- SCS axis motors --------------------------------------------------------------
# Limits from the MX-lab reference client (resources_2/Smargon.py) -- VERIFY per build.
# NOTE: SHZ is not centred on 0 (home ~18); PHI is continuous (client wraps to
# [-180,180) -- open question whether smargopolo wraps server-side).
# NOTE: SHZ is not centred on 0 (home ~18). PHI is continuous: `modulo: 360` makes
# sgphi take requested angles mod 360 and always move the shortest way (350 -> 10 is
# +20); the readback is shown wrapped into [-180,180), the raw smargopolo PHI may grow.
sgx:
description: SmarGon SHX (sample X)
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
@@ -69,12 +70,41 @@ sgchi:
sgphi:
description: SmarGon PHI (goniometer rotation)
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
deviceConfig: {scs_axis: PHI, host: tt-smargopolo, port: 3000, limits: [-180, 180], tolerance: 0.01}
deviceConfig: {scs_axis: PHI, host: tt-smargopolo, port: 3000, modulo: 360, tolerance: 0.01}
deviceTags: [goniometer, smargon]
enabled: true
onFailure: retry
readoutPriority: baseline
sgox:
description: SmarGon OX
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
deviceConfig: {scs_axis: OX, host: tt-smargopolo, port: 3000, limits: [-2, 2], tolerance: 0.001}
deviceTags: [goniometer, smargon]
enabled: true
onFailure: retry
readoutPriority: baseline
sgoy:
description: SmarGon OY
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
deviceConfig: {scs_axis: OY, host: tt-smargopolo, port: 3000, limits: [-2, 2], tolerance: 0.001}
deviceTags: [goniometer, smargon]
enabled: true
onFailure: retry
readoutPriority: baseline
sgoz:
description: SmarGon OZ
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
deviceConfig: {scs_axis: OZ, host: tt-smargopolo, port: 3000, limits: [-2, 2], tolerance: 0.001}
deviceTags: [goniometer, smargon]
enabled: true
onFailure: retry
readoutPriority: baseline
# --- Optional OMEGA rotation drive (only on builds that have it) -------------------
# sgomega:
# description: SmarGon OMEGA (rotation drive)
@@ -1,6 +1,7 @@
# Self-contained laptop test session for the SmarGon device (SIMULATION).
#
# Per-axis motors (dev.sgx, dev.sgy, dev.sgz, dev.sgchi, dev.sgphi, dev.sgomega) +
# Per-axis motors (dev.sgx, dev.sgy, dev.sgz, dev.sgchi, dev.sgphi, dev.sgox/sgoy/sgoz,
# optional dev.sgomega) +
# a `smargon` coordinator, all sharing one simulated controller, plus a sim monitor
# so scans record data. No smargopolo server / hardware needed.
#
@@ -94,7 +95,7 @@ sgphi:
scs_axis: PHI,
simulation: true,
gradual_motion: true,
limits: [-180, 180],
modulo: 360,
tolerance: 0.01,
}
deviceTags: [goniometer, smargon, simulation]
@@ -102,6 +103,36 @@ sgphi:
onFailure: retry
readoutPriority: baseline
# --- O-vector (SCS offset vector OX/OY/OZ, mm) ------------------------------------
# Drivable like any SCS axis and recorded in the baseline. No soft limits by default
# (smargopolo enforces the real ones) -- add `limits: [low, high]` per experiment.
sgox:
description: SmarGon OX (offset vector, sim)
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
deviceConfig: {scs_axis: OX, simulation: true, gradual_motion: true, tolerance: 0.001}
deviceTags: [goniometer, smargon, simulation]
enabled: true
onFailure: retry
readoutPriority: baseline
sgoy:
description: SmarGon OY (offset vector, sim)
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
deviceConfig: {scs_axis: OY, simulation: true, gradual_motion: true, tolerance: 0.001}
deviceTags: [goniometer, smargon, simulation]
enabled: true
onFailure: retry
readoutPriority: baseline
sgoz:
description: SmarGon OZ (offset vector, sim)
deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
deviceConfig: {scs_axis: OZ, simulation: true, gradual_motion: true, tolerance: 0.001}
deviceTags: [goniometer, smargon, simulation]
enabled: true
onFailure: retry
readoutPriority: baseline
# sgomega:
# description: SmarGon OMEGA (sim)
# deviceClass: csaxs_bec.devices.smargon.positioner.SmargopoloMotor
+251 -50
View File
@@ -28,7 +28,7 @@ from ophyd import Device, PositionerBase, Signal
from ophyd.status import wait as status_wait
from ophyd.utils import LimitError, ReadOnlyError
from ophyd_devices import AsyncMultiSignal, ProgressSignal, PSIDeviceBase
from ophyd_devices.utils.controller import Controller, retry_once, threadlocked
from ophyd_devices.utils.controller import Controller, threadlocked
from ophyd_devices.utils.socket import SocketIO, SocketSignal, raise_if_disconnected
from prettytable import PrettyTable
@@ -141,32 +141,147 @@ class A3200Controller(Controller):
array_global_base = 0
array_read_chunk = 200
# Time allowed to re-open a connection that was dropped after a communication failure.
reconnect_timeout = 3
# How long operations that are safe to repeat keep retrying over fresh connections
# before they give up. Covers short network or controller outages during long scans.
comm_recovery_timeout = 60.0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not hasattr(self, "_rx_buffer"):
self._rx_buffer = ""
self._reconnect_pending = False
self._counts_per_unit = {}
self._pso_reference = {} # axis -> (position at PSOWINDOW LOAD, PSO counts per unit)
def on(self, timeout: int = 10) -> None:
self._rx_buffer = ""
super().on(timeout=timeout)
self._reconnect_pending = False
def off(self, update_config: bool = True) -> None:
self._reconnect_pending = False # a deliberate disconnect stays disconnected
if self.sock is None and self.connected:
# the socket was already dropped after a failure; finish the disconnect
self.connected = False
if update_config:
self.set_all_devices_enabled(False)
return
super().off(update_config=update_config)
def _drop_connection(self, reason: str) -> None:
"""
Close a connection that can no longer be trusted. The next command opens a new one.
Used when the TCP connection broke (e.g. BrokenPipe after the kernel gave up on an
unresponsive peer) or when a reply did not arrive in time: a late reply would
otherwise be read as the answer to the next command.
`connected` is left unchanged: it drives the axes' connection state, and the drop is
expected to be repaired by the next command. It only goes False if reconnecting fails.
"""
logger.warning(
f"A3200 {self._socket_host}:{self._socket_port}: dropping connection ({reason})."
" It will be re-opened with the next command."
)
self.command_history.append(f"[DROP]: {reason}")
self._rx_buffer = ""
if self.sock is not None:
try:
self.sock.close()
except OSError:
pass
self.sock = None
self._reconnect_pending = True
def _ensure_connected(self) -> None:
"""Re-open a connection dropped by _drop_connection. A deliberate off() is respected."""
if not self._reconnect_pending:
return
logger.info(f"A3200 {self._socket_host}:{self._socket_port}: reconnecting.")
try:
self.on(timeout=self.reconnect_timeout)
except Exception as exc:
self.sock = None
if self.connected:
self.connected = False # unreachable: axes report disconnected until it is back
raise A3200CommunicationError(
f"Could not reconnect to the A3200 at {self._socket_host}:{self._socket_port}:"
f" {exc}"
) from exc
def _with_recovery(self, action, description: str):
"""
Run `action`, which must be safe to repeat, and retry it after communication
failures for up to comm_recovery_timeout. Every failure has already dropped the
connection, so each retry runs over a freshly opened one.
Controller errors (A3200Error: invalid command, task fault, switched off) are not
retried.
"""
deadline = time.time() + self.comm_recovery_timeout
delay = 0.5
while True:
try:
return action()
except A3200CommunicationError as exc:
remaining = deadline - time.time()
if remaining <= 0:
raise A3200CommunicationError(
f"{description}: no working connection to the A3200 for"
f" {self.comm_recovery_timeout:.0f} s. Last error: {exc}"
) from exc
logger.warning(f"{description} failed ({exc}). Retrying in {delay:.1f} s.")
time.sleep(min(delay, remaining))
delay = min(delay * 2, 5.0)
@threadlocked
def socket_put(self, val: str) -> None:
if self.sock is None and not self._reconnect_pending:
raise A3200Error(
f"The connection to the A3200 at {self._socket_host}:{self._socket_port} is"
" switched off."
)
self._ensure_connected()
self.command_history.append(f"[PUT]: {val}")
self.sock.put(f"{val}{EOS}".encode())
try:
self.sock.put(f"{val}{EOS}".encode())
except OSError as exc:
self._drop_connection(f"sending '{val}' failed: {exc!r}")
raise A3200CommunicationError(
f"Sending '{val}' to the A3200 failed ({exc!r}). The connection was reset."
) from exc
@threadlocked
def socket_get(self, timeout: float = 5.0) -> str:
"""Receive one EOS-terminated reply. The EOS character is stripped."""
start = time.time()
while EOS not in self._rx_buffer:
chunk = self.sock.receive().decode()
try:
chunk = self.sock.receive().decode()
except TimeoutError as exc:
if exc.errno is not None: # e.g. ETIMEDOUT: the kernel gave up on the connection
self._drop_connection(f"receive failed: {exc!r}")
raise A3200CommunicationError(
f"Connection to the A3200 lost ({exc!r}). The connection was reset."
) from exc
chunk = "" # socket read timeout: no data yet, keep waiting until `timeout`
except OSError as exc:
self._drop_connection(f"receive failed: {exc!r}")
raise A3200CommunicationError(
f"Connection to the A3200 lost ({exc!r}). The connection was reset."
) from exc
if chunk:
self._rx_buffer += chunk
continue
if time.time() - start > timeout:
partial, self._rx_buffer = self._rx_buffer, ""
partial = self._rx_buffer
self._drop_connection(f"no complete reply within {timeout} s")
raise A3200CommunicationError(
f"No complete reply within {timeout} s. Received so far:"
f" {partial!r}. Is 'Always Send EOS' set in CommandSetup?"
" The connection was reset."
)
time.sleep(0.005)
response, self._rx_buffer = self._rx_buffer.split(EOS, 1)
@@ -182,23 +297,24 @@ class A3200Controller(Controller):
def command(self, cmd: str) -> str:
"""
Send a command and return the reply data (without the success character).
Not retried: a motion command must not be sent twice.
Not retried here: the methods that are safe to repeat wrap it in _with_recovery,
a command that must not run twice (HOMEASYNC, PSOCONTROL FIRE) is sent only once.
Raises:
A3200Error: invalid command ('!') or task fault ('#'); for a fault the
controller's ~LASTERROR message is included.
A3200CommunicationError: unexpected reply.
A3200CommunicationError: no or unexpected reply; the connection was reset.
"""
reply = self.socket_put_and_receive(cmd)
if not reply:
raise A3200CommunicationError(f"Empty reply to '{cmd}'.")
code, data = reply[0], reply[1:].strip()
code, data = (reply[0], reply[1:].strip()) if reply else ("", "")
if code == ACK_CHAR:
return data
if code == NAK_CHAR:
raise A3200Error(f"Controller rejected '{cmd}' as invalid.")
if code == FAULT_CHAR:
raise A3200Error(f"'{cmd}' failed: {self.last_error()}")
# replies and commands are out of step: start again on a clean connection
self._drop_connection(f"unexpected reply to '{cmd}': {reply!r}")
raise A3200CommunicationError(f"Unexpected reply to '{cmd}': {reply!r}")
def last_error(self) -> str:
@@ -206,10 +322,8 @@ class A3200Controller(Controller):
return reply[1:].strip() if reply.startswith(ACK_CHAR) else reply
def get_version(self) -> str:
return self.command("~VERSION")
return self._with_recovery(lambda: self.command("~VERSION"), "~VERSION")
@retry_once
@threadlocked
def get_status_items(self, items: list[tuple]) -> list[float]:
"""
Read several status items in one round trip with ~STATUS.
@@ -218,10 +332,17 @@ class A3200Controller(Controller):
items: tuples as in the ~STATUS syntax, e.g. [("X", "PositionFeedback")]
"""
query = " ".join(f"({', '.join(str(i) for i in item)})" for item in items)
return self._with_recovery(
lambda: self._get_status_items_once(query, len(items)), f"~STATUS {query}"
)
@threadlocked
def _get_status_items_once(self, query: str, n_items: int) -> list[float]:
values = self.command(f"~STATUS {query}").split()
if len(values) != len(items):
if len(values) != n_items:
self._drop_connection(f"wrong number of values for ~STATUS {query}: {values}")
raise A3200CommunicationError(
f"Expected {len(items)} values for ~STATUS {query}, received {values}"
f"Expected {n_items} values for ~STATUS {query}, received {values}"
)
return [float(v) for v in values]
@@ -284,17 +405,42 @@ class A3200Controller(Controller):
if require_homed and not status["homed"]:
raise A3200Error(f"Axis {axis} is not homed. Use home_axis('{axis}').")
def move_absolute(self, axis: str, position: float, velocity: float) -> None:
"""Start an asynchronous absolute move (MOVEABS returns before the move is done)."""
def move_absolute(
self, axis: str, position: float, velocity: float, tolerance: float | None = None
) -> None:
"""
Start an asynchronous absolute move (MOVEABS returns before the move is done).
If the connection fails while the command is sent, it is unknown whether the
controller received it. After reconnecting, the axis decides: moving or already at
the target (within `tolerance`) means it arrived; otherwise MOVEABS is sent again.
"""
if velocity <= 0:
raise ValueError(f"Velocity must be positive, received {velocity}.")
self.command(f"MOVEABS {axis} {position:.6f} {velocity:.6f}")
cmd = f"MOVEABS {axis} {position:.6f} {velocity:.6f}"
try:
self.command(cmd)
return
except A3200CommunicationError as exc:
logger.warning(f"{cmd}: {exc}. Checking the axis before sending it again.")
def _verify_or_resend():
status = self._get_status_items_once(
f"({axis}, ProgramPositionFeedback) ({axis}, AxisStatus)", 2
)
if self._is_moving(int(status[1])):
return
if tolerance is not None and abs(status[0] - position) <= tolerance:
return
self.command(cmd)
self._with_recovery(_verify_or_resend, cmd)
def enable_axis(self, axis: str) -> None:
self.command(f"ENABLE {axis}")
self._with_recovery(lambda: self.command(f"ENABLE {axis}"), f"ENABLE {axis}")
def disable_axis(self, axis: str) -> None:
self.command(f"DISABLE {axis}")
self._with_recovery(lambda: self.command(f"DISABLE {axis}"), f"DISABLE {axis}")
def home_axis(self, axis: str, wait: bool = True, timeout: float = 300) -> None:
"""Home an axis with HOMEASYNC (non-blocking on the socket), optionally wait."""
@@ -313,20 +459,26 @@ class A3200Controller(Controller):
raise A3200Error(f"Homing of axis {axis} failed. Faults: {status['faults']}")
def fault_ack(self, axis: str) -> None:
self.command(f"FAULTACK {axis}")
self._with_recovery(lambda: self.command(f"FAULTACK {axis}"), f"FAULTACK {axis}")
def abort_axis(self, axis: str) -> None:
self.command(f"ABORT {axis}")
self._with_recovery(lambda: self.command(f"ABORT {axis}"), f"ABORT {axis}")
def abort_all_axes(self) -> None:
axes = [ax.axis_Id for ax in self._axis if ax is not None]
if axes:
self.command(f"ABORT {' '.join(axes)}")
cmd = f"ABORT {' '.join(axes)}"
self._with_recovery(lambda: self.command(cmd), cmd)
def set_ramp_rate(self, axis: str, rate: float) -> None:
"""Rate-based ramping for axis-based moves (MOVEABS), rate in user units/s^2."""
self.command(f"RAMP MODE RATE {axis}")
self.command(f"RAMP RATE {axis} {rate:.6f}")
@threadlocked
def _set(self):
self.command(f"RAMP MODE RATE {axis}")
self.command(f"RAMP RATE {axis} {rate:.6f}")
self._with_recovery(lambda: _set(self), f"RAMP RATE {axis}")
# --- global variables (scratch space for functions and array reads) -----------
@@ -336,8 +488,13 @@ class A3200Controller(Controller):
def evaluate(self, expression: str) -> float:
"""Evaluate an AeroBasic expression on the controller, e.g. UNITSTOCOUNTS(X, 1)."""
self.command(f"$global[{self.scratch_global}] = {expression}")
return self.get_globals(self.scratch_global, 1)[0]
@threadlocked
def _evaluate(self):
self.command(f"$global[{self.scratch_global}] = {expression}")
return self._get_status_items_once(f"($global[{self.scratch_global}])", 1)[0]
return self._with_recovery(lambda: _evaluate(self), f"evaluate {expression}")
def counts_per_unit(self, axis: str) -> float:
"""Encoder counts per user unit of an axis (cached, it is a fixed parameter)."""
@@ -358,14 +515,22 @@ class A3200Controller(Controller):
the EmulatedQuadratureDivider for the MXR emulated quadrature inputs 6-8.
"""
cpu = self.counts_per_unit(axis) / counts_divider
self._pso_reference[axis] = (self.get_position(axis), cpu)
low_counts, high_counts = self._pso_window_counts(axis, low, high)
self.command(f"PSOCONTROL {axis} RESET")
self.command(f"PSOWINDOW {axis} 1 INPUT {pso_input}")
self.command(f"PSOWINDOW {axis} 1 LOAD 0")
self.command(f"PSOWINDOW {axis} 1 RANGE {low_counts}, {high_counts}")
self.command(f"PSOOUTPUT {axis} WINDOW")
self.command(f"PSOCONTROL {axis} ARM")
@threadlocked
def _arm(self):
# the whole sequence is repeated after a failure: RESET starts it from scratch,
# and the position reference is read again with the window counter LOAD
(position,) = self._get_status_items_once(f"({axis}, ProgramPositionFeedback)", 1)
self._pso_reference[axis] = (position, cpu)
low_counts, high_counts = self._pso_window_counts(axis, low, high)
self.command(f"PSOCONTROL {axis} RESET")
self.command(f"PSOWINDOW {axis} 1 INPUT {pso_input}")
self.command(f"PSOWINDOW {axis} 1 LOAD 0")
self.command(f"PSOWINDOW {axis} 1 RANGE {low_counts}, {high_counts}")
self.command(f"PSOOUTPUT {axis} WINDOW")
self.command(f"PSOCONTROL {axis} ARM")
self._with_recovery(lambda: _arm(self), f"PSO arm {axis}")
def pso_window_range(self, axis: str, low: float, high: float) -> None:
"""
@@ -376,7 +541,8 @@ class A3200Controller(Controller):
if axis not in self._pso_reference:
raise A3200Error(f"PSO window of axis {axis} is not armed.")
low_counts, high_counts = self._pso_window_counts(axis, low, high)
self.command(f"PSOWINDOW {axis} 1 RANGE {low_counts}, {high_counts}")
cmd = f"PSOWINDOW {axis} 1 RANGE {low_counts}, {high_counts}"
self._with_recovery(lambda: self.command(cmd), cmd)
def _pso_window_counts(self, axis: str, low: float, high: float) -> tuple[int, int]:
reference, cpu = self._pso_reference[axis]
@@ -385,8 +551,12 @@ class A3200Controller(Controller):
)
def pso_off(self, axis: str) -> None:
self.command(f"PSOWINDOW {axis} 1 OFF")
self.command(f"PSOCONTROL {axis} OFF")
@threadlocked
def _off(self):
self.command(f"PSOWINDOW {axis} 1 OFF")
self.command(f"PSOCONTROL {axis} OFF")
self._with_recovery(lambda: _off(self), f"PSO off {axis}")
self._pso_reference.pop(axis, None)
# --- DATAACQ (position capture into the drive array) -----------------------
@@ -398,30 +568,48 @@ class A3200Controller(Controller):
(measured: 3 latches when the TTL level at J12 rises), 6 = PSO firing.
Npaq sources: 0-5 local encoder counter, 6-11 encoder multiplier (MXR) channel 0-5.
"""
self.command(f"DATAACQ {axis} 1 OFF")
self.command(f"DATAACQ {axis} 1 TRIGGER {trigger}")
for channel in sorted(channels):
self.command(f"DATAACQ {axis} 1 INPUT {channel}")
self.command(f"DATAACQ {axis} 1 ARRAY 0, {n_triggers * len(channels)}")
@threadlocked
def _arm(self):
# repeated as a whole after a failure: it starts with OFF
self.command(f"DATAACQ {axis} 1 OFF")
self.command(f"DATAACQ {axis} 1 TRIGGER {trigger}")
for channel in sorted(channels):
self.command(f"DATAACQ {axis} 1 INPUT {channel}")
self.command(f"DATAACQ {axis} 1 ARRAY 0, {n_triggers * len(channels)}")
self._with_recovery(lambda: _arm(self), f"DATAACQ arm {axis}")
def dataacq_off(self, axis: str) -> None:
self.command(f"DATAACQ {axis} 1 OFF")
cmd = f"DATAACQ {axis} 1 OFF"
self._with_recovery(lambda: self.command(cmd), cmd)
def read_drive_array(self, axis: str, start: int, count: int) -> list[float]:
"""Read drive array elements through $global[array_global_base ...] in chunks."""
base = self.array_global_base
@threadlocked
def _read_chunk(self, first: int, n: int) -> list[float]:
# copy and read back as one unit: a retry copies the chunk again
self.command(f"ARRAY {axis} READ $global[{base}] {first} {n} FAST")
query = " ".join(f"($global[{i}])" for i in range(base, base + n))
return self._get_status_items_once(query, n)
values = []
chunk = self.array_read_chunk
for offset in range(0, count, chunk):
n = min(chunk, count - offset)
self.command(
f"ARRAY {axis} READ $global[{self.array_global_base}] {start + offset} {n} FAST"
values.extend(
self._with_recovery(
lambda first=start + offset, n=n: _read_chunk(self, first, n),
f"ARRAY {axis} READ {start + offset} {n}",
)
)
values.extend(self.get_globals(self.array_global_base, n))
return values
def describe(self) -> None:
t = PrettyTable()
t.title = f"{self.__class__.__name__} on {self.sock.host}:{self.sock.port}"
t.title = f"{self.__class__.__name__} on {self._socket_host}:{self._socket_port}"
t.field_names = ["Axis", "Name", "Enabled", "Homed", "Moving", "Faults", "Position"]
for axis in self._axis:
if axis is None:
@@ -458,7 +646,6 @@ class A3200SignalRO(A3200SignalBase):
class A3200ReadbackSignal(A3200SignalRO):
@retry_once
@threadlocked
def _socket_get(self) -> float:
return self.controller.get_position(self.parent.axis_Id) * self.parent.sign
@@ -484,7 +671,10 @@ class A3200SetpointSignal(A3200SignalBase):
if acceleration:
self.controller.set_ramp_rate(self.parent.axis_Id, acceleration)
self.controller.move_absolute(
self.parent.axis_Id, val * self.parent.sign, self.parent.motor_velocity.get()
self.parent.axis_Id,
val * self.parent.sign,
self.parent.motor_velocity.get(),
tolerance=self.parent.tolerance,
)
@@ -739,7 +929,18 @@ class A3200Motor(Device, PositionerBase):
)
self._done_moving(success=success)
threading.Thread(target=move_and_finish, daemon=True).start()
def watch_move():
# Without this, an exception (e.g. the controller unreachable for longer than
# comm_recovery_timeout) would end the thread silently and leave the move
# status pending until its timeout.
try:
move_and_finish()
except Exception as exc: # pylint: disable=broad-except
logger.error(f"{self.name}: lost track of the move to {position}: {exc}")
if not status.done:
self._done_moving(success=False)
threading.Thread(target=watch_move, daemon=True).start()
try:
if wait:
status_wait(status)
+8 -1
View File
@@ -572,7 +572,14 @@ class Eiger(PSIDeviceBase):
f"Device {self.name} is in ERROR state during acquisition. Broker status: "
f"{yaml.dump(self.jfj_client.jfj_status.to_dict(), indent=4)}"
)
if self.jfj_client.wait_for_idle(timeout=1, raise_on_timeout=False):
# NOTE A broker error that ends a collection (e.g. missing packets) makes
# /wait_till_done fail while the broker is Idle; wait_for_idle treats that
# as idle, and the message checks below decide. Other failures can return
# immediately, so pause before retrying rather than spinning.
finished = self.jfj_client.wait_for_idle(timeout=1, raise_on_timeout=False)
if not finished:
time.sleep(0.2)
if finished:
# Call API endpoints to get broker status
broker_status = self.jfj_client.jfj_status
if broker_status.message_severity not in [
@@ -402,6 +402,14 @@ class JungfrauJochClient:
)
thread.start()
def _broker_is_idle(self) -> bool:
"""True if the broker reports Idle; False if it does not or cannot be asked."""
try:
state = self.api.status_get(_request_timeout=2).state
except Exception: # pylint: disable=broad-except
return False
return getattr(state, "value", state) == DetectorState.IDLE.value
def wait_for_idle(self, timeout: int = 10, raise_on_timeout: bool = True) -> bool:
"""
Method to wait until the detector is in IDLE state. This is a blocking call with a
@@ -427,8 +435,20 @@ class JungfrauJochClient:
)
return False
except Exception as exc:
content = traceback.format_exc()
message = self._api_error_message(exc)
# NOTE After a collection that ended with a broker error (e.g. "Missing packets in
# data collection; reduce frame rate"), /wait_till_done answers HTTP 500 with that
# message on every call until the next collection, although the broker is Idle.
# The detector is then idle, which is all this method promises; the broker message
# stays readable via jfj_status for whoever has to judge the finished collection.
# Without this, on_complete timed out and the next scan failed in on_stage.
if isinstance(exc, ServiceException) and self._broker_is_idle():
logger.info(
f"Device {self._parent_name}: wait_till_done reported '{message}', but the "
f"broker is Idle, so the detector is treated as idle."
)
return True
content = traceback.format_exc()
logger.info(
f"Error on device {self._parent_name} in wait_for_idle. "
f"{message or ''} Full traceback: {content}"
+24 -2
View File
@@ -34,8 +34,13 @@ poll-to-tolerance moves), since both wrap a non-EPICS, poll-to-confirm HTTP back
- **One motor per axis**, top-level: the YAML key is the BEC name (**you choose it**:
`sgx`, `sgchi`, …); a `scs_axis:` field binds it to the fixed smargopolo axis name
(`SHX/SHY/SHZ/CHI/PHI/OMEGA`). OMEGA is optional hardware — add a motor entry only on
builds that have it.
(`SHX/SHY/SHZ/CHI/PHI/OMEGA/OX/OY/OZ`). OMEGA is optional hardware — add a motor entry
only on builds that have it.
- **O-vector motors** `sgox/sgoy/sgoz` drive the SCS offset vector `OX/OY/OZ` (all mm).
They are ordinary motors (`umv`, scans, baseline readout), so the offset is recorded
with every scan. The beamline config gives them `limits: [-2, 2]`; adjust per experiment.
`nudge_beamline(modify_offset=True)` (`/nudgeOBCS`) also changes them; their readback
catches up on the next read.
- **`dev.smargon`** — the coordinator: `reference()`, `get_mode()`, `is_ready()`,
`wait_until_ready()`, `move_scs(...)`, `nudge_beamline(...)`, `motor_positions()`,
`stop_all()`, `transport_info()`, plus read-only `mode`/`rosout` signals.
@@ -111,13 +116,30 @@ pytest tests/tests_devices/test_smargon_transport.py tests/tests_devices/test_sm
All run against `FakeTransport` — no hardware or server needed.
## Stop (Ctrl-C, scan abort)
smargopolo has no stop endpoint; an axis is halted by setting its target to its
readback. A stop only does this for axes that are actually moving: the controller
remembers the targets of the absolute moves BEC commanded (`move`, `umv`, `move_scs`)
until they finish, and `stop()` of a motor or of the `smargon` coordinator retargets only
those axes whose readback is not yet within tolerance of the target, in one request.
Idle axes keep their target, so repeated aborts do not accumulate readback noise or
kinematics round-off in the targets. Not stopped: relative moves, nudges and moves made
outside BEC. The O-vector is never retargeted (see below); `dev.smargon.stop_all()`
still retargets every other axis (explicit command only).
## Open items / to confirm with the smargopolo maintainer (Wayne Glettig)
- **Stop semantics**: no explicit stop endpoint; we retarget axes to their readback
("Follow Target" halt). Confirm this is the intended way to abort a move.
The O-vector (`OX/OY/OZ`) is never retargeted by a stop: its readback fluctuates,
so writing it back would shift the offset on every stop (`STOP_EXCLUDED_AXES`).
- **Mid-move fault signal**: we infer faults from `Mode.ERROR`. Confirm an
out-of-range / coupled-limit violation reliably drives `/mode` to 99 (and that
`rosout` carries the reason), so the abort path is dependable.
- **PHI wrap**: the MX-lab reference client wraps PHI to `[-180,180)` before sending.
Confirm whether smargopolo wraps server-side, or whether the motor should.
- **O-vector semantics**: confirm what `OX/OY/OZ` represent physically, whether
changing them moves the sample (or only re-expresses `SH*`), sensible travel ranges,
and that `OZ` is in mm (the API example shows `OZ: 300.0`, the example client 180).
- *(resolved)* OMEGA is drivable via `/targetSCS` wherever it physically exists.
+77 -6
View File
@@ -22,7 +22,7 @@ import time
from ophyd import OphydObject
from .transport.base import Axis, BeamlineAxis, Mode, SmargopoloTransport
from .transport.base import STOP_EXCLUDED_AXES, Axis, BeamlineAxis, Mode, SmargopoloTransport
from .transport.errors import SmargopoloModeError
from .transport.fake import FakeTransport
from .transport.rest import RestTransport
@@ -103,6 +103,9 @@ class SmargopoloController(OphydObject):
else:
self.transport = RestTransport(host=host, port=port, timeout=timeout)
self._axes: dict[Axis, object] = {} # scs_axis -> SmargopoloMotor (registered by motors)
# raw targets of absolute moves commanded by BEC that have not finished yet;
# stop_moving() only halts these axes, the others are never retargeted
self._active_moves: dict[Axis, float] = {}
self._connected = False
# readback monitor: follows moves made outside BEC (smargopolo web interface)
self.monitor_interval = DEFAULT_MONITOR_INTERVAL
@@ -167,7 +170,10 @@ class SmargopoloController(OphydObject):
failing = False
for axis, motor in motors.items():
value = positions.get(axis)
if value is not None and abs(value - motor.readback.get()) > MONITOR_DEADBAND:
if value is None:
continue
user_value = motor._user_position(value) # pylint: disable=protected-access
if abs(user_value - motor.readback.get()) > MONITOR_DEADBAND:
motor._update_readback(value) # pylint: disable=protected-access
# -- connection lifecycle ----------------------------------------------
@@ -204,8 +210,64 @@ class SmargopoloController(OphydObject):
return self.transport.get_positions()
def move_absolute(self, targets: dict) -> None:
parsed = {Axis(a): float(v) for a, v in targets.items()}
with self._lock:
self.transport.move_absolute({Axis(a): float(v) for a, v in targets.items()})
self.transport.move_absolute(parsed)
self._active_moves.update(parsed)
def finish_move(self, axis: Axis, target: float | None = None) -> None:
"""Forget the active move of *axis* (only if it still has *target*, when given)."""
axis = Axis(axis)
with self._lock:
if target is None or self._active_moves.get(axis) == target:
self._active_moves.pop(axis, None)
def active_moves(self) -> dict:
"""Raw targets of the BEC moves that are still active, ``{Axis: target}``."""
with self._lock:
return dict(self._active_moves)
def stop_moving(self, axes: list | None = None) -> list:
"""Halt only the axes that are actually moving (used by Ctrl-C / scan abort).
Candidates are the axes with an active BEC move (of *axes*, or all). An axis
whose readback is already within its motor's tolerance of the target has
finished and is left alone. Only the remaining axes are retargeted to their
readback, in one request; all other axes keep their target untouched, so a stop
does not write readback (encoder noise, kinematics round-off) into the targets
of idle axes. O-vector axes (STOP_EXCLUDED_AXES) are never retargeted: a stop
only ends BEC's wait for them. Returns the axes that were halted.
"""
wanted = None if axes is None else {Axis(a) for a in axes}
with self._lock:
candidates = {
a: t for a, t in self._active_moves.items() if wanted is None or a in wanted
}
if not candidates:
return []
for axis in candidates:
self._active_moves.pop(axis, None)
positions = self.transport.get_positions()
moving = []
for axis, target in candidates.items():
pos = positions.get(axis)
if pos is None:
continue
motor = self._axes.get(axis)
tol = getattr(motor, "_tolerance", 1e-3)
dist = motor._distance(pos, target) if motor is not None else abs(pos - target)
if dist > tol:
moving.append(axis)
halted = [a for a in moving if a not in STOP_EXCLUDED_AXES]
if halted:
self.transport.stop(halted)
for axis in moving:
motor = self._axes.get(axis)
if motor is not None:
motor._stopped = True # ends its move poll ("interrupted by stop()")
if halted:
logger.info(f"{self.name}: stopped {', '.join(a.value for a in halted)}")
return halted
def move_relative(self, deltas: dict) -> None:
with self._lock:
@@ -290,7 +352,8 @@ class SmargopoloController(OphydObject):
"""Move several SCS axes at once in a single ``/targetSCS`` request.
Keys are SCS axis names, e.g. ``move_scs(SHX=0.1, SHZ=18)``. Each targeted
axis is limit-checked against its registered motor (if any) before sending.
axis is limit-checked against its registered motor (if any) before sending;
axes whose motor has a ``modulo`` take the shortest way.
"""
self.require_ready()
parsed = {Axis(k): float(v) for k, v in targets.items()}
@@ -298,10 +361,12 @@ class SmargopoloController(OphydObject):
motor = self._axes.get(ax)
if motor is not None:
motor.check_value(val)
parsed[ax] = motor._resolve_target(val)[1] # pylint: disable=protected-access
self.move_absolute(parsed)
if wait:
for ax, val in parsed.items():
self._wait_axis(ax, val)
self.finish_move(ax, val)
def _wait_axis(self, axis: Axis, target: float, timeout: float | None = None) -> None:
motor = self._axes.get(axis)
@@ -312,7 +377,8 @@ class SmargopoloController(OphydObject):
pos = self.get_position(axis)
if motor is not None:
motor._update_readback(pos) # noqa: SLF001
if abs(pos - target) <= tol:
dist = motor._distance(pos, target) if motor is not None else abs(pos - target)
if dist <= tol:
return
self.raise_if_error()
if time.monotonic() > deadline:
@@ -327,7 +393,12 @@ class SmargopoloController(OphydObject):
self.transport.nudge_beamline(parsed, modify_offset=modify_offset)
def stop_all(self) -> None:
"""Halt all SCS axes."""
"""Retarget ALL SCS axes to their readback (explicit operator command only).
Ctrl-C / scan aborts use :meth:`stop_moving`, which leaves idle axes untouched.
"""
with self._lock:
self._active_moves.clear()
self.stop(None)
def motor_positions(self) -> dict:
+52 -6
View File
@@ -1,7 +1,7 @@
"""Per-axis SmarGon motor -- a top-level BEC device for one SCS axis.
``SmargopoloMotor`` is an independent ophyd positioner (``Device`` +
``PositionerBase``): each SCS axis (SHX/SHY/SHZ/CHI/PHI/OMEGA) is its own top-level
``PositionerBase``): each SCS axis (SHX/SHY/SHZ/CHI/PHI/OMEGA/OX/OY/OZ) is its own top-level
BEC motor, exactly like the ``smaract`` motors. It talks to hardware only through a
shared :class:`~csaxs_bec.devices.smargon.controller.SmargopoloController` (singleton
per smargopolo server), so ``dev.sgx`` and ``dev.sgchi`` pointing at the same host
@@ -52,6 +52,13 @@ class SmargopoloMotor(Device, PositionerBase):
share one monitor; the value of the last configured axis applies.
egu:
Engineering unit; defaults to the axis' natural unit (mm or deg).
modulo:
Optional period (e.g. ``360`` for an endless rotation such as PHI). When set,
requested positions are taken modulo this value and the axis always moves the
shortest way (350 -> 10 moves +20, not -340). The readback is shown wrapped into
``[-modulo/2, modulo/2)`` while the raw smargopolo position may grow freely.
Note: this applies to every absolute request, so a relative move of more than
half a period (``umvr(sgphi, 270)``) also takes the short way (-90).
"""
readback = Cpt(Signal, value=0.0, kind=Kind.hinted)
@@ -82,6 +89,7 @@ class SmargopoloMotor(Device, PositionerBase):
move_timeout: float = 60.0,
monitor_interval: float = 0.5,
egu: str | None = None,
modulo: float | None = None,
device_manager=None,
kind=None,
parent=None,
@@ -92,6 +100,7 @@ class SmargopoloMotor(Device, PositionerBase):
self._poll_interval = poll_interval
self._move_timeout = move_timeout
self._egu = egu if egu is not None else AXIS_INFO[self.scs_axis].egu
self._modulo = float(modulo) if modulo else None
self._stopped = False
self._move_thread: threading.Thread | None = None
# Optional extra gate (parent/tests). The controller READY-gate is always applied.
@@ -149,10 +158,38 @@ class SmargopoloMotor(Device, PositionerBase):
return self.readback.get()
def check_value(self, value: float) -> None:
value = self._wrap(value)
low, high = self.limits
if low != high and not low <= value <= high:
raise LimitError(f"{self.name}: position {value} outside limits {(low, high)}")
# -- modulo (endless rotation) helpers ------------------------------------
def _wrap(self, value: float) -> float:
"""Wrap *value* into ``[-modulo/2, modulo/2)``; identity without modulo."""
if self._modulo is None:
return value
half = self._modulo / 2
return ((value + half) % self._modulo) - half
def _user_position(self, raw: float) -> float:
"""User-facing position for a raw smargopolo position."""
return self._wrap(raw)
def _distance(self, pos: float, target: float) -> float:
"""Distance pos -> target (modulo-aware, so a server-side wrap still matches)."""
return abs(self._wrap(pos - target))
def _resolve_target(self, position: float) -> tuple[float, float]:
"""Return ``(user_target, raw_target)`` for a requested *position*.
With modulo, raw_target is the raw position reached by the shortest move.
"""
if self._modulo is None:
return position, position
raw_now = self.controller.get_position(self.scs_axis)
return self._wrap(position), raw_now + self._wrap(position - raw_now)
# -- connection lifecycle ----------------------------------------------
# pylint: disable=arguments-differ
@@ -167,6 +204,7 @@ class SmargopoloMotor(Device, PositionerBase):
# -- motion ------------------------------------------------------------
def _update_readback(self, value: float) -> None:
value = self._user_position(value)
old = self.readback.get()
self.readback.put(value)
self._set_position(value)
@@ -180,7 +218,7 @@ class SmargopoloMotor(Device, PositionerBase):
while not self._stopped:
pos = self.controller.get_position(self.scs_axis)
self._update_readback(pos)
if abs(pos - target) <= self._tolerance:
if self._distance(pos, target) <= self._tolerance:
break
self.controller.raise_if_error()
if time.monotonic() > deadline:
@@ -190,10 +228,12 @@ class SmargopoloMotor(Device, PositionerBase):
time.sleep(self._poll_interval)
self._update_readback(self.controller.get_position(self.scs_axis))
except Exception as exc: # pylint: disable=broad-except
self.controller.finish_move(self.scs_axis, target)
self.motor_is_moving.put(0)
if not status.done:
status.set_exception(exc)
return
self.controller.finish_move(self.scs_axis, target)
self.motor_is_moving.put(0)
if self._stopped:
if not status.done:
@@ -209,6 +249,7 @@ class SmargopoloMotor(Device, PositionerBase):
if self.pre_move_hook is not None:
self.pre_move_hook(position)
self._stopped = False
position, raw_target = self._resolve_target(position)
self.setpoint.put(position)
status = DeviceStatus(self, timeout=timeout or self._move_timeout)
@@ -217,14 +258,14 @@ class SmargopoloMotor(Device, PositionerBase):
self.motor_is_moving.put(1)
try:
self.controller.move_absolute({self.scs_axis: position})
self.controller.move_absolute({self.scs_axis: raw_target})
except Exception as exc: # pylint: disable=broad-except
self.motor_is_moving.put(0)
status.set_exception(exc)
return status
self._move_thread = threading.Thread(
target=self._poll_until_target, args=(position, status), daemon=True
target=self._poll_until_target, args=(raw_target, status), daemon=True
)
self._move_thread.start()
@@ -237,10 +278,15 @@ class SmargopoloMotor(Device, PositionerBase):
return self.move(position, wait=False, **kwargs)
def stop(self, *, success: bool = False) -> None:
"""Halt this axis immediately (best-effort: never raises during teardown)."""
"""Halt this axis if it is moving (best-effort: never raises during teardown).
Only an active move of this axis is stopped (its target is set to the
readback); an idle axis is not touched, so stopping does not write readback
noise into its target.
"""
self._stopped = True
try:
self.controller.stop([self.scs_axis])
self.controller.stop_moving([self.scs_axis])
except Exception as exc: # pylint: disable=broad-except
self.log.warning("%s: transport stop failed: %s", self.name, exc)
finally:
+2 -2
View File
@@ -147,8 +147,8 @@ class SmarGon(PSIDeviceBase):
super().wait_for_connection(all_signals=all_signals, timeout=timeout)
def on_stop(self) -> None:
"""Halt all SCS axes."""
self.controller.stop_all()
"""Halt the SCS axes that are moving; idle axes keep their targets untouched."""
self.controller.stop_moving()
# -- delegated whole-goniometer operations -----------------------------
@@ -14,6 +14,7 @@ from .base import (
BeamlineAxis,
Mode,
SmargopoloInfo,
STOP_EXCLUDED_AXES,
SmargopoloTransport,
)
from .errors import (
@@ -36,6 +37,7 @@ __all__ = [
"MOTOR_CHANNELS",
"SmargopoloInfo",
"SmargopoloTransport",
"STOP_EXCLUDED_AXES",
"FakeTransport",
"RestTransport",
"SmargopoloTransportError",
+17 -2
View File
@@ -17,6 +17,8 @@ smargopolo runs the kinematics; we drive the *virtual* SmarGon Coordinate System
* **SCS** -- the user axes: ``SHX SHY SHZ OMEGA CHI PHI OX OY OZ`` (mm and deg).
Settable via ``/targetSCS`` (+ ``/targetSCS_rel``), read via ``/readbackSCS``.
``OX OY OZ`` are the O-vector (offset) components, a length in mm like ``SH*``;
``/nudgeOBCS`` shifts the same vector in the beamline frame.
* **MCS** -- the raw motor positions ``q1..q6``, read-only via ``/readbackMCS``
(diagnostics only; we never command them directly).
* **BCS** -- beamline-frame nudges ``BX BY BZ`` via ``/nudgeBCS`` / ``/nudgeOBCS``
@@ -98,9 +100,20 @@ AXIS_INFO: dict[Axis, AxisLimits] = {
Axis.PHI: AxisLimits(egu="deg"),
Axis.OX: AxisLimits(egu="mm"),
Axis.OY: AxisLimits(egu="mm"),
Axis.OZ: AxisLimits(egu="deg"),
Axis.OZ: AxisLimits(egu="mm"), # O-vector component (mm), not an angle
}
# Axes a stop never retargets. Stop works by writing the current readback back as
# the target; the O-vector readback fluctuates, so doing that would shift the offset
# on every stop. Stopping only the moving SCS axes is enough to halt the sample.
STOP_EXCLUDED_AXES: frozenset[Axis] = frozenset({Axis.OX, Axis.OY, Axis.OZ})
def axes_to_stop(axes) -> list[Axis]:
"""The axes a stop request may retarget: *axes* (or all) minus STOP_EXCLUDED_AXES."""
chosen = list(Axis) if axes is None else [Axis(a) for a in axes]
return [a for a in chosen if a not in STOP_EXCLUDED_AXES]
@dataclass
class SmargopoloInfo:
@@ -195,7 +208,9 @@ class SmargopoloTransport(abc.ABC):
smargopolo exposes no explicit stop endpoint; in ``Mode.READY`` ("Follow
Target") setting the target equal to the current readback brings the axis
to rest. Best-effort: must not raise during teardown.
to rest. Axes in :data:`STOP_EXCLUDED_AXES` (the O-vector) are never
retargeted, even when named explicitly. Best-effort: must not raise during
teardown.
"""
# -- diagnostics -------------------------------------------------------
+2 -3
View File
@@ -29,6 +29,7 @@ from .base import (
Mode,
SmargopoloInfo,
SmargopoloTransport,
axes_to_stop,
)
from .errors import SmargopoloModeError
@@ -198,9 +199,7 @@ class FakeTransport(SmargopoloTransport):
def stop(self, axes: list[Axis] | None = None) -> None:
self._record("stop")
chosen = list(axes) if axes is not None else list(Axis)
for axis in chosen:
axis = Axis(axis)
for axis in axes_to_stop(axes):
if self._gradual:
self._settle(axis)
self._targets[axis] = self._positions[axis]
+6 -2
View File
@@ -28,6 +28,7 @@ from .base import (
Mode,
SmargopoloInfo,
SmargopoloTransport,
axes_to_stop,
)
from .errors import (
SmargopoloCommandError,
@@ -167,12 +168,15 @@ class RestTransport(SmargopoloTransport):
def stop(self, axes: list[Axis] | None = None) -> None:
# Retarget the chosen axes to their current readback: in "Follow Target"
# mode this halts them. Best-effort -- never raise.
# mode this halts them. The O-vector is never retargeted (see
# STOP_EXCLUDED_AXES). Best-effort -- never raise.
chosen = axes_to_stop(axes)
if not chosen:
return
try:
positions = self.get_positions()
except Exception: # pylint: disable=broad-except
return
chosen = list(axes) if axes is not None else list(positions)
targets = {a: positions[a] for a in chosen if a in positions}
if not targets:
return
+201
View File
@@ -104,6 +104,207 @@ def test_missing_eos_times_out(mock_motor):
mock_motor.controller.socket_get(timeout=0.05)
# --- connection recovery -------------------------------------------------------
class _ReplayingSocketMock(SocketMock):
"""SocketMock whose new instances start with the replies queued in `next_replies`."""
next_replies: list = []
instances: list = []
def __init__(self, host, port):
super().__init__(host, port)
self.buffer_recv = list(type(self).next_replies)
type(self).instances.append(self)
@pytest.fixture
def replay_motor():
_ReplayingSocketMock.next_replies = []
_ReplayingSocketMock.instances = []
motor = A3200Motor(
"X",
name="aerox",
host=_HOST,
port=_PORT,
socket_cls=_ReplayingSocketMock,
device_manager=DMMock(),
)
motor.controller.on()
motor.controller.sock.flush_buffer()
motor.controller.comm_recovery_timeout = 0 # fail at once unless a test sets it
yield motor
motor.controller.off()
def _raise(exc):
def _fail(*args, **kwargs):
raise exc
return _fail
def _status_reply(position, axis_status):
return f"%{position} {axis_status}\n".encode()
_IDLE = 1 << 22 # AxisStatus MoveDone, no busy bits
_PROFILING = 1 << 1
def test_broken_pipe_drops_connection(replay_motor):
controller = replay_motor.controller
old_sock = controller.sock
old_sock.put = _raise(BrokenPipeError(32, "Broken pipe"))
with pytest.raises(A3200CommunicationError):
controller.socket_put("~VERSION")
assert controller.sock is None
assert controller.connected # axes stay usable; the next command reconnects
_ReplayingSocketMock.next_replies = [b"%6.04\n"]
assert controller.get_version() == "6.04"
assert controller.sock is not old_sock
assert controller.sock.buffer_put == [b"~VERSION\n"]
def test_lost_moveabs_is_resent_when_axis_idle(replay_motor):
controller = replay_motor.controller
controller.sock.put = _raise(BrokenPipeError(32, "Broken pipe"))
_ReplayingSocketMock.next_replies = [_status_reply(0.0, _IDLE), b"%\n"]
controller.move_absolute("X", 1.0, 2.0, tolerance=0.001)
assert controller.sock.buffer_put == [
b"~STATUS (X, ProgramPositionFeedback) (X, AxisStatus)\n",
b"MOVEABS X 1.000000 2.000000\n",
]
@pytest.mark.parametrize(
"position, axis_status", [(0.5, _PROFILING), (1.0004, _IDLE)], ids=["moving", "at_target"]
)
def test_moveabs_that_arrived_is_not_sent_twice(replay_motor, position, axis_status):
controller = replay_motor.controller
controller.sock.put = _raise(BrokenPipeError(32, "Broken pipe"))
_ReplayingSocketMock.next_replies = [_status_reply(position, axis_status)]
controller.move_absolute("X", 1.0, 2.0, tolerance=0.001)
assert controller.sock.buffer_put == [
b"~STATUS (X, ProgramPositionFeedback) (X, AxisStatus)\n"
]
def test_outage_is_bridged_within_recovery_timeout(replay_motor, monkeypatch):
controller = replay_motor.controller
controller.comm_recovery_timeout = 10
controller.sock.put = _raise(BrokenPipeError(32, "Broken pipe"))
attempts = []
original_open = _ReplayingSocketMock.open
def _open(self, timeout=10):
attempts.append(1)
if len(attempts) <= 2:
raise ConnectionError("Could not connect")
return original_open(self, timeout)
monkeypatch.setattr(_ReplayingSocketMock, "open", _open)
_ReplayingSocketMock.next_replies = [b"%4.5\n"]
assert controller.get_position("X") == 4.5
assert len(attempts) >= 3 # two failed reconnects, then success
assert controller.connected
def test_failed_move_watch_finishes_the_status(mock_motor, monkeypatch):
controller = mock_motor.controller
monkeypatch.setattr(controller, "check_ready_to_move", lambda *a, **k: None)
monkeypatch.setattr(controller, "move_absolute", lambda *a, **k: None)
monkeypatch.setattr(controller, "set_ramp_rate", lambda *a, **k: None)
def _unreachable(axis):
raise A3200CommunicationError("no working connection")
monkeypatch.setattr(controller, "is_axis_moving", _unreachable)
status = mock_motor.move(1.0, wait=False)
with pytest.raises(Exception):
status.wait(timeout=2)
assert status.done and not status.success
def test_status_read_retries_on_new_connection(replay_motor):
controller = replay_motor.controller
controller.comm_recovery_timeout = 5
controller.sock.put = _raise(BrokenPipeError(32, "Broken pipe"))
_ReplayingSocketMock.next_replies = [b"%7.5\n"]
assert controller.get_position("X") == 7.5
assert len(_ReplayingSocketMock.instances) == 2
def test_reply_timeout_drops_connection_so_late_reply_is_not_misread(replay_motor):
controller = replay_motor.controller
old_sock = controller.sock
old_sock.buffer_recv = []
controller.socket_put("~STATUS (X, ProgramPositionFeedback)")
with pytest.raises(A3200CommunicationError, match="connection was reset"):
controller.socket_get(timeout=0.05)
old_sock.buffer_recv = [b"%1.0\n"] # the late reply arrives on the old connection
_ReplayingSocketMock.next_replies = [b"%2.0\n"]
assert controller.get_position("X") == 2.0
def test_socket_read_timeout_is_not_a_failure(replay_motor):
controller = replay_motor.controller
replies = [TimeoutError("timed out"), b"%3.25\n"]
def _receive(*args, **kwargs):
item = replies.pop(0)
if isinstance(item, Exception):
raise item
return item
controller.sock.receive = _receive
assert controller.get_position("X") == 3.25
assert len(_ReplayingSocketMock.instances) == 1
def test_connection_timed_out_drops_connection(replay_motor):
controller = replay_motor.controller
controller.sock.receive = _raise(TimeoutError(110, "Connection timed out"))
with pytest.raises(A3200CommunicationError, match="Connection to the A3200 lost"):
controller.socket_put_and_receive("~VERSION")
assert controller.sock is None
def test_failed_reconnect_marks_controller_disconnected(replay_motor, monkeypatch):
controller = replay_motor.controller
controller.sock.put = _raise(BrokenPipeError(32, "Broken pipe"))
with pytest.raises(A3200CommunicationError):
controller.enable_axis("X")
def _unreachable(self, timeout=10):
raise ConnectionError("Could not connect")
monkeypatch.setattr(_ReplayingSocketMock, "open", _unreachable)
with pytest.raises(A3200CommunicationError, match="Could not reconnect"):
controller.enable_axis("X")
assert not controller.connected
monkeypatch.undo()
_ReplayingSocketMock.next_replies = [b"%\n"]
controller.enable_axis("X")
assert controller.connected
def test_deliberate_off_is_not_undone(replay_motor):
controller = replay_motor.controller
controller.sock.put = _raise(BrokenPipeError(32, "Broken pipe"))
with pytest.raises(A3200CommunicationError):
controller.enable_axis("X")
controller.off(update_config=False)
assert not controller.connected
assert not controller._reconnect_pending
with pytest.raises(A3200Error, match="switched off"):
controller.enable_axis("X")
def test_status_query_format(mock_motor):
mock_motor.controller.sock.buffer_recv = [b"%1.5 4194305 1 0\n"]
status = mock_motor.controller.axis_status("X")
+98 -1
View File
@@ -401,7 +401,11 @@ def test_eiger_on_complete(eiger_1_5m, raise_timeout):
mock.patch.object(
eiger.jfj_client.api,
"status_get",
return_value=BrokerStatus(state="Idle", message_severity="info"),
# A broker that reports Idle counts as finished even if wait_for_idle fails,
# so the timeout case needs one that is still measuring.
return_value=BrokerStatus(
state="Measuring" if raise_timeout else "Idle", message_severity="info"
),
),
mock.patch.object(eiger.jfj_client, "wait_for_idle", side_effect=mock_wait_for_idle),
mock.patch.object(
@@ -781,6 +785,99 @@ def test_eiger_tolerance_does_not_hide_a_short_acquisition(eiger_1_5m):
_run_on_complete(eiger, _missing_packets_status(), images_collected=9)
def _missing_packets_http_500():
"""The ServiceException JFJoch's /wait_till_done raises after a lossy collection."""
return ServiceException(
status=500,
reason="Internal Server Error",
body='{"msg":"Missing packets in data collection; reduce frame rate","reason":"Other"}',
)
def test_jfj_client_wait_for_idle_is_idle_when_broker_idle_despite_http_500():
"""on_stage's raising wait_for_idle must pass when the previous collection lost packets
(2026-11-11: S00998 completed with the tolerance, S00999 then failed in on_stage)."""
client = _jfj_client()
idle = BrokerStatus(state="Idle", message_severity="error", message="Missing packets")
with (
mock.patch.object(client.api, "wait_till_done_post", side_effect=_missing_packets_http_500()),
mock.patch.object(client.api, "status_get", return_value=idle),
):
assert client.wait_for_idle(timeout=1) is True
assert client.wait_for_idle(timeout=1, raise_on_timeout=False) is True
def test_jfj_client_wait_for_idle_still_raises_on_http_500_when_not_idle():
"""The Idle shortcut must not hide a 500 while the broker is busy or in error."""
client = _jfj_client()
busy = BrokerStatus(state="Error", message_severity="error", message="Detector error")
with (
mock.patch.object(client.api, "wait_till_done_post", side_effect=_missing_packets_http_500()),
mock.patch.object(client.api, "status_get", return_value=busy),
):
with pytest.raises(JungfrauJochClientError, match="Missing packets"):
client.wait_for_idle(timeout=1)
assert client.wait_for_idle(timeout=1, raise_on_timeout=False) is False
def _run_on_complete_wait_till_done_failing(eiger, broker_status, images_collected=10):
"""Like _run_on_complete, but as JFJoch behaves after a collection that ended in an
error: /wait_till_done answers HTTP 500 on every call while the broker itself already
reports Idle (seen 2026-11-11, S00985).
"""
eiger._wait_for_on_complete = 2
with (
mock.patch.object(eiger.jfj_client.api, "status_get", return_value=broker_status),
mock.patch.object(
eiger.jfj_client.api, "wait_till_done_post", side_effect=_missing_packets_http_500()
),
mock.patch.object(
eiger.jfj_client.api,
"statistics_data_collection_get",
return_value=MeasurementStatistics(run_number=1, images_collected=images_collected),
),
):
status = eiger.complete()
status.wait(timeout=5)
return status
def test_eiger_tolerates_missing_packets_when_wait_till_done_errors(eiger_1_5m):
"""The tolerance must apply although /wait_till_done keeps failing -- before the fix
this case spun until the on_complete timeout and raised TimeoutError instead."""
eiger = eiger_1_5m
eiger.set_raise_on_missing_packets(False)
eiger._num_triggers = 10
start = time.time()
status = _run_on_complete_wait_till_done_failing(eiger, _missing_packets_status())
assert status.done is True
assert status.success is True
assert eiger.get_missing_packet_events() == 1
assert time.time() - start < 1.5 # resolved on the first pass, not by the timeout
def test_eiger_raises_eiger_error_not_timeout_when_wait_till_done_errors(eiger_1_5m):
"""With the tolerance off the scan still fails -- with the broker error, promptly."""
eiger = eiger_1_5m
eiger.set_raise_on_missing_packets(True)
with pytest.raises(EigerError, match="error status from JungfrauJoch broker"):
_run_on_complete_wait_till_done_failing(eiger, _missing_packets_status())
def test_eiger_still_waits_while_measuring_when_wait_till_done_errors(eiger_1_5m):
"""A failing wait_till_done must not count as finished while the broker is busy."""
eiger = eiger_1_5m
eiger.set_raise_on_missing_packets(False)
with pytest.raises(TimeoutError):
_run_on_complete_wait_till_done_failing(
eiger, BrokerStatus(state="Measuring", message_severity="info", message="")
)
def test_eiger_missing_packet_tolerance_is_switchable_at_runtime(eiger_1_5m):
"""The flag is reachable from the client, so a beamtime can change its mind."""
eiger = eiger_1_5m
+255 -1
View File
@@ -7,7 +7,7 @@ import pytest
from ophyd.utils import LimitError, ReadOnlyError
from csaxs_bec.devices.smargon import SmarGon, SmargopoloController, SmargopoloMotor
from csaxs_bec.devices.smargon.transport import FakeTransport, Mode
from csaxs_bec.devices.smargon.transport import Axis, FakeTransport, Mode
from csaxs_bec.devices.smargon.transport.errors import SmargopoloCommandError, SmargopoloModeError
@@ -266,3 +266,257 @@ def test_monitor_stops_with_the_last_axis_and_can_be_disabled():
off = _motor("sgz", "SHZ", monitor_interval=0)
assert off.controller._monitor_thread is None
off.destroy()
# -- modulo (endless rotation, shortest path) ---------------------------------
def _phi(**cfg):
coord = _coordinator()
sgphi = _motor("sgphi", "PHI", limits=[-180, 180], modulo=360, tolerance=0.01, **cfg)
coord.reference()
return coord, sgphi
def test_modulo_moves_shortest_way_across_the_wrap():
from csaxs_bec.devices.smargon.transport.base import Axis
_, sgphi = _phi()
sgphi.move(170, wait=True)
sgphi.move(-170, wait=True) # +20 through 180, not -340
assert sgphi.controller.transport._positions[Axis.PHI] == pytest.approx(190)
assert sgphi.position == pytest.approx(-170)
assert sgphi.setpoint.get() == pytest.approx(-170)
def test_modulo_request_is_taken_mod_360():
from csaxs_bec.devices.smargon.transport.base import Axis
_, sgphi = _phi()
sgphi.move(350, wait=True) # == -10: short way from 0 is -10
assert sgphi.controller.transport._positions[Axis.PHI] == pytest.approx(-10)
assert sgphi.position == pytest.approx(-10)
sgphi.move(10, wait=True) # +20
assert sgphi.controller.transport._positions[Axis.PHI] == pytest.approx(10)
sgphi.move(370, wait=True) # == 10: no motion
assert sgphi.controller.transport._positions[Axis.PHI] == pytest.approx(10)
def test_modulo_readback_wraps_after_several_turns():
from csaxs_bec.devices.smargon.transport.base import Axis
_, sgphi = _phi()
for target in (120, -120, 0, 120, -120, 0, 120): # always +120
sgphi.move(target, wait=True)
assert sgphi.controller.transport._positions[Axis.PHI] == pytest.approx(840)
assert sgphi.position == pytest.approx(120)
def test_modulo_limit_check_uses_wrapped_value():
_, sgphi = _phi()
sgphi.check_value(350) # == -10, inside [-180, 180]
plain = _motor("sgchi", "CHI", limits=[-180, 180])
with pytest.raises(LimitError):
plain.check_value(350)
def test_modulo_done_check_works_if_server_wraps():
from csaxs_bec.devices.smargon.transport.base import Axis
_, sgphi = _phi()
transport = sgphi.controller.transport
raw_get = transport.get_position
def wrapped_get(axis):
value = raw_get(axis)
return ((value + 180) % 360) - 180 if Axis(axis) is Axis.PHI else value
transport.get_position = wrapped_get
sgphi.move(170, wait=True)
st = sgphi.move(-170, wait=True) # raw target 190, server reports -170
assert st.success and sgphi.position == pytest.approx(-170)
def test_modulo_move_scs_takes_shortest_way():
from csaxs_bec.devices.smargon.transport.base import Axis
coord, sgphi = _phi()
coord.move_scs(PHI=170, wait=True)
coord.move_scs(PHI=-170, wait=True)
assert sgphi.controller.transport._positions[Axis.PHI] == pytest.approx(190)
assert sgphi.position == pytest.approx(-170)
def test_modulo_monitor_does_not_republish_wrapped_position():
import time
from csaxs_bec.devices.smargon.transport.base import Axis
_, sgphi = _phi(monitor_interval=0.02)
sgphi.controller.transport._positions[Axis.PHI] = 370.0 # raw beyond the window
assert _wait_for(lambda: sgphi.readback.get() == pytest.approx(10))
published = []
sgphi.subscribe(lambda value, **_: published.append(value), event_type="readback", run=False)
time.sleep(0.15)
assert published == []
sgphi.destroy()
# -- O-vector (OX/OY/OZ) motors ----------------------------------------------
@pytest.mark.parametrize("axis", ["OX", "OY", "OZ"])
def test_o_vector_axes_are_mm_motors(axis):
m = _motor(f"sgo{axis[1].lower()}", axis)
assert m.egu == "mm"
assert m.limits == (0.0, 0.0) # unbounded unless configured
def test_o_vector_initial_readback_and_record():
sgoz = _motor("sgoz", "OZ")
assert sgoz.position == pytest.approx(180.0) # fake's home O-vector
assert sgoz.read()["sgoz"]["value"] == pytest.approx(180.0)
def test_o_vector_move_and_limits():
coord = _coordinator()
sgox = _motor("sgox", "OX", limits=[-1, 1])
sgoz = _motor("sgoz", "OZ")
coord.reference()
sgox.move(0.25, wait=True)
sgoz.move(200.0, wait=True)
assert sgox.position == pytest.approx(0.25)
assert sgoz.position == pytest.approx(200.0)
with pytest.raises(LimitError):
sgox.move(5.0)
def test_o_vector_move_refused_until_referenced():
sgoy = _motor("sgoy", "OY")
with pytest.raises(SmargopoloModeError):
sgoy.move(0.1)
def test_move_scs_includes_o_vector():
coord = _coordinator()
sgx = _motor("sgx", "SHX")
sgoy = _motor("sgoy", "OY", limits=[-1, 1])
coord.reference()
coord.move_scs(SHX=0.1, OY=-0.4, wait=True)
assert sgx.position == pytest.approx(0.1)
assert sgoy.position == pytest.approx(-0.4)
with pytest.raises(LimitError):
coord.move_scs(OY=3.0)
def test_stop_all_and_o_motor_stop_leave_o_vector_untouched():
coord = _coordinator()
sgox = _motor("sgox", "OX")
coord.reference()
transport = coord.controller.transport
transport._targets[Axis.OX] = 2.0
coord.stop_all()
sgox.stop()
assert transport._targets[Axis.OX] == pytest.approx(2.0)
assert sgox.motor_is_moving.get() == 0
# -- stop: only the moving axes are retargeted ---------------------------------
def _spy_stop(controller):
"""Record the axes passed to transport.stop()."""
calls = []
original = controller.transport.stop
def spy(axes=None):
calls.append(None if axes is None else sorted(a.value for a in axes))
return original(axes)
controller.transport.stop = spy
return calls
def test_stop_of_idle_axes_does_not_touch_the_targets():
coord = _coordinator()
sgx = _motor("sgx", "SHX")
sgchi = _motor("sgchi", "CHI")
coord.reference()
sgx.move(0.5, wait=True)
calls = _spy_stop(coord.controller)
sgx.stop()
sgchi.stop()
coord.stop() # scan abort: the coordinator is in the stop list
assert calls == []
assert coord.controller.active_moves() == {}
def test_coordinator_stop_halts_only_the_moving_axis():
from csaxs_bec.devices.smargon.transport.base import Axis
coord = _coordinator(gradual_motion=True)
sgx = _motor("sgx", "SHX", gradual_motion=True)
_motor("sgchi", "CHI", gradual_motion=True)
coord.reference()
targets_before = dict(coord.controller.transport._targets)
calls = _spy_stop(coord.controller)
st = sgx.set(1e6) # far target: stays in flight
coord.stop()
assert calls == [["SHX"]]
with pytest.raises(RuntimeError, match="interrupted by stop"):
st.wait(timeout=5)
targets = coord.controller.transport._targets
assert targets[Axis.SHX] != 1e6
assert {a: v for a, v in targets.items() if a is not Axis.SHX} == {
a: v for a, v in targets_before.items() if a is not Axis.SHX
}
assert sgx.motor_is_moving.get() == 0
def test_motor_stop_halts_its_own_move_only():
coord = _coordinator(gradual_motion=True)
sgx = _motor("sgx", "SHX", gradual_motion=True)
sgy = _motor("sgy", "SHY", gradual_motion=True)
coord.reference()
calls = _spy_stop(coord.controller)
st_x = sgx.set(1e6)
st_y = sgy.set(1e6)
sgx.stop()
assert calls == [["SHX"]]
with pytest.raises(RuntimeError):
st_x.wait(timeout=5)
assert not st_y.done
sgy.stop()
assert calls == [["SHX"], ["SHY"]]
def test_finished_move_scs_without_wait_is_not_retargeted():
coord = _coordinator()
_motor("sgx", "SHX")
coord.reference()
coord.move_scs(SHX=0.3, wait=False) # instant in the non-gradual fake
calls = _spy_stop(coord.controller)
coord.stop()
assert calls == []
assert coord.controller.active_moves() == {}
def test_stop_all_still_retargets_every_axis():
coord = _coordinator()
coord.reference()
calls = _spy_stop(coord.controller)
coord.stop_all()
assert calls == [None]
def test_stop_of_a_moving_o_motor_ends_the_wait_without_retargeting():
coord = _coordinator(gradual_motion=True)
sgox = _motor("sgox", "OX", gradual_motion=True)
coord.reference()
calls = _spy_stop(coord.controller)
st = sgox.set(1e6)
assert coord.controller.stop_moving() == []
assert calls == []
with pytest.raises(RuntimeError, match="interrupted by stop"):
st.wait(timeout=5)
assert sgox.motor_is_moving.get() == 0
@@ -80,3 +80,48 @@ def test_gradual_motion_advances_over_time():
assert t.get_position(Axis.SHX) == pytest.approx(50.0)
clock["t"] = 5.0
assert t.get_position(Axis.SHX) == pytest.approx(100.0)
# -- stop leaves the O-vector alone -----------------------------------------
class _RecordingRest:
"""A RestTransport with HTTP replaced: canned readback, PUTs recorded."""
def __new__(cls):
from csaxs_bec.devices.smargon.transport import RestTransport
t = RestTransport.__new__(RestTransport)
t.puts = []
readback = {a.value: float(i) for i, a in enumerate(Axis)}
t._get = lambda resource: dict(readback)
t._put = lambda resource, params: t.puts.append((resource, dict(params))) or {}
return t
def test_rest_stop_all_never_writes_o_vector():
t = _RecordingRest()
t.stop(None)
[(resource, params)] = t.puts
assert resource == "targetSCS"
assert not {"OX", "OY", "OZ"} & set(params)
assert {"SHX", "SHY", "SHZ", "CHI", "PHI"} <= set(params)
def test_rest_stop_of_o_axis_sends_nothing():
t = _RecordingRest()
t.stop([Axis.OX, Axis.OZ])
assert t.puts == []
def test_rest_stop_mixed_axes_keeps_only_non_o():
t = _RecordingRest()
t.stop([Axis.SHX, Axis.OY])
assert t.puts == [("targetSCS", {"SHX": float(list(Axis).index(Axis.SHX))})]
def test_fake_stop_all_leaves_o_targets(transport):
transport.set_mode(Mode.REFERENCING)
transport._targets[Axis.OX] = 1.5 # pending O target, readback still 0
transport.stop(None)
assert transport._targets[Axis.OX] == pytest.approx(1.5)