from __future__ import annotations import time import threading from typing import Dict, Iterable, List, Optional, TYPE_CHECKING from qtpy.QtCore import QObject, Signal import squid.logging from control.microcontroller import Microcontroller from control.serial_peripherals import SerialDeviceError from squid.abc import CameraAcquisitionMode, AbstractCamera, LightSourceHold from control.rcm_scan_trigger import ConfocalScanFailedError from control._def import * from control.core.config.utils import apply_confocal_override from control.models import merge_channel_configs if TYPE_CHECKING: from control.models import AcquisitionChannel, IlluminationChannelConfig class LiveController(QObject): # Emitted when live start encounters a non-fatal condition the user should see # (e.g. the Squid laser engine is not yet ready for the requested wavelength). signal_warning = Signal(str) def __init__( self, microscope: "Microscope", # NOTE(imo): Right now, Microscope needs to import LiveController. So we can't properly annotate it here. camera: AbstractCamera, control_illumination: bool = True, use_internal_timer_for_hardware_trigger: bool = True, for_displacement_measurement: bool = False, ): super().__init__() self._log = squid.logging.get_logger(self.__class__.__name__) self.microscope = microscope self.camera: AbstractCamera = camera self.currentConfiguration: Optional[AcquisitionChannel] = None self.trigger_mode: Optional[TriggerMode] = TriggerMode.SOFTWARE # @@@ change to None self.is_live = False # True only for the duration of a single snap(); see should_display_frames(). self._is_snapping = False self.control_illumination = control_illumination self.illumination_on = False self.use_internal_timer_for_hardware_trigger = ( use_internal_timer_for_hardware_trigger # use Timer vs timer in the MCU ) self.for_displacement_measurement = for_displacement_measurement self.fps_trigger = 1 self.timer_trigger_interval = (1.0 / self.fps_trigger) * 1000 self._trigger_skip_count = 0 self._confocal_scan_failed = False # log a confocal-unit trigger failure once, not on every frame self._channel_holds: Dict[str, LightSourceHold] = {} # hold_current_channel(): they follow set_microscope_mode # Live runs on the GUI thread and each TCP client on its own: one lock for making, releasing and moving them self._channel_holds_lock = threading.RLock() self.timer_trigger: Optional[threading.Timer] = None self.trigger_ID = -1 self.fps_real = 0 self.counter = 0 self.timestamp_last = 0 self.enable_channel_auto_filter_switching: bool = True # Confocal mode state - when True, use confocal_override from acquisition configs self._confocal_mode: bool = False # ───────────────────────────────────────────────────────────────────────────── # Illumination config helpers # ───────────────────────────────────────────────────────────────────────────── def _get_illumination_config(self) -> Optional[IlluminationChannelConfig]: """Get the machine's illumination channel configuration.""" return self.microscope.config_repo.get_illumination_config() def _get_illumination_source(self) -> int: """Get the illumination source code for current configuration.""" if not self.currentConfiguration: return 0 ill_config = self._get_illumination_config() if not ill_config: return 0 return self.currentConfiguration.get_illumination_source_code(ill_config) def _get_illumination_wavelength(self) -> Optional[int]: """Get the wavelength for current configuration (None for LED matrix).""" if not self.currentConfiguration: return None ill_config = self._get_illumination_config() if not ill_config: return None return self.currentConfiguration.get_illumination_wavelength(ill_config) def _is_led_matrix(self) -> bool: """Check if current configuration is LED matrix (source code 0-9).""" return 0 <= self._get_illumination_source() < 10 def get_intensity_cap_percent(self, channel_config: Optional["AcquisitionChannel"]) -> float: """Maximum allowed illumination intensity (percent) for a channel. From the illumination channel's max_output (fraction of full scale), except that a channel with a new-format calibration offers the full range: its ceiling is inside the lookup (design §6.2). Unknown channels or missing config fall back to 100%. """ if not channel_config: return 100.0 ill_config = self._get_illumination_config() if not ill_config: return 100.0 max_output_percent = channel_config.get_max_output_percent(ill_config) wavelength = channel_config.get_illumination_wavelength(ill_config) if wavelength is None: return max_output_percent return self.microscope.illumination_controller.get_intensity_cap_percent(wavelength, max_output_percent / 100.0) def get_intensity_description(self, channel_config: Optional["AcquisitionChannel"]) -> Dict[str, object]: """What a channel's intensity % means - power %, DAC % or the light source's own % - for the live controls and the acquisition metadata.""" ill_config = self._get_illumination_config() wavelength = None if channel_config and ill_config: wavelength = channel_config.get_illumination_wavelength(ill_config) if wavelength is None: return {"intensity_unit": "dac_percent"} return self.microscope.illumination_controller.describe_intensity(wavelength) # ───────────────────────────────────────────────────────────────────────────── # Squid laser engine readiness (warn-only) # ───────────────────────────────────────────────────────────────────────────── def _check_laser_engine_warn_only(self) -> None: """Warn (don't block) at Live start if the channel isn't yet ACTIVE.""" engine = getattr(self.microscope.addons, "squid_laser_engine", None) if engine is None: return wavelength = self._get_illumination_wavelength() if wavelength is None: return needed = engine.channel_keys_for_wavelengths([wavelength]) if not needed: return status = engine.get_latest_status() if status is not None and status.is_ready_for(needed): return for k in needed: engine.wake_up(k) self._log.warning(f"Squid laser engine not ready for channel(s) {needed}; live started anyway") self.signal_warning.emit(f"Laser engine warming up (channel {','.join(needed)}); image may be dim") # ───────────────────────────────────────────────────────────────────────────── # Declared use of the light source (IlluminationController.use) # ───────────────────────────────────────────────────────────────────────────── def _current_wavelengths(self) -> List[int]: """The current channel's wavelength; [] for a channel without one (LED matrix).""" wavelength = self._get_illumination_wavelength() return [] if wavelength is None else [wavelength] def use_current_channel(self, name: str) -> LightSourceHold: """`name` images with the current channel until the hold is released (or its `with` ends). The light source acts on it: laser engine v2 wakes the line, keeps the 560 from idling off and opens its mechanical shutter. Does nothing on a controller that does not drive the illumination (the laser AF camera's).""" if not self.control_illumination: return LightSourceHold() return self.microscope.illumination_controller.use(name, self._current_wavelengths()) def use_channels(self, name: str, configurations: Iterable["AcquisitionChannel"]) -> LightSourceHold: """As use_current_channel, for every channel in `configurations` (e.g. tracking's).""" if not self.control_illumination: return LightSourceHold() ill_config = self._get_illumination_config() wavelengths = [] for configuration in configurations if ill_config is not None else []: wavelength = configuration.get_illumination_wavelength(ill_config) if wavelength is not None: wavelengths.append(wavelength) return self.microscope.illumination_controller.use(name, wavelengths) def hold_current_channel(self, name: str) -> None: """Hold the current channel for `name` (live, the TCP illumination commands) until release_current_channel(name). set_microscope_mode moves the hold to each new channel, so it never stays on an old one.""" with self._channel_holds_lock: # two clients at once must not both make one: the orphan would never be released if name not in self._channel_holds: self._channel_holds[name] = self.use_current_channel(name) def release_current_channel(self, name: str) -> None: with self._channel_holds_lock: hold = self._channel_holds.pop(name, None) if hold is not None: hold.release() # ───────────────────────────────────────────────────────────────────────────── # Confocal mode # ───────────────────────────────────────────────────────────────────────────── def toggle_confocal_widefield(self, confocal: bool) -> None: """Toggle between confocal and widefield modes. This only updates the internal state. Hardware control (spinning disk position) should be handled separately by the microscope or widget. Args: confocal: Whether to enable confocal mode """ self._confocal_mode = bool(confocal) self._log.info(f"Imaging mode set to: {'confocal' if self._confocal_mode else 'widefield'}") def is_confocal_mode(self) -> bool: """Check if currently in confocal mode.""" return self._confocal_mode def sync_confocal_mode_from_hardware(self, confocal: bool) -> None: """Sync confocal mode state from hardware. Called during initialization to sync state with actual hardware position. """ self.toggle_confocal_widefield(confocal) # ───────────────────────────────────────────────────────────────────────────── # Channel configuration access # ───────────────────────────────────────────────────────────────────────────── def get_channels(self, objective: str) -> List["AcquisitionChannel"]: """Get acquisition channels for an objective, with confocal mode applied. This method provides channels with the current confocal_mode state applied. It uses ConfigRepository for config I/O and applies confocal overrides based on this controller's confocal_mode state. Args: objective: Objective name (e.g., "10x", "20x") Returns: List of AcquisitionChannel objects with confocal overrides applied if in confocal mode. Returns empty list if no profile is set or no configs are available. """ config_repo = self.microscope.config_repo # Check if a profile is set if config_repo.current_profile is None: self._log.warning("get_channels() returning empty list: no profile is set") return [] # Get general config (shared settings) general = config_repo.get_general_config() if not general: self._log.warning( f"get_channels() returning empty list: no general config for profile '{config_repo.current_profile}'" ) return [] # Get objective-specific config obj_config = config_repo.get_objective_config(objective) # Merge configs (if no objective config, use general channels) if obj_config: channels = merge_channel_configs(general, obj_config) else: channels = list(general.channels) # Filter to only enabled channels channels = [ch for ch in channels if ch.enabled] # Apply confocal mode if active return apply_confocal_override(channels, self._confocal_mode) def get_channel_by_name(self, objective: str, name: str) -> Optional["AcquisitionChannel"]: """Get a specific channel by name. Args: objective: Objective name name: Channel name to find Returns: AcquisitionChannel if found, None otherwise """ channels = self.get_channels(objective) return next((ch for ch in channels if ch.name == name), None) # ───────────────────────────────────────────────────────────────────────────── # Illumination control # ───────────────────────────────────────────────────────────────────────────── def turn_on_illumination(self): if not self._is_led_matrix(): wavelength = self._get_illumination_wavelength() if wavelength: self.microscope.illumination_controller.turn_on_illumination(wavelength) elif self.microscope.addons.sci_microscopy_led_array and self._is_led_matrix(): self.microscope.addons.sci_microscopy_led_array.turn_on_illumination() # LED matrix without SciMicroscopy array else: self.microscope.low_level_drivers.microcontroller.turn_on_illumination() self.illumination_on = True def turn_off_illumination(self): if not self._is_led_matrix(): wavelength = self._get_illumination_wavelength() if wavelength: self.microscope.illumination_controller.turn_off_illumination(wavelength) else: self._log.warning( f"turn_off_illumination() skipped - no wavelength configured for " f"'{self.currentConfiguration.name if self.currentConfiguration else 'None'}'" ) elif self.microscope.addons.sci_microscopy_led_array and self._is_led_matrix(): self.microscope.addons.sci_microscopy_led_array.turn_off_illumination() # LED matrix without SciMicroscopy array else: self.microscope.low_level_drivers.microcontroller.turn_off_illumination() self.illumination_on = False def update_illumination(self): if self.currentConfiguration is None: self._log.warning("update_illumination() called with no currentConfiguration") return illumination_source = self._get_illumination_source() intensity = self.currentConfiguration.illumination_intensity intensity_cap = self.get_intensity_cap_percent(self.currentConfiguration) if intensity > intensity_cap: self._log.warning( f"Clamping illumination intensity for '{self.currentConfiguration.name}' from " f"{intensity}% to {intensity_cap}% (channel max output)" ) intensity = intensity_cap if self._is_led_matrix(): if self.microscope.addons.sci_microscopy_led_array: # set color based on channel name led_array = self.microscope.addons.sci_microscopy_led_array name = self.currentConfiguration.name if "BF LED matrix full_R" in name: led_colors = (1, 0, 0) elif "BF LED matrix full_G" in name: led_colors = (0, 1, 0) elif "BF LED matrix full_B" in name: led_colors = (0, 0, 1) else: led_colors = SCIMICROSCOPY_LED_ARRAY_DEFAULT_COLOR # set mode based on channel name if "BF LED matrix left half" in name: led_mode = "dpc.l" elif "BF LED matrix right half" in name: led_mode = "dpc.r" elif "BF LED matrix top half" in name: led_mode = "dpc.t" elif "BF LED matrix bottom half" in name: led_mode = "dpc.b" elif "BF LED matrix full" in name: led_mode = "bf" elif "DF LED matrix" in name: led_mode = "df" else: self._log.warning("Unknown configuration name, using default mode 'bf'.") led_mode = "bf" led_array.set_color(led_colors) led_array.set_brightness(intensity) led_array.set_illumination(led_mode) else: micro: Microcontroller = self.microscope.low_level_drivers.microcontroller name = self.currentConfiguration.name if "BF LED matrix full_R" in name: micro.set_illumination_led_matrix(illumination_source, r=(intensity / 100), g=0, b=0) elif "BF LED matrix full_G" in name: micro.set_illumination_led_matrix(illumination_source, r=0, g=(intensity / 100), b=0) elif "BF LED matrix full_B" in name: micro.set_illumination_led_matrix(illumination_source, r=0, g=0, b=(intensity / 100)) else: micro.set_illumination_led_matrix( illumination_source, r=(intensity / 100) * LED_MATRIX_R_FACTOR, g=(intensity / 100) * LED_MATRIX_G_FACTOR, b=(intensity / 100) * LED_MATRIX_B_FACTOR, ) else: # Laser/fluorescence illumination wavelength = self._get_illumination_wavelength() if wavelength: self.microscope.illumination_controller.set_intensity(wavelength, intensity) if self.microscope.addons.nl5 and NL5_USE_DOUT: self.microscope.addons.nl5.set_active_channel(NL5_WAVENLENGTH_MAP[wavelength]) if NL5_USE_AOUT: self.microscope.addons.nl5.set_laser_power(NL5_WAVENLENGTH_MAP[wavelength], int(intensity)) if self.microscope.addons.cellx and ENABLE_CELLX: self.microscope.addons.cellx.set_laser_power(NL5_WAVENLENGTH_MAP[wavelength], int(intensity)) # set emission filter position and iris values if ENABLE_SPINNING_DISK_CONFOCAL and self.microscope.addons.xlight and not USE_DRAGONFLY: try: if self.currentConfiguration.emission_filter_position: self.microscope.addons.xlight.set_emission_filter( self.currentConfiguration.emission_filter_position, extraction=False, validate=XLIGHT_VALIDATE_WHEEL_POS, ) except Exception as e: self._log.warning(f"Not setting emission filter position: {e}") # Apply per-channel iris values. A channel without its own value gets the default, which # is what the confocal widget shows for it. hw_settings = self.currentConfiguration.confocal_hardware_settings xlight = self.microscope.addons.xlight if xlight.has_illumination_iris_diaphragm: iris_val = getattr(hw_settings, "illumination_iris", None) try: xlight.set_illumination_iris( int(iris_val if iris_val is not None else XLIGHT_ILLUMINATION_IRIS_DEFAULT) ) except (OSError, ValueError, SerialDeviceError) as e: self._log.error(f"Not setting illumination iris: {e}") if xlight.has_emission_iris_diaphragm: iris_val = getattr(hw_settings, "emission_iris", None) try: xlight.set_emission_iris(int(iris_val if iris_val is not None else XLIGHT_EMISSION_IRIS_DEFAULT)) except (OSError, ValueError, SerialDeviceError) as e: self._log.error(f"Not setting emission iris: {e}") elif ENABLE_SPINNING_DISK_CONFOCAL and USE_DRAGONFLY and self.microscope.addons.dragonfly: try: if self.currentConfiguration.emission_filter_position: # The channel's filter position applies to the wheel on the port the camera is on self.microscope.addons.dragonfly.set_emission_filter( self.microscope.addons.dragonfly.get_camera_port(), self.currentConfiguration.emission_filter_position, ) except Exception as e: self._log.warning(f"Not setting emission filter position: {e}") if self.microscope.addons.emission_filter_wheel and self.enable_channel_auto_filter_switching: try: if self.trigger_mode == TriggerMode.SOFTWARE: self.microscope.addons.emission_filter_wheel.set_delay_offset_ms(0) elif self.trigger_mode == TriggerMode.HARDWARE: self.microscope.addons.emission_filter_wheel.set_delay_offset_ms(-self.camera.get_strobe_time()) # The channel's position applies to the first configured wheel (EMISSION_FILTER_WHEEL_INDICES), # which is not always index 1: an Optospin wheel may sit on rotor port 2. wheel = self.microscope.addons.emission_filter_wheel if wheel.available_filter_wheels: wheel.set_filter_wheel_position( {wheel.available_filter_wheels[0]: self.currentConfiguration.emission_filter_position} ) except Exception as e: self._log.warning(f"Not setting emission filter position: {e}") def start_live(self): self._check_laser_engine_warn_only() self.hold_current_channel("live") self.is_live = True self.camera.start_streaming() if self.trigger_mode == TriggerMode.SOFTWARE or ( self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger ): self.camera.enable_callbacks(True) # in case it's disabled e.g. by the laser AF controller self._start_triggerred_acquisition() elif self.trigger_mode == TriggerMode.CONTINUOUS: # Continuous mode has no trigger_acquisition() loop to turn on the # illumination, so do it here. stop_live() already turns it off # symmetrically. if self.control_illumination and not self.illumination_on: self.turn_on_illumination() # if controlling the laser displacement measurement camera if self.for_displacement_measurement: self.microscope.low_level_drivers.microcontroller.set_pin_level(MCU_PINS.AF_LASER, 1) def stop_live(self): self._confocal_scan_failed = False if self.is_live: self.is_live = False if self.trigger_mode == TriggerMode.SOFTWARE: self._stop_triggerred_acquisition() if self.trigger_mode == TriggerMode.CONTINUOUS: self.camera.stop_streaming() if (self.trigger_mode == TriggerMode.SOFTWARE) or ( self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger ): self._stop_triggerred_acquisition() if self.control_illumination: self.turn_off_illumination() self.release_current_channel("live") # if controlling the laser displacement measurement camera if self.for_displacement_measurement: self.microscope.low_level_drivers.microcontroller.set_pin_level(MCU_PINS.AF_LASER, 0) def snap(self): """Acquire exactly one frame using the current live configuration. Same trigger/illumination path as live, but the illumination is turned off as soon as the frame has been read, so a light-sensitive sample only sees a single exposure instead of a free-running stream. The frame reaches the display through the normal camera callbacks. Does nothing while live is running - the sample is already being exposed. Returns True if a frame was captured. """ if self.is_live: self._log.debug("snap() called while live is running, ignoring.") return False # Same wedge-avoidance as trigger_acquisition(): never fire a trigger while # the MCU is mid-command. A stage move finishes well within this wait. try: self.microscope.low_level_drivers.microcontroller.wait_till_operation_is_completed() except TimeoutError: self._log.warning("Microcontroller still busy; not snapping.") return False self._check_laser_engine_warn_only() was_streaming = self.camera.get_is_streaming() if not was_streaming: self.camera.start_streaming() # Callbacks may be disabled e.g. by the laser AF controller; the snapped frame # reaches the display through them, so enable them for the duration of the snap. callbacks_were_enabled = self.camera.get_callbacks_enabled() self.camera.enable_callbacks(True) if self.for_displacement_measurement: self.microscope.low_level_drivers.microcontroller.set_pin_level(MCU_PINS.AF_LASER, 1) # read_frame() returns as soon as the frame is stored, which can be just # before the callbacks that put it on screen run. This event lets us hold # is_snapping (which gates those callbacks) until they have actually run. frame_propagated = threading.Event() callback_id = self.camera.add_frame_callback(lambda _frame: frame_propagated.set()) self._is_snapping = True got_frame = False snap_hold = self.use_current_channel("snap") try: # In HARDWARE mode the microcontroller strobes the illumination for the # exposure, so don't also turn it on here. In CONTINUOUS mode it stays on # for one frame period plus whatever is left of the in-flight frame, i.e. # up to two exposures worth of light. if self.trigger_mode != TriggerMode.HARDWARE and self.control_illumination and not self.illumination_on: self.turn_on_illumination() # CONTINUOUS free-runs, so there is no trigger to send. if self.trigger_mode in (TriggerMode.HARDWARE, TriggerMode.SOFTWARE): self.trigger_ID = self.trigger_ID + 1 try: self.camera.send_trigger(self.camera.get_exposure_time()) except ConfocalScanFailedError as e: self._log.error(f"Snap: {e}") return False got_frame = self.camera.read_frame() is not None if not got_frame: self._log.warning("Snap timed out waiting for a frame.") return got_frame finally: # Light off first, then let the frame finish its trip to the display. if self.control_illumination and self.illumination_on: self.turn_off_illumination() snap_hold.release() if self.for_displacement_measurement: self.microscope.low_level_drivers.microcontroller.set_pin_level(MCU_PINS.AF_LASER, 0) if got_frame: frame_propagated.wait(1.0) self.camera.remove_frame_callback(callback_id) self.camera.enable_callbacks(callbacks_were_enabled) self._is_snapping = False if not was_streaming: self.camera.stop_streaming() @property def is_snapping(self) -> bool: """True only while snap() is acquiring its single frame.""" return self._is_snapping def should_display_frames(self) -> bool: """True when camera frames are meant to reach the display (live or snap).""" return self.is_live or self._is_snapping def _trigger_acquisition_timer_fn(self): trigger_start = time.monotonic() triggered = self.trigger_acquisition() if not self.is_live: return if triggered: # The live FPS is a trigger rate, so the interval runs from the start of this trigger. A trigger can # block for a whole frame (a confocal scan on NL5/AION takes ~90 ms), and waiting the full interval # after it returned gave about half the set rate. elapsed_ms = (time.monotonic() - trigger_start) * 1000 self._start_new_timer(maybe_custom_interval_ms=max(0.0, self.timer_trigger_interval - elapsed_ms)) elif self.microscope.low_level_drivers.microcontroller.is_busy(): # A busy MCU (a stage move) resolves on a 100 ms-to-seconds scale, and every # re-check spins up a fresh Timer thread: poll at frame cadence, not every 10 ms. self._start_new_timer() else: self._start_new_timer(maybe_custom_interval_ms=10) # camera not ready yet: retry soon # software trigger related def trigger_acquisition(self): if self.microscope.low_level_drivers.microcontroller.is_busy(): # Don't trigger while the MCU executes a command (usually a stage move): # triggering mid-command corrupts the firmware's single command-status # slot and wedges it - the firmware keeps executing commands but reports # IN_PROGRESS for everything until the trigger stream stops for a few # seconds. Callers must treat False as "not triggered"; the live trigger # timer re-checks on its own schedule, so live resumes after the move. return False if not self.camera.get_ready_for_trigger(): # TODO(imo): Before, send_trigger would pass silently for this case. Now # we do the same here. Should this warn? I didn't add a warning because it seems like # we over-trigger as standard practice (eg: we trigger at our exposure time frequency, but # the cameras can't give us images that fast so we essentially always have at least 1 skipped trigger) self._trigger_skip_count += 1 if self._trigger_skip_count % 100 == 1: self._log.debug( f"Not ready for trigger, skipping (_trigger_skip_count={self._trigger_skip_count}, total frame time = {self.camera.get_total_frame_time()} [ms])." ) return False self._trigger_skip_count = 0 if self.trigger_mode == TriggerMode.SOFTWARE and self.control_illumination: if not self.illumination_on: self.turn_on_illumination() self.trigger_ID = self.trigger_ID + 1 try: self.camera.send_trigger(self.camera.get_exposure_time()) except ConfocalScanFailedError as e: # Keep live view going (the timer only reschedules when this returns) and say why it is blank. if not self._confocal_scan_failed: self._log.error(f"Live view: {e}") self._confocal_scan_failed = True return True if self._confocal_scan_failed: self._log.info("Live view: confocal triggering works again") self._confocal_scan_failed = False if self.trigger_mode == TriggerMode.SOFTWARE: if self.control_illumination and self.illumination_on == False: self.turn_on_illumination() return True def _stop_existing_timer(self): if self.timer_trigger and self.timer_trigger.is_alive(): self.timer_trigger.cancel() self.timer_trigger = None def _start_new_timer(self, maybe_custom_interval_ms=None): self._stop_existing_timer() if maybe_custom_interval_ms is not None: interval_s = maybe_custom_interval_ms / 1000.0 else: interval_s = self.timer_trigger_interval / 1000.0 self.timer_trigger = threading.Timer(interval_s, self._trigger_acquisition_timer_fn) self.timer_trigger.daemon = True self.timer_trigger.start() def _start_triggerred_acquisition(self): self._start_new_timer() def _set_trigger_fps(self, fps_trigger): if fps_trigger <= 0: raise ValueError(f"fps_trigger must be > 0, but {fps_trigger=}") self._log.debug(f"Setting {fps_trigger=}") self.fps_trigger = fps_trigger self.timer_trigger_interval = (1 / self.fps_trigger) * 1000 if self.is_live: self._start_new_timer() def _stop_triggerred_acquisition(self): self._stop_existing_timer() # trigger mode and settings def set_trigger_mode(self, mode): self._confocal_scan_failed = False if mode == TriggerMode.SOFTWARE: if self.is_live and ( self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger ): self._stop_triggerred_acquisition() self.camera.set_acquisition_mode(CameraAcquisitionMode.SOFTWARE_TRIGGER) if self.is_live: self._start_triggerred_acquisition() self.microscope.low_level_drivers.microcontroller.set_trigger_mode(0) if mode == TriggerMode.HARDWARE: if self.trigger_mode == TriggerMode.SOFTWARE and self.is_live: self._stop_triggerred_acquisition() self.camera.set_acquisition_mode(CameraAcquisitionMode.HARDWARE_TRIGGER) self.camera.set_exposure_time(self.currentConfiguration.exposure_time) if self.is_live and self.use_internal_timer_for_hardware_trigger: self._start_triggerred_acquisition() self.microscope.low_level_drivers.microcontroller.set_trigger_mode(HARDWARE_TRIGGER_MODE) if mode == TriggerMode.CONTINUOUS: if (self.trigger_mode == TriggerMode.SOFTWARE) or ( self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger ): self._stop_triggerred_acquisition() self.camera.set_acquisition_mode(CameraAcquisitionMode.CONTINUOUS) self.microscope.low_level_drivers.microcontroller.set_trigger_mode(0) self.trigger_mode = mode def set_trigger_fps(self, fps): if (self.trigger_mode == TriggerMode.SOFTWARE) or ( self.trigger_mode == TriggerMode.HARDWARE and self.use_internal_timer_for_hardware_trigger ): self._set_trigger_fps(fps) # set microscope mode def set_microscope_mode(self, configuration: "AcquisitionChannel"): if configuration is None: self._log.error("set_microscope_mode() called with None configuration - this is a bug in the caller") return self._log.info("setting microscope mode to " + configuration.name) # temporarily stop live while changing mode if self.is_live is True: self._stop_existing_timer() if self.control_illumination: # Turn off illumination BEFORE switching self.currentConfiguration. # turn_off_illumination() reads self.currentConfiguration to determine which # laser wavelength to turn off. If we switch first, we'd turn off the NEW # channel's laser instead of the OLD channel's laser (which is still on). self.turn_off_illumination() self.currentConfiguration = configuration # set camera exposure time and analog gain self.camera.set_exposure_time(self.currentConfiguration.exposure_time) try: self.camera.set_analog_gain(self.currentConfiguration.analog_gain) except NotImplementedError: pass # set illumination if self.control_illumination: self.update_illumination() # every hold on the current channel (live, the TCP illumination commands) moves to the new one, live or not with self._channel_holds_lock: for hold in self._channel_holds.values(): hold.update(self._current_wavelengths()) # restart live if self.is_live is True: if self.control_illumination: # as at Live start: an unchanged intensity reaches no light source, so a laser engine line that went # off meanwhile (the 560 idle-off, Sleep all) is woken here self._check_laser_engine_warn_only() self.turn_on_illumination() self._start_new_timer() self._log.info("Done setting microscope mode.") def get_trigger_mode(self): return self.trigger_mode # slot def on_new_frame(self): if self.fps_trigger <= 5: if self.control_illumination and self.illumination_on == True: self.turn_off_illumination()