From 7847b5a98e8e9f102b73b84d3339c674c18cac68 Mon Sep 17 00:00:00 2001 From: appleb_m Date: Wed, 20 May 2026 15:50:16 +0200 Subject: [PATCH] DAQ/GUI: fixed local_contact_panel.py, exception handling for state transition errors, added transition to BEC maintenance mode, and wired or added palce holder functions for local contact panel --- src/aare/daq/daq.py | 86 +++++++++++++++++++--- src/aare/daq/server_exception_handler.py | 14 ++++ src/aare/daq/tellupdater.py | 2 +- src/aare/daq/workflows.py | 3 + src/aare/devices/jfjoch.py | 3 + src/aare/gui/panels/local_contact_panel.py | 14 ++-- src/aare/gui/threads/daq_worker.py | 7 +- 7 files changed, 107 insertions(+), 22 deletions(-) diff --git a/src/aare/daq/daq.py b/src/aare/daq/daq.py index 52451ad4..5429def3 100644 --- a/src/aare/daq/daq.py +++ b/src/aare/daq/daq.py @@ -63,6 +63,8 @@ from aare.devices.mx_lib import clean_filename from aare.common.exception_handler import ( TransformationInvalidException, + StateTransitionFailed, + MaintenanceStateException, LoopCenteringFailed, MountingFailed, WarningTellException, @@ -90,7 +92,7 @@ logger = setup_logger("aareDAQ") class AareDAQ: """ Main Data Acquisition class for the Aare system. - + This class orchestrates interactions between various beamline devices, the Aare database, ML services, and data collection workflows. """ @@ -101,7 +103,7 @@ class AareDAQ: AUTO_RASTER_MAX_IMAGES = 4500 AUTO_RASTER_MIN_CELL_SIZE_MM = 0.005 AUTO_RASTER_SKIP_IF_EXCEED_MAX_IMAGE_THRESHOLD = True - + def __init__(self, cfg: BeamlineConfig, bl: MXBeamline): self.last_time = 0.0 self.__cfg = cfg @@ -137,6 +139,8 @@ class AareDAQ: UnmountingFailed, MagnetPositionSensorErorr, TransformationInvalidException, + StateTransitionFailed, + MaintenanceStateException, DataCollectionException, RasterScanException, ), @@ -192,6 +196,19 @@ class AareDAQ: logger.critical(message) raise CriticalTellException(message) from error + def _ensure_not_in_maintenance(self, *, context: str) -> None: + if self.__cfg.state == BeamlineStateEnum.Maintenance: + raise MaintenanceStateException( + f"Automation cannot continue because beamline is in Maintenance during {context}" + ) + + def _validate_automation_state(self, *, context: str) -> None: + self._ensure_not_in_maintenance(context=context) + if self.__cfg.state == BeamlineStateEnum.Moving: + raise StateTransitionFailed( + f"Automation cannot continue because beamline is still in Moving state during {context}" + ) + def _run_noncritical( self, action: Callable[[], object], @@ -1204,8 +1221,10 @@ class AareDAQ: start = time.perf_counter() self.__cfg.try_set_busy(timeout=300) - self.__set_state(target) - self.__cfg.state_busy = False + try: + self.__set_state(target) + finally: + self.__cfg.state_busy = False end = time.perf_counter() @@ -3163,9 +3182,12 @@ class AareDAQ: sample.pin, sample.sample_name ) - self.__cfg.simulated_detector = True + try: - self.__cfg.try_set_busy(timeout=self.AUTOMATION_BUSY_TIMEOUT_S) # upped tiemout for large grids + self._validate_automation_state(context="automation start") + self.__cfg.try_set_busy(timeout=self.AUTOMATION_BUSY_TIMEOUT_S) + + self._validate_automation_state(context="after acquiring automation busy state") self._set_progress_context( progress, @@ -3177,8 +3199,10 @@ class AareDAQ: mount_error_message = self._last_mount_error_message or "Mount failed" self._mark_progress_failed(progress, WorkflowStateKind.MOUNT, mount_error_message) return self._end_operation(start, DAQOperation.MOUNT, error=True) + self._validate_automation_state(context="after mount") self._mark_progress_success(progress, WorkflowStateKind.MOUNT, "Mount complete") self.__set_state(BeamlineStateEnum.SampleAlignment) + self._validate_automation_state(context="after transition to SampleAlignment") logger.info(f"mounting done at {time.perf_counter() - start}") @@ -3186,6 +3210,7 @@ class AareDAQ: if not self._execute_loop_centering(sample): self._mark_progress_failed(progress, WorkflowStateKind.LOOP_CENTRE, "Centering failed") return self._end_operation(start, DAQOperation.LOOP_CENTERING, error=True) + self._validate_automation_state(context="after loop centering") logger.info(f"Loop Centering done at {time.perf_counter() - start}") @@ -3203,6 +3228,7 @@ class AareDAQ: {"comment": face_detection_result.comment}, ), ) + self._validate_automation_state(context="after face detection") logger.info(f"Face Detection done at {time.perf_counter() - start}") self._mark_progress_success(progress, WorkflowStateKind.LOOP_CENTRE, "Centering complete") @@ -3223,7 +3249,6 @@ class AareDAQ: omega_deg=self.omega, transmission=raster_params.transmission, ) - self.__cfg.simulated_detector = True try: raster_result = self._execute_raster_sequence(raster_grid, auto_center=True) @@ -3262,8 +3287,10 @@ class AareDAQ: self._mark_progress_failed(progress, WorkflowStateKind.RASTER, "Raster failed") return self._end_operation(start, DAQOperation.RASTER, error=True) + self._validate_automation_state(context="after raster") self._mark_progress_success(progress, WorkflowStateKind.RASTER, "Raster complete") self.__set_state(BeamlineStateEnum.DataCollection) + self._validate_automation_state(context="after transition to DataCollection") logger.info(f"Raster scans completed at {time.perf_counter() - start}") @@ -3290,9 +3317,12 @@ class AareDAQ: self._mark_progress_failed(progress, WorkflowStateKind.DATA_COLLECTION, "Collection failed") return self._end_operation(start, DAQOperation.ROTATION, error=True) + self._validate_automation_state(context="after data collection") self._mark_progress_success(progress, WorkflowStateKind.DATA_COLLECTION, "Collection complete") logger.info(f"Rotation scan done at {time.perf_counter() - start}") + self._validate_automation_state(context="automation end") + except BECCommunicationError as e: self._raise_if_critical_bec_error(e, command=getattr(e, "operation", None) or "bec") @@ -3300,6 +3330,29 @@ class AareDAQ: self._raise_if_critical_jfjoch_detector_error(e, command=e.endpoint or "unknown") raise + except (StateTransitionFailed, MaintenanceStateException) as e: + logger.error(f"Critical automation state error: {e}") + if progress.current_step is not None: + current_kind = next( + ( + item.step + for item in progress.steps + if self._step_display_name(item.step) == progress.current_step + ), + WorkflowStateKind.FINAL, + ) + self._mark_progress_failed(progress, current_kind, str(e)) + else: + self._mark_progress_finished(progress, False, str(e)) + + self._handle_operation_error( + operation=DAQOperation.AUTOMATION, + sample=sample, + error=e, + event_type=SampleEventType.FAILED, + ) + raise + except (BeamlineBusyTimeoutException, BeamlineBusyException) as e: time_of_measure = abs(time.perf_counter() - start) @@ -3386,11 +3439,14 @@ class AareDAQ: if target == BeamlineStateEnum.Maintenance: self.__cfg.state = BeamlineStateEnum.Maintenance + logger.warning("Beamline entered Maintenance state during state transition request.") + return elif target == curr_state: logger.debug( f"State already set to {target}", extra={"from_state": curr_state, "to_state": target}, ) + return elif target != curr_state: self.__cfg.state = BeamlineStateEnum.Moving try: @@ -3526,10 +3582,18 @@ class AareDAQ: f"Changing state to maintenance due to error: {e}", extra={"from_state": curr_state, "to_state": target}, ) - self.__cfg.state = BeamlineStateEnum.Maintenance - #TODO check if this is the right thing to do - self.__cfg.state_busy = False - raise + try: + workflows.common2maintenance(self.__devs, self.__cfg) + logger.info("in BEC mainteance") + except Exception as e2: + logger.error(f"failed to go to BEC Maintenance state, motor positions unknown. {e2}") + finally: + self.__cfg.state = BeamlineStateEnum.Maintenance + self.__cfg.state_busy = False + raise StateTransitionFailed( + f"State transition failed: {curr_state} -> {target}. " + f"Beamline moved to Maintenance. Original error: {e}" + ) from e @property def shutter(self) -> bool: diff --git a/src/aare/daq/server_exception_handler.py b/src/aare/daq/server_exception_handler.py index 35853320..e064a013 100644 --- a/src/aare/daq/server_exception_handler.py +++ b/src/aare/daq/server_exception_handler.py @@ -112,6 +112,20 @@ def register_exception_handlers(app) -> None: content=_error_payload(code="TRANSFORMATION_INVALID", message=str(exc)), ) + @app.exception_handler(StateTransitionFailed) + async def state_transition_failed_handler(request: Request, exc: StateTransitionFailed) -> JSONResponse: + return JSONResponse( + status_code=api_status.HTTP_500_INTERNAL_SERVER_ERROR, + content=_error_payload(code="STATE_TRANSITION_FAILED", message=str(exc)), + ) + + @app.exception_handler(MaintenanceStateException) + async def maintenance_state_handler(request: Request, exc: MaintenanceStateException) -> JSONResponse: + return JSONResponse( + status_code=api_status.HTTP_409_CONFLICT, + content=_error_payload(code="MAINTENANCE_STATE", message=str(exc)), + ) + @app.exception_handler(BeamlineBusyException) async def beamline_busy_handler(request: Request, exc: BeamlineBusyException) -> JSONResponse: return JSONResponse( diff --git a/src/aare/daq/tellupdater.py b/src/aare/daq/tellupdater.py index 22da69be..531159c3 100644 --- a/src/aare/daq/tellupdater.py +++ b/src/aare/daq/tellupdater.py @@ -25,7 +25,7 @@ from aare.daq.config import BeamlineConfig from aare.daq.tell_state_machine import advance_tell_state, initial_tell_state from aare.common.beamline import MXBeamline, mx_beamline -logger = setup_logger("aareDAQ") +logger = setup_logger(__name__) # Initialize TELL client and DB wrapper to None so they can be patched in tests tell_client = None diff --git a/src/aare/daq/workflows.py b/src/aare/daq/workflows.py index 50f66463..732f6861 100644 --- a/src/aare/daq/workflows.py +++ b/src/aare/daq/workflows.py @@ -216,6 +216,9 @@ def common2dh(devs: BeamlineDevices, cfg: BeamlineConfig): def dh2sa(devs: BeamlineDevices, cfg: BeamlineConfig): devs.bec_worker.planner.move_to(BeamlineState.SAMPLE_ALIGNMENT) +def common2maintenance(devs: BeamlineDevices, cfg: BeamlineConfig): + devs.bec_worker.planner.move_to(BeamlineState.MAINTENANCE) + if __name__ == "__main__": from aare.common.beamline import mx_beamline import time diff --git a/src/aare/devices/jfjoch.py b/src/aare/devices/jfjoch.py index 0d551a4f..e36919f7 100644 --- a/src/aare/devices/jfjoch.py +++ b/src/aare/devices/jfjoch.py @@ -267,6 +267,9 @@ class JFJochWrapper: endpoint="config_select_detector_get", ) + def take_pedestal(self): + raise NotImplementedError("take_pedestal is not implemented in DAQ through the JFJoch API yet") + def get_diffraction_image(self, image_id: int, wait_between_retries_s: float = 0.1): last_error = None for _ in range(3): diff --git a/src/aare/gui/panels/local_contact_panel.py b/src/aare/gui/panels/local_contact_panel.py index d60c2b92..22f0b0a0 100644 --- a/src/aare/gui/panels/local_contact_panel.py +++ b/src/aare/gui/panels/local_contact_panel.py @@ -23,8 +23,13 @@ from aare.gui.widgets.title_label import TitleLabel logger = setup_logger("aareGUI") - class LocalContactPanel(QFrame): + TAB_RECOVERY = "Recovery" + TAB_TELL = "TELL" + TAB_BEC = "BEC" + TAB_HARDWARE = "Hardware" + TAB_DETECTOR = "Detector" + def __init__(self, *, daq: DAQWorker, parent=None): super().__init__(parent) self._daq = daq @@ -48,7 +53,7 @@ class LocalContactPanel(QFrame): self._tabs = QTabWidget(self) layout.addWidget(self._tabs, 1) - self._tabs.addTab(self._build_recovery_tab(), "Recovery") + self._tabs.addTab(self._build_recovery_tab(), self.TAB_RECOVERY) self._tabs.addTab(self._build_tell_tab(), self.TAB_TELL) self._tabs.addTab(self._build_bec_tab(), self.TAB_BEC) self._tabs.addTab(self._build_hardware_tab(), self.TAB_HARDWARE) @@ -67,11 +72,6 @@ class LocalContactPanel(QFrame): layout = QVBoxLayout(tab) layout.setContentsMargins(0, 0, 0, 0) - self._recovery_panel = RecoveryPanel(daq=self._daq, parent=tab) - layout.addWidget(self._recovery_panel) - - return tab - def _build_tell_tab(self) -> QWidget: tab = QWidget(self) layout = QGridLayout(tab) diff --git a/src/aare/gui/threads/daq_worker.py b/src/aare/gui/threads/daq_worker.py index d44a2e3c..cd00113d 100644 --- a/src/aare/gui/threads/daq_worker.py +++ b/src/aare/gui/threads/daq_worker.py @@ -1277,7 +1277,7 @@ class DAQWorker(QObject): @Slot() def bec_load_user_macros(self): - self._emit_placeholder_local_contact_action("BEC load user macros") + self.generic_post("bec/load_user_macros") @Slot() def initialise_smargon(self): @@ -1285,11 +1285,12 @@ class DAQWorker(QObject): @Slot() def initialise_aerotech(self): - self._emit_placeholder_local_contact_action("Initialise Aerotech") + logger.info("initisalisation does not initisalise aareSCAN but runs homing script") + self.generic_post("aerotech/initialize") @Slot() def detector_take_pedestal(self): - self._emit_placeholder_local_contact_action("Detector take pedestal") + self.generic_post("detector/take_pedestal") @Slot() def initialise_detector(self):