import abc import enum import random import struct import threading import time from abc import abstractmethod from typing import Callable, Optional, Tuple import numpy as np import serial import serial.tools.list_ports from crc import CrcCalculator, Crc8 from serial.serialutil import SerialException import squid.logging import control._def from control.startup_homing import ( CONFIG_SIGNATURE_FORMAT, config_signature, require_objective_lowered, required_homed_axes_mask, ) from control._def import * # add user to the dialout group to avoid the need to use sudo # done (7/20/2021) - remove the time.sleep in all functions (except for __init__) to # make all callable functions nonblocking, instead, user should check use is_busy() to # check if the microcontroller has finished executing the more recent command # We have a few top level functions here, so we have this module level log instance. Classes should make their own! _log = squid.logging.get_logger("microcontroller") # Mapping of execution status bytes to human-readable names for logging _CMD_EXECUTION_STATUS_NAMES = {value: name for name, value in vars(CMD_EXECUTION_STATUS).items() if name.isupper()} # Status byte values of a startup verdict reply (firmware >= STARTUP_STATE_MIN_FIRMWARE): base + StartupVerdict _STARTUP_VERDICT_STATUSES = range(STARTUP_VERDICT_STATUS_BASE, STARTUP_VERDICT_STATUS_BASE + len(StartupVerdict)) _CMD_EXECUTION_STATUS_NAMES.update( {STARTUP_VERDICT_STATUS_BASE + v: f"STARTUP_VERDICT_{v.name}" for v in StartupVerdict} ) # The startup path each verdict leads to, and why: one log line per verdict _STARTUP_VERDICT_LOG = { StartupVerdict.WARM: ( "Controller reports the stage homed, at rest, healthy, same configuration: startup homing skipped" ), StartupVerdict.NO_SIGNATURE: ( "Controller holds no configuration signature (power-up, INITIALIZE, or a setting changed since it was " "stored): normal startup" ), StartupVerdict.SIGNATURE_MISMATCH: "Configuration changed since the controller was homed: normal startup", StartupVerdict.UNHEALTHY: ( "Stage hardware not healthy (motor power dropped, or a stage driver lost its configuration or is disabled): " "normal startup" ), StartupVerdict.MOVING: "Stage still moving: normal startup", StartupVerdict.NOT_HOMED: "Stage not homed since power-up, a zero or a driver disable: normal startup", } # Mapping of command type bytes to human-readable names for logging _CMD_NAMES = { CMD_SET.MOVE_X: "MOVE_X", CMD_SET.MOVE_Y: "MOVE_Y", CMD_SET.MOVE_Z: "MOVE_Z", CMD_SET.MOVE_THETA: "MOVE_THETA", CMD_SET.MOVE_W: "MOVE_W", CMD_SET.MOVE_W2: "MOVE_W2", CMD_SET.HOME_OR_ZERO: "HOME_OR_ZERO", CMD_SET.MOVETO_X: "MOVETO_X", CMD_SET.MOVETO_Y: "MOVETO_Y", CMD_SET.MOVETO_Z: "MOVETO_Z", CMD_SET.SET_LIM: "SET_LIM", CMD_SET.TURN_ON_ILLUMINATION: "TURN_ON_ILLUMINATION", CMD_SET.TURN_OFF_ILLUMINATION: "TURN_OFF_ILLUMINATION", CMD_SET.SET_ILLUMINATION: "SET_ILLUMINATION", CMD_SET.SET_ILLUMINATION_LED_MATRIX: "SET_ILLUMINATION_LED_MATRIX", CMD_SET.ACK_JOYSTICK_BUTTON_PRESSED: "ACK_JOYSTICK_BUTTON_PRESSED", CMD_SET.ANALOG_WRITE_ONBOARD_DAC: "ANALOG_WRITE_ONBOARD_DAC", CMD_SET.SET_DAC80508_REFDIV_GAIN: "SET_DAC80508_REFDIV_GAIN", CMD_SET.SET_ILLUMINATION_INTENSITY_FACTOR: "SET_ILLUMINATION_INTENSITY_FACTOR", CMD_SET.MOVETO_W: "MOVETO_W", CMD_SET.MOVETO_W2: "MOVETO_W2", CMD_SET.SET_LIMIT_SWITCH_CONFIG: "SET_LIMIT_SWITCH_CONFIG", CMD_SET.STORE_CONFIG_SIGNATURE: "STORE_CONFIG_SIGNATURE", CMD_SET.QUERY_STARTUP_STATE: "QUERY_STARTUP_STATE", CMD_SET.CONFIGURE_STEPPER_DRIVER: "CONFIGURE_STEPPER_DRIVER", CMD_SET.SET_MAX_VELOCITY_ACCELERATION: "SET_MAX_VELOCITY_ACCELERATION", CMD_SET.SET_LEAD_SCREW_PITCH: "SET_LEAD_SCREW_PITCH", CMD_SET.SET_OFFSET_VELOCITY: "SET_OFFSET_VELOCITY", CMD_SET.CONFIGURE_STAGE_PID: "CONFIGURE_STAGE_PID", CMD_SET.ENABLE_STAGE_PID: "ENABLE_STAGE_PID", CMD_SET.DISABLE_STAGE_PID: "DISABLE_STAGE_PID", CMD_SET.SET_HOME_SAFETY_MERGIN: "SET_HOME_SAFETY_MERGIN", CMD_SET.SET_PID_ARGUMENTS: "SET_PID_ARGUMENTS", CMD_SET.SEND_HARDWARE_TRIGGER: "SEND_HARDWARE_TRIGGER", CMD_SET.SET_STROBE_DELAY: "SET_STROBE_DELAY", CMD_SET.SET_AXIS_DISABLE_ENABLE: "SET_AXIS_DISABLE_ENABLE", CMD_SET.SET_PIN_LEVEL: "SET_PIN_LEVEL", # Multi-port illumination commands (firmware v1.0+) CMD_SET.SET_PORT_INTENSITY: "SET_PORT_INTENSITY", CMD_SET.TURN_ON_PORT: "TURN_ON_PORT", CMD_SET.TURN_OFF_PORT: "TURN_OFF_PORT", CMD_SET.SET_PORT_ILLUMINATION: "SET_PORT_ILLUMINATION", CMD_SET.SET_MULTI_PORT_MASK: "SET_MULTI_PORT_MASK", CMD_SET.TURN_OFF_ALL_PORTS: "TURN_OFF_ALL_PORTS", CMD_SET.SET_WATCHDOG_TIMEOUT: "SET_WATCHDOG_TIMEOUT", CMD_SET.HEARTBEAT: "HEARTBEAT", CMD_SET.INITFILTERWHEEL: "INITFILTERWHEEL", CMD_SET.INITFILTERWHEEL_W2: "INITFILTERWHEEL_W2", CMD_SET.INITIALIZE: "INITIALIZE", CMD_SET.RESET: "RESET", } # "move backward" if SIGN is 1, "move forward" if SIGN is -1 class HomingDirection(enum.Enum): HOMING_DIRECTION_FORWARD = 0 HOMING_DIRECTION_BACKWARD = 1 def movement_sign_to_homing_direction(sign: int) -> HomingDirection: if sign not in (-1, 1): raise ValueError("Only -1 and 1 are valid movement signs.") return HomingDirection(int((sign + 1) / 2)) _default_x_homing_direction = movement_sign_to_homing_direction(STAGE_MOVEMENT_SIGN_X) _default_y_homing_direction = movement_sign_to_homing_direction(STAGE_MOVEMENT_SIGN_Y) _default_z_homing_direction = movement_sign_to_homing_direction(STAGE_MOVEMENT_SIGN_Z) _default_theta_homing_direction = movement_sign_to_homing_direction(STAGE_MOVEMENT_SIGN_THETA) _default_w_homing_direction = movement_sign_to_homing_direction(STAGE_MOVEMENT_SIGN_W) _default_w2_homing_direction = movement_sign_to_homing_direction(STAGE_MOVEMENT_SIGN_W) # W2 uses same sign as W # to do (7/28/2021) - add functions for configuring the stepper motors class CommandAborted(RuntimeError): """ If we send a command and it needs to abort for any reason (too many retries, timeout waiting for the mcu to acknowledge, etc), the Microcontroller class will throw this for wait and progress check operations until a new command is started. This does mean that if you don't check for command completion, you may miss these errors! `recoverable` is True only when the firmware actively reported the command as failed before acting on it (CMD_EXECUTION_ERROR) — the motor never moved, so a plain resend is safe. It is False for aborts where the motor state is uncertain (ack timeout / checksum failure after retries), which should be recovered by re-homing rather than blindly resending. """ def __init__(self, command_id, reason, recoverable: bool = False): super().__init__(reason) self.command_id = command_id self.recoverable = recoverable class LimitSwitchConfigError(RuntimeError): """The configuration's [LIMIT_SWITCHES] section is invalid, or asks for settings the controller's firmware cannot apply. Raised by the Microcontroller constructor before anything is sent that could move a stage; the controller link is closed by then. """ def decode_z_limits(byte18: int) -> Tuple[bool, bool]: """(left, right) Z limit switch triggered, from status byte 18.""" return bool(byte18 & (1 << BIT_POS_Z_LIMIT_LEFT)), bool(byte18 & (1 << BIT_POS_Z_LIMIT_RIGHT)) # NOTE(imo): We'll want to pull this out into a common serial impl shared with serial_peripheral.py at some point, but # for now ust auto reconnect down at this level. class AbstractCephlaMicroSerial(abc.ABC): def __init__(self): self._log = squid.logging.get_logger(self.__class__.__name__) @abstractmethod def close(self) -> None: """ A noop if already closed. Can throw an IOError for close related errors or invalid states. """ pass @abstractmethod def reset_input_buffer(self) -> bool: """ Reset the input buffer of the serial port. """ pass @abstractmethod def write(self, data: bytearray, reconnect_tries: int = 0) -> int: """ This must raise an IOError or OSError on any io issues, or ValueError if data is not sendable. If reconnect_tries > 0, this will attempt to reconnect if the device isn't connected (up to the number of tries specified, and with exponential backoff. This means that if you specific reconnect_tries=5 and it needs to try 5 times, it may hang for a while!) """ pass @abstractmethod def read(self, count: int = 1, reconnect_tries: int = 0) -> bytes: """ Read up to count bytes, and return them as bytes. Can throw IOError or OSError if the device is in an invalid state, or ValueError if count is not valid. If reconnect_tries > 0, this will attempt to reconnect if the device isn't connected (up to the number of tries specified, and with exponential backoff. This means that if you specific reconnect_tries=5 and it needs to try 5 times, it may hang for a while!) """ pass @abstractmethod def bytes_available(self) -> int: """ Returns the number of bytes in the read buffer ready for immediate reading. If the device is no longer connected or is in an invalid state, this might be None or might throw IOError. """ pass @abstractmethod def is_open(self) -> bool: """ Returns true if the device is open and ready for read/writing, false otherwise. """ pass @abstractmethod def reconnect(self, attempts: int) -> bool: """ Attempts to reconnect, if needed, and returns true if successful. If already connected, this is a noop (and will return True) """ pass class SimSerial(AbstractCephlaMicroSerial): # Number of illumination ports for simulation NUM_ILLUMINATION_PORTS = 16 # Simulated firmware version # v1.0: multi-port illumination support # v1.1: serial watchdog for illumination auto-shutoff # v1.2: CMD_EXECUTION_ERROR reported on failed moves + MOVETO_W2 command # v1.3: strobe ISR latches illumination source at start (race fix for # channel switch during live HW-triggered acquisition) FIRMWARE_VERSION_MAJOR = 1 FIRMWARE_VERSION_MINOR = 3 @staticmethod def response_bytes_for( command_id, execution_status, x, y, z, theta, joystick_button, switch, firmware_version=(1, 3) ) -> bytes: """ - byte 0: command ID (1 byte) - byte 1: execution status (1 byte) - bytes 2-5: X pos (4 bytes) - bytes 6-9: Y pos (4 bytes) - bytes 10-13: Z pos (4 bytes) - bytes 14-17: Theta (4 bytes) - byte 18: buttons and switches (1 byte) - bytes 19-21: reserved (3 bytes) - byte 22: firmware version, nibble-encoded (1 byte) - byte 23: CRC (1 byte) """ crc_calculator = CrcCalculator(Crc8.CCITT, table_based=True) button_state = joystick_button << BIT_POS_JOYSTICK_BUTTON | switch << BIT_POS_SWITCH # Firmware version is nibble-encoded in byte 22 (last byte of reserved section) # High nibble = major version, low nibble = minor version version_byte = (firmware_version[0] << 4) | (firmware_version[1] & 0x0F) reserved_state = version_byte # Byte 22 = version_byte when packed as big-endian int response = bytearray( struct.pack(">BBiiiiBi", command_id, execution_status, x, y, z, theta, button_state, reserved_state) ) response.append(crc_calculator.calculate_checksum(response)) return bytes(response) def __init__(self): super().__init__() # All the public methods must hold this to modify internal state. Any _ prefixed members are # assumed to be called from a context that already holds the lock self._update_lock = threading.Lock() self._in_waiting = 0 self.response_buffer = [] self.x = 0 self.y = 0 self.z = 0 self.theta = 0 self.w = 0 self.w2 = 0 self.joystick_button = False self.switch = False # Multi-port illumination state for simulation self.port_is_on = [False] * SimSerial.NUM_ILLUMINATION_PORTS self.port_intensity = [0] * SimSerial.NUM_ILLUMINATION_PORTS # Serial watchdog (firmware v1.1+) self.watchdog_timeout_ms = DEFAULT_WATCHDOG_TIMEOUT_MS # Legacy illumination state tracking (for backward compatibility) # Maps legacy source codes (11-15) to port indices (0-4) self._illumination_source = None # Currently selected legacy source self._illumination_is_on = False # Legacy global on/off state # Test hooks modelling a controller that stays busy or goes quiet. While hold_in_progress is True, command # responses (and send_status_packet()) carry IN_PROGRESS; while drop_responses is True, commands get no # response (a lost link). self.hold_in_progress = False self.drop_responses = False self._last_command_id = 0 self._closed = False @staticmethod def unpack_position(pos_bytes): return Microcontroller._payload_to_int(pos_bytes, len(pos_bytes)) def _respond_to(self, write_bytes): # NOTE: As we need more and more microcontroller simulator functionality, add # CMD_SET handlers here. Prefer this over adding checks for simulated mode in # the Microcontroller! command_byte = write_bytes[1] # If this is a position related command, these are our position bytes. position_bytes = write_bytes[2:6] if command_byte == CMD_SET.MOVE_X: self.x += self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVE_Y: self.y += self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVE_Z: self.z += self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVE_THETA: self.theta += self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVE_W: self.w += self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVE_W2: self.w2 += self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVETO_X: self.x = self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVETO_Y: self.y = self.unpack_position(position_bytes) elif command_byte == CMD_SET.MOVETO_Z: self.z = self.unpack_position(position_bytes) elif command_byte == CMD_SET.HOME_OR_ZERO: axis = write_bytes[2] # NOTE: write_bytes[3] might indicate that we only want to "ZERO", but # in the simulated case zeroing is the same as homing. So don't check # that here. If we want to simulate the homing motion in the future # we'd need to do that here. if axis == AXIS.X: self.x = 0 elif axis == AXIS.Y: self.y = 0 elif axis == AXIS.Z: self.z = 0 elif axis == AXIS.THETA: self.theta = 0 elif axis == AXIS.XY: self.x = 0 self.y = 0 elif axis == AXIS.W: self.w = 0 elif axis == AXIS.W2: self.w2 = 0 # Multi-port illumination commands elif command_byte == CMD_SET.SET_PORT_INTENSITY: port_index = write_bytes[2] if 0 <= port_index < SimSerial.NUM_ILLUMINATION_PORTS: intensity = (write_bytes[3] << 8) | write_bytes[4] self.port_intensity[port_index] = intensity elif command_byte == CMD_SET.TURN_ON_PORT: port_index = write_bytes[2] if 0 <= port_index < SimSerial.NUM_ILLUMINATION_PORTS: self.port_is_on[port_index] = True elif command_byte == CMD_SET.TURN_OFF_PORT: port_index = write_bytes[2] if 0 <= port_index < SimSerial.NUM_ILLUMINATION_PORTS: self.port_is_on[port_index] = False elif command_byte == CMD_SET.SET_PORT_ILLUMINATION: port_index = write_bytes[2] if 0 <= port_index < SimSerial.NUM_ILLUMINATION_PORTS: intensity = (write_bytes[3] << 8) | write_bytes[4] turn_on = write_bytes[5] != 0 self.port_intensity[port_index] = intensity self.port_is_on[port_index] = turn_on elif command_byte == CMD_SET.SET_MULTI_PORT_MASK: port_mask = (write_bytes[2] << 8) | write_bytes[3] on_mask = (write_bytes[4] << 8) | write_bytes[5] for i in range(SimSerial.NUM_ILLUMINATION_PORTS): if port_mask & (1 << i): self.port_is_on[i] = bool(on_mask & (1 << i)) elif command_byte == CMD_SET.TURN_OFF_ALL_PORTS: for i in range(SimSerial.NUM_ILLUMINATION_PORTS): self.port_is_on[i] = False elif command_byte == CMD_SET.SET_WATCHDOG_TIMEOUT: requested_timeout = (write_bytes[2] << 24) | (write_bytes[3] << 16) | (write_bytes[4] << 8) | write_bytes[5] if requested_timeout > MAX_WATCHDOG_TIMEOUT_MS: requested_timeout = MAX_WATCHDOG_TIMEOUT_MS if requested_timeout == 0: requested_timeout = DEFAULT_WATCHDOG_TIMEOUT_MS self.watchdog_timeout_ms = requested_timeout elif command_byte == CMD_SET.HEARTBEAT: pass # No-op, just triggers a response # Legacy illumination commands - sync with multi-port state elif command_byte == CMD_SET.SET_ILLUMINATION: source = write_bytes[2] intensity = (write_bytes[3] << 8) | write_bytes[4] self._illumination_source = source # Update port intensity for the corresponding port port_index = source_code_to_port_index(source) if 0 <= port_index < SimSerial.NUM_ILLUMINATION_PORTS: self.port_intensity[port_index] = intensity elif command_byte == CMD_SET.TURN_ON_ILLUMINATION: self._illumination_is_on = True # Turn on the currently selected source's port if self._illumination_source is not None: port_index = source_code_to_port_index(self._illumination_source) if 0 <= port_index < SimSerial.NUM_ILLUMINATION_PORTS: self.port_is_on[port_index] = True elif command_byte == CMD_SET.TURN_OFF_ILLUMINATION: self._illumination_is_on = False # Turn off all ports (matches firmware behavior) for i in range(SimSerial.NUM_ILLUMINATION_PORTS): self.port_is_on[i] = False self._last_command_id = write_bytes[0] if not self.drop_responses: self._queue_status_packet() self._update_internal_state() def _queue_status_packet(self): status = ( CMD_EXECUTION_STATUS.IN_PROGRESS if self.hold_in_progress else CMD_EXECUTION_STATUS.COMPLETED_WITHOUT_ERRORS ) self.response_buffer.extend( SimSerial.response_bytes_for( self._last_command_id, status, self.x, self.y, self.z, self.theta, self.joystick_button, self.switch, firmware_version=(SimSerial.FIRMWARE_VERSION_MAJOR, SimSerial.FIRMWARE_VERSION_MINOR), ) ) def send_status_packet(self) -> None: """Queue one status packet, as the firmware sends periodically: the last command's id, the current status.""" with self._update_lock: self._queue_status_packet() self._update_internal_state() def _update_internal_state(self, clear_buffer: bool = False): if clear_buffer: self.response_buffer.clear() self._in_waiting = len(self.response_buffer) def close(self): with self._update_lock: self._closed = True self._update_internal_state(clear_buffer=True) def reset_input_buffer(self) -> bool: with self._update_lock: self._update_internal_state(clear_buffer=True) return True def write(self, data: bytearray, reconnect_tries: int = 0) -> int: # Reconnect takes the lock and checks closed too, so let it handle locking for reconnect if self._closed: if not self.reconnect(reconnect_tries): raise IOError("Closed") with self._update_lock: self._respond_to(data) return len(data) def read(self, count=1, reconnect_tries: int = 0) -> bytes: # Reconnect takes the lock and checks closed too, so let it handle locking for reconnect if self._closed: if not self.reconnect(reconnect_tries): raise IOError("Closed") with self._update_lock: response = bytearray() for i in range(count): if not len(self.response_buffer): break response.append(self.response_buffer.pop(0)) self._update_internal_state() return response def bytes_available(self) -> int: with self._update_lock: self._update_internal_state() return self._in_waiting def is_open(self) -> bool: with self._update_lock: return not self._closed def reconnect(self, attempts: int) -> bool: with self._update_lock: self._update_internal_state() if not attempts: # open takes the lock, so we can't use it. return not self._closed if self._closed: self._log.warning("Reconnect required, succeeded.") self._update_internal_state(clear_buffer=True) self._closed = False return True class MicrocontrollerSerial(AbstractCephlaMicroSerial): INITIAL_RECONNECT_INTERVAL = 0.5 @staticmethod def exponential_backoff_time(attempt_index: int, initial_interval: float) -> float: """ This is the time to sleep before you attempt the attempt_index attempt, where attempt_index is 0 indexed. EG: time.sleep(exponential_backoff_time(0, 0.5)) attempt_0() time.sleep(exponential_backoff_time(1, 0.5)) attempt_1() will have a 0 sleep before attempt_0(), and 0.5 before attempt_1() """ if attempt_index <= 0: return 0.0 else: return initial_interval * 2**attempt_index def __init__(self, port: str, baudrate: int): super().__init__() self._port = port self._baudrate = baudrate self._serial = serial.Serial(port, baudrate) def __del__(self): self.close() def close(self) -> None: return self._serial.close() def reset_input_buffer(self) -> bool: try: self._serial.reset_input_buffer() return True except Exception as e: self._log.exception(f"Failed to clear input buffer: {e}") return False def write(self, data: bytearray, reconnect_tries: int = 0) -> int: # the is_open attribute is unreliable - if a device just recently dropped out, it may not be up to date. # So we just try to write, and if we get an OS error we try to write again but without retrying try: return self._serial.write(data) except (IOError, OSError, SerialException) as e: if reconnect_tries > 0: if not self.reconnect(reconnect_tries): raise return self.write(data, reconnect_tries=0) else: raise def read(self, count: int = 1, reconnect_tries: int = 0) -> bytes: # the is_open attribute is unreliable - if a device just recently dropped out, it may not be up to date. # So we just try to read, and if we get an OS error we try to read again but without retrying try: return self._serial.read(count) except (IOError, OSError, SerialException) as e: if reconnect_tries > 0: if not self.reconnect(reconnect_tries): raise self.read(count, reconnect_tries=0) else: raise def bytes_available(self) -> int: if not self.is_open(): return 0 return self._serial.in_waiting def is_open(self) -> bool: try: if not self._serial.is_open: return False # pyserial is_open is sortof useless - it doesn't force a check to see if the device is still valid. # but the in_waiting does an ioctl to check for the bytes in the read buffer. This is a system call, so # not the best from a performance perspective, but we are operating with 2 mega baud and a system call # is insignificant on that timescale! bytes_avail = self._serial.in_waiting return True except OSError: return False def reconnect(self, attempts: int) -> bool: self._log.debug(f"Attempting reconnect to {self._serial.port}. With max of {attempts} attempts.") for i in range(attempts): this_interval = MicrocontrollerSerial.exponential_backoff_time( i, MicrocontrollerSerial.INITIAL_RECONNECT_INTERVAL ) if not self.is_open(): time.sleep(this_interval) try: try: self._serial.close() except OSError: pass self._serial = serial.Serial(port=self._port, baudrate=self._baudrate) except (IOError, OSError, SerialException) as se: if i + 1 == attempts: self._log.error( f"Reconnect to {self._serial.port} failed after {attempts} attempts. Last reconnect interval was {this_interval} [s]", exc_info=se, ) # This is the last time around the loop, so it'll exit and return self.is_open() as false after this. else: self._log.warning( f"Couldn't reconnect serial={self._serial.port} @ baud={self._serial.baudrate}. Attempt {i + 1}/{attempts}." ) else: break # We print warnings/errors in the loop above, so here we can just return the result of our best efforts! return self.is_open() def get_microcontroller_serial_device( version=None, sn=None, baudrate=2000000, simulated=False ) -> AbstractCephlaMicroSerial: if simulated: return SimSerial() else: _log.info(f"Getting serial device for microcontroller {version=}") if version == "Arduino Due": controller_ports = [ p.device for p in serial.tools.list_ports.comports() if "Arduino Due" == p.description ] # autodetect - based on Deepak's code else: if sn is not None: controller_ports = [p.device for p in serial.tools.list_ports.comports() if sn == p.serial_number] else: if sys.platform == "win32": controller_ports = [ p.device for p in serial.tools.list_ports.comports() if p.manufacturer == "Microsoft" ] else: controller_ports = [ p.device for p in serial.tools.list_ports.comports() if p.manufacturer == "Teensyduino" ] if not controller_ports: raise IOError("no controller found for serial device") if len(controller_ports) > 1: _log.warning("multiple controller found - using the first") return MicrocontrollerSerial(controller_ports[0], baudrate) class Microcontroller: LAST_COMMAND_ACK_TIMEOUT = 0.5 MAX_RETRY_COUNT = 5 MAX_RECONNECT_COUNT = 3 # The micro has an update time it tries to keep to. This must be > that time. As of 2025-04-28, it's 10ms # on the micro. So 0.1 is 10x that. STALE_READ_TIMEOUT = 0.1 # How long _detect_firmware_version waits for the connect handshake to be answered before it gives up. HANDSHAKE_TIMEOUT_S = 5 # How long _detect_firmware_version waits for the connect handshake to settle before it sends its command again # (_take_handshake_answer). The controller answers within a status period or two (10 ms each). The wait doubles # with each resend, up to the maximum: a controller that does not answer is not sent dozens of commands. HANDSHAKE_RESEND_INTERVAL_S = 0.1 HANDSHAKE_RESEND_INTERVAL_MAX_S = 1.0 # The ids _detect_firmware_version picks from when it sends its command again: not the next id, which a counting # byte in the stream could follow, and not 0, 1 or 255, which fill a status packet's other fields. HANDSHAKE_RESEND_CMD_IDS = range(2, 255) # The most bytes _next_status_packet reads before it returns to the reader loop without a packet, so that the # loop can stop, or discard a backlog, even if bytes arrive as fast as they are read. STATUS_STREAM_MAX_BYTES_PER_READ = 256 # After this many bytes without a status packet (20 packets' worth), the reader says the stream is lost. STATUS_STREAM_LOST_AFTER_BYTES = 20 * MicrocontrollerDef.MSG_LENGTH # The most bytes two consecutive status packets may differ in, besides the first (command id) and last (checksum), # for the handshake to take them as two answers to different commands: the status, the low bytes of the # positions of a stage still moving, the switches. Bytes that are not from one stream differ in most places. HANDSHAKE_MAX_BYTES_CHANGED = 8 def __init__(self, serial_device: AbstractCephlaMicroSerial, reset_and_initialize=True): self.log = squid.logging.get_logger(self.__class__.__name__) if not serial_device: raise ValueError("You must pass in an AbstractCephlaSerial device for the microcontroller instance to use.") self._serial = serial_device self._is_simulated = isinstance(serial_device, SimSerial) self.tx_buffer_length = MicrocontrollerDef.CMD_LENGTH self.rx_buffer_length = MicrocontrollerDef.MSG_LENGTH self._cmd_id = 0 self._cmd_id_mcu = None # command id of mcu's last received command self._cmd_execution_status = None self.mcu_cmd_execution_in_progress = False # This is a sentinel/watchdog of sorts. Every time we receive a valid packet from the micro, we update this. # The micro should be sending packets once very ~10 ms, so if we go much longer than that without something # is likely wrong. See def _warn_if_reads_stale() and the read loop. self._last_successful_read_time = time.time() self.x_pos = 0 # unit: microstep or encoder resolution self.y_pos = 0 # unit: microstep or encoder resolution self.z_pos = 0 # unit: microstep or encoder resolution self.w_pos = 0 # unit: microstep or encoder resolution self.theta_pos = 0 # unit: microstep or encoder resolution # Encoder reporting (firmware >= 1.6, set_encoder_reporting). Updated only by packets whose # byte 19 has ENC_FLAG.REPORTING set; they keep their last values otherwise. self.encoder_pos = 0 # ENC_POS of the reported axis, microsteps self.encoder_deviation = 0 # int16 ENC_POS - XACTUAL of that axis, microsteps, clipped self.encoder_flags = 0 # raw status byte 19 while reporting, else 0 # Focus wheel ticks since SET_FOCUS_WHEEL_MODE TO_HOST (wrapping int32); None while the packet carries none. self.focus_wheel_count = None self.button_and_switch_state = 0 self.joystick_button_pressed = 0 # This is used to keep track of whether or not we should emit joystick events to the joystick listeners, # and can be changed with enable_joystick(...) self.joystick_listener_events_enabled = False # This is a list of (id, functions) to call when we get a joystick event. The functions are called # with the new state of the button (True -> pressed, False -> not pressed). # # The id in the tuple is an internally defined unique ID that callers to add_joystick_button_listener() get back, # and which can be used to remove the listener with remove_joystick_button_listener. # # These are called in our busy loop, and so should return immediately! self.joystick_event_listeners = [] self.switch_state = 0 self.z_limit_left_triggered = False self.z_limit_right_triggered = False # Firmware version (major, minor) - detected from response byte 22 # (0, 0) indicates legacy firmware without version reporting self.firmware_version = (0, 0) # Heartbeat thread for serial watchdog keepalive self._heartbeat_thread = None self._heartbeat_stop_event = threading.Event() self._heartbeat_interval_s = None # the running heartbeat's interval; None when none runs # Lock to serialize all outgoing serial commands (heartbeat thread + main thread) self._cmd_lock = threading.Lock() self.last_command = None self.last_command_send_timestamp = time.time() self.last_command_aborted_error = None self.crc_calculator = CrcCalculator(Crc8.CCITT, table_based=True) self.crc_calculator_rx = CrcCalculator(Crc8.CCITT, table_based=True) # the reader thread's own self.retry = 0 self.new_packet_callback_external = None self.terminate_reading_received_packet_thread = False self._received_packet_cv = threading.Condition() # The status stream (see _next_status_packet). The controller sends a status packet every 10 ms with nothing # marking where one starts, so the reader thread keeps the bytes it has read but not used yet, and its place # in them, here. Reader thread only, except where noted. self._rx = bytearray() # The connect handshake (_take_handshake_answer): until a packet answers a command sent on this connection, # no packet is used. The ids of the commands sent so far while it is pending (added under _cmd_lock): self._handshake_cmd_ids = set() # Where _rx starts in the stream: the bytes dropped from its front since the reader started, or last # discarded its input. self._handshake_position = 0 # The windows that have a verified checksum, or could be an answer, and end at or after the next window to # look at: {stream position just past the window: (the window, checksum matched, checksum verified, could be # an answer)}. self._handshake_ends = {} # For the handshake's timeout message: the bytes read, how many windows could have been an answer, and the # (command id, status) of the last window with a verified checksum that was none. self._handshake_bytes_read = 0 self._handshake_echoes_seen = 0 self._handshake_last_skipped = None # When the reader last read a byte while the handshake was pending: the mcu is talking, though nothing is # parsed yet (for _warn_if_reads_stale). self._last_byte_read_time = time.time() # Set, under _received_packet_cv, once the handshake's answer has been parsed; _detect_firmware_version waits # for it. self._handshake_answered = False # How packets are told from other bytes after the handshake. None until the handshake ends, then # _FRAMING_VERIFIED (the firmware sends checksums: a packet has a matching checksum and this connection's # firmware-version byte, _rx_version_byte) or _FRAMING_LEGACY (firmware from before checksums, or a handshake # answer that could not prove otherwise: a matching checksum or a zero in its place). self._framing = None self._rx_version_byte = None self._rx_dropped = 0 # bytes dropped since the last packet while looking for the next one # For reported_idle_since_last_command(), all under _received_packet_cv: a count of the valid packets # received, with the status and command id the newest one carried, and the count when the host last sent a # command. self._packet_seq = 0 self._last_packet_status = None self._last_packet_cmd_id = None self._packet_seq_at_last_send = 0 # (command id, StartupVerdict value, piezo DAC code or None) of the newest packet whose status byte was a startup # verdict reply (firmware >= STARTUP_STATE_MIN_FIRMWARE), under _received_packet_cv; for query_startup_state(). self._startup_verdict_packet = None # The startup decision (reset_and_initialize only). startup_verdict: the controller's answer to the startup # query, None when it was not asked (older firmware, --skip-init, a startup that homes no stage axis) or gave # none. startup_was_warm: the answer was WARM, so INITIALIZE and the motor configuration were skipped and the # stage is still homed. self.startup_verdict: Optional[StartupVerdict] = None self.startup_was_warm = False # From the startup reply: the last code written to the objective piezo's DAC since the controller powered up; # None when not asked or none was written. startup_piezo_um() converts it. self.startup_piezo_dac_code: Optional[int] = None self.thread_read_received_packet = threading.Thread(target=self.read_received_packet, daemon=True) self.thread_read_received_packet.start() # The illumination intensity factor the firmware applies to every DAC illumination command, as it receives it. # Set to the configured value here - with skip-init nothing is sent and the controller keeps what the previous # session sent from the same configuration - and updated whenever a factor is sent. self.illumination_intensity_factor = ( self._illumination_factor_byte(control._def.ILLUMINATION_INTENSITY_FACTOR) / 100.0 ) try: # Detect the firmware version first by sending a harmless command: supports_multi_port() needs it right # after construction, and the limit-switch check needs it before anything else is sent. self._detect_firmware_version() # Refuse before reset/initialize/actuator setup, so that nothing moves with the limit switches read # wrong and an unsupported current in the same config cannot end startup first. self.check_limit_switch_compatibility() if reset_and_initialize: # First, before anything changes the controller's state: may this startup skip homing? self.startup_verdict = self._ask_startup_verdict() self.startup_was_warm = self.startup_verdict is StartupVerdict.WARM # RESET on both paths: it ends a crashed session's command in progress (the query does not wait for # one) and puts back what a session may have changed, and writes no position. self.reset() if self.startup_was_warm: # INITIALIZE would change things: it zeroes XACTUAL and re-initialises the drivers and the DAC # config. Skipping it keeps the homed frame, which the controller's homed flags and health check # vouch for. The matching signature covers the other half: configure_actuators would send what # the controller already holds. self.log.debug("Resetting the microcontroller (warm start: drivers and actuators kept).") self.set_dac80508_scaling_factor_for_illumination(ILLUMINATION_INTENSITY_FACTOR) else: self.log.debug("Resetting and initializing microcontroller.") time.sleep(0.5) self.initialize_drivers() time.sleep(0.5) self.configure_actuators() self.set_dac80508_scaling_factor_for_illumination(ILLUMINATION_INTENSITY_FACTOR) time.sleep(0.5) # On both startup paths (--skip-init skips the block above). self.apply_limit_switch_config() if reset_and_initialize and not self.startup_was_warm and self.supports_startup_state(): # The last covered step: sign the configuration just sent, so a relaunch can be told it still holds self.store_config_signature(config_signature(), CONFIG_SIGNATURE_FORMAT) self.apply_focus_wheel_power_up_mode() self.unlock_panel() # a lock left by an earlier session (closed at the loading position, a crash) except BaseException: # A failed constructor leaves no reader thread or open port behind: headless callers may catch this # and keep their process. try: self.close() except Exception: self.log.exception("Failed to close the microcontroller link after a failed start") raise @property def is_simulated(self) -> bool: """True when this controller talks to SimSerial instead of a real one. Callers that need the hardware to answer truthfully - the filter-wheel tuner needs the wheel's encoder - ask this before they start.""" return self._is_simulated def simulated_port_is_on(self, port_index: int) -> bool: """Simulation only: whether the simulated controller has illumination port `port_index` (0 = D1) on - its TTL, what a simulated meter behind it sees.""" if not self._is_simulated: raise RuntimeError("simulated_port_is_on is only for a simulated controller") return bool(self._serial.port_is_on[port_index]) def _warn_if_reads_stale(self): if self._is_simulated: return # Until the connect handshake is answered no packet is parsed; bytes arriving show the mcu is talking. last_heard = self._last_byte_read_time if self._framing is None else self._last_successful_read_time if time.time() - last_heard > Microcontroller.STALE_READ_TIMEOUT: self.log.warning(f"Read thread is stale. {self._mcu_state()}") def close(self): self.stop_heartbeat() self.terminate_reading_received_packet_thread = True self.thread_read_received_packet.join() self._serial.close() def add_joystick_button_listener(self, listener: Callable[[bool], None]): try: next_id = max(t[0] for t in self.joystick_event_listeners) + 1 except ValueError as e: next_id = 1 self.log.debug(f"Adding joystick button listener with id={next_id}") self.joystick_event_listeners.append((next_id, listener)) def remove_joystick_button_listener(self, id_to_remove): try: idx = [t[0] for t in self.joystick_event_listeners].index(id_to_remove) self.log.debug(f"Removing joystick button listener id={id_to_remove} at idx={idx}") del self.joystick_event_listeners[idx] except ValueError as e: self.log.warning( f"Asked to remove joystick button listener {id_to_remove}, but it is not a known listener id" ) def enable_joystick(self, enabled: bool): self.joystick_listener_events_enabled = enabled def reset(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.RESET self.log.debug("reset the microcontroller") self.send_command(cmd) # On the microcontroller side, reset forces the command Id back to 0 # so any responses will look like they are for command id 0. Force that # here. self._cmd_id = 0 def initialize_drivers(self): self._cmd_id = 0 cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.INITIALIZE self.send_command(cmd) self.log.debug("initialize the drivers") def init_filter_wheel(self, axis=AXIS.W): """Initialize a filter wheel axis. Args: axis: The axis to initialize (AXIS.W or AXIS.W2). Defaults to AXIS.W. """ cmd_map = {AXIS.W: CMD_SET.INITFILTERWHEEL, AXIS.W2: CMD_SET.INITFILTERWHEEL_W2} if axis not in cmd_map: raise ValueError(f"Unsupported filter wheel axis: {axis}. Expected AXIS.W or AXIS.W2.") self._cmd_id = 0 cmd = bytearray(self.tx_buffer_length) cmd[1] = cmd_map[axis] self.send_command(cmd) def turn_on_illumination(self): self.log.debug("[MCU] turn_on_illumination") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.TURN_ON_ILLUMINATION self.send_command(cmd) def turn_off_illumination(self): self.log.debug("[MCU] turn_off_illumination") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.TURN_OFF_ILLUMINATION self.send_command(cmd) def set_illumination(self, illumination_source, intensity): self.log.debug(f"[MCU] set_illumination: source={illumination_source}, intensity={intensity}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_ILLUMINATION cmd[2] = illumination_source cmd[3] = int((intensity / 100) * 65535) >> 8 cmd[4] = int((intensity / 100) * 65535) & 0xFF self.send_command(cmd) def set_illumination_led_matrix(self, illumination_source, r, g, b): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_ILLUMINATION_LED_MATRIX cmd[2] = illumination_source cmd[3] = min(int(g * 255), 255) cmd[4] = min(int(r * 255), 255) cmd[5] = min(int(b * 255), 255) self.send_command(cmd) # Multi-port illumination commands (firmware v1.0+) # These allow multiple ports to be ON simultaneously with independent intensities # Maximum number of ports supported by firmware _MAX_ILLUMINATION_PORTS = 16 def _validate_port_index(self, port_index: int): """Validate port index is in valid range (0-15).""" if not isinstance(port_index, int): raise TypeError(f"port_index must be an integer, got {type(port_index).__name__}") if port_index < 0 or port_index >= self._MAX_ILLUMINATION_PORTS: raise ValueError(f"Invalid port_index {port_index}, must be 0-{self._MAX_ILLUMINATION_PORTS - 1}") def set_port_intensity(self, port_index: int, intensity: float): """Set DAC intensity for a specific port without changing on/off state. Note: Non-blocking. Call wait_till_operation_is_completed() before sending another command if ordering matters. Args: port_index: Port index (0=D1, 1=D2, etc.) intensity: Intensity percentage (0-100), clamped to valid range Raises: ValueError: If port_index is out of range (0-15) TypeError: If port_index is not an integer """ self._validate_port_index(port_index) self.log.debug(f"[MCU] set_port_intensity: port={port_index}, intensity={intensity}") # Clamp intensity to valid range intensity = max(0, min(100, intensity)) cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_PORT_INTENSITY cmd[2] = port_index intensity_value = int((intensity / 100) * 65535) cmd[3] = intensity_value >> 8 cmd[4] = intensity_value & 0xFF self.send_command(cmd) def turn_on_port(self, port_index: int): """Turn on a specific illumination port. Note: Non-blocking. Call wait_till_operation_is_completed() before sending another command if ordering matters. Args: port_index: Port index (0=D1, 1=D2, etc.) Raises: ValueError: If port_index is out of range (0-15) TypeError: If port_index is not an integer """ self._validate_port_index(port_index) self.log.debug(f"[MCU] turn_on_port: port={port_index}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.TURN_ON_PORT cmd[2] = port_index self.send_command(cmd) def turn_off_port(self, port_index: int): """Turn off a specific illumination port. Note: Non-blocking. Call wait_till_operation_is_completed() before sending another command if ordering matters. Args: port_index: Port index (0=D1, 1=D2, etc.) Raises: ValueError: If port_index is out of range (0-15) TypeError: If port_index is not an integer """ self._validate_port_index(port_index) self.log.debug(f"[MCU] turn_off_port: port={port_index}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.TURN_OFF_PORT cmd[2] = port_index self.send_command(cmd) def set_port_illumination(self, port_index: int, intensity: float, turn_on: bool): """Set intensity and on/off state for a specific port in one command. Note: Non-blocking. Call wait_till_operation_is_completed() before sending another command if ordering matters. Args: port_index: Port index (0=D1, 1=D2, etc.) intensity: Intensity percentage (0-100), clamped to valid range turn_on: Whether to turn the port on Raises: ValueError: If port_index is out of range (0-15) TypeError: If port_index is not an integer """ self._validate_port_index(port_index) self.log.debug(f"[MCU] set_port_illumination: port={port_index}, intensity={intensity}, on={turn_on}") # Clamp intensity to valid range intensity = max(0, min(100, intensity)) cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_PORT_ILLUMINATION cmd[2] = port_index intensity_value = int((intensity / 100) * 65535) cmd[3] = intensity_value >> 8 cmd[4] = intensity_value & 0xFF cmd[5] = 1 if turn_on else 0 self.send_command(cmd) def set_multi_port_mask(self, port_mask: int, on_mask: int): """Set on/off state for multiple ports using masks. This allows turning multiple ports on/off in a single command while leaving other ports unchanged. Note: Non-blocking. Call wait_till_operation_is_completed() before sending another command if ordering matters. Args: port_mask: 16-bit mask of which ports to update (bit 0=D1, bit 15=D16) on_mask: 16-bit mask of on/off state for selected ports (1=on, 0=off) Example: # Turn on D1 and D2, turn off D3, leave others unchanged set_multi_port_mask(0x0007, 0x0003) # port_mask=D1|D2|D3, on_mask=D1|D2 """ self.log.debug(f"[MCU] set_multi_port_mask: port_mask=0x{port_mask:04X}, on_mask=0x{on_mask:04X}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_MULTI_PORT_MASK cmd[2] = (port_mask >> 8) & 0xFF cmd[3] = port_mask & 0xFF cmd[4] = (on_mask >> 8) & 0xFF cmd[5] = on_mask & 0xFF self.send_command(cmd) def turn_off_all_ports(self): """Turn off all illumination ports. Note: Non-blocking. Call wait_till_operation_is_completed() before sending another command if ordering matters. """ self.log.debug("[MCU] turn_off_all_ports") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.TURN_OFF_ALL_PORTS self.send_command(cmd) def set_watchdog_timeout(self, timeout_s: float) -> None: """Set firmware serial watchdog timeout and enable the watchdog. The firmware will automatically turn off all illumination if it stops receiving serial messages for longer than this timeout. This is a safety feature to protect against software crashes or USB disconnects. Note: Non-blocking. Call wait_till_operation_is_completed() before sending another command if ordering matters. Args: timeout_s: Timeout in seconds. Valid range is 0 to 3600 (1 hour). Values below 0 are clamped to 0. Values above 3600 are clamped to 3600. A value of 0 tells the firmware to use its default timeout (5s). """ timeout_ms = int(max(0, min(timeout_s * 1000, MAX_WATCHDOG_TIMEOUT_MS))) if timeout_ms != int(timeout_s * 1000): max_s = MAX_WATCHDOG_TIMEOUT_MS / 1000.0 self.log.warning( f"[MCU] set_watchdog_timeout: requested {timeout_s}s clamped to " f"{timeout_ms / 1000.0}s (valid range: 0-{max_s}s)" ) self.log.debug(f"[MCU] set_watchdog_timeout: {timeout_s}s ({timeout_ms}ms)") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_WATCHDOG_TIMEOUT cmd[2] = (timeout_ms >> 24) & 0xFF cmd[3] = (timeout_ms >> 16) & 0xFF cmd[4] = (timeout_ms >> 8) & 0xFF cmd[5] = timeout_ms & 0xFF self.send_command(cmd) def send_heartbeat(self) -> None: """Send a no-op heartbeat command to reset the firmware watchdog timer.""" cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HEARTBEAT self.send_command(cmd) def start_heartbeat(self, interval_s: float = None) -> None: """Start a daemon thread that sends periodic heartbeat commands. Args: interval_s: Seconds between heartbeats. Defaults to WATCHDOG_TIMEOUT_S / 2. """ if self._heartbeat_thread is not None and self._heartbeat_thread.is_alive(): self.log.warning("[MCU] Heartbeat already running, stopping before restart") self.stop_heartbeat() if interval_s is None: interval_s = WATCHDOG_TIMEOUT_S / 2 self._heartbeat_stop_event.clear() def _heartbeat_loop(): consecutive_failures = 0 while not self._heartbeat_stop_event.wait(interval_s): try: self.send_heartbeat() if consecutive_failures > 0: self.log.info(f"[MCU] Heartbeat recovered after {consecutive_failures} failures") consecutive_failures = 0 except Exception as e: consecutive_failures += 1 if consecutive_failures == 1: self.log.warning(f"[MCU] Heartbeat send failed: {e}") elif consecutive_failures == 5: self.log.error( f"[MCU] Heartbeat has failed {consecutive_failures} times consecutively. " "Firmware watchdog may fire and disable illumination." ) elif consecutive_failures % 50 == 0: self.log.error(f"[MCU] Heartbeat still failing: {consecutive_failures} consecutive failures") self._heartbeat_thread = threading.Thread(target=_heartbeat_loop, daemon=True) self._heartbeat_thread.start() self._heartbeat_interval_s = interval_s self.log.debug(f"[MCU] Heartbeat started: interval={interval_s}s") @property def heartbeat_interval_s(self): """The running heartbeat's interval in seconds, or None when no heartbeat runs (no watchdog: firmware before 1.1, or not started). Code that drives the light itself can stop the heartbeat for that time and feed the watchdog from its own loop, so the firmware turns the light off if that loop stops.""" return self._heartbeat_interval_s def stop_heartbeat(self) -> None: """Stop the heartbeat thread.""" self._heartbeat_interval_s = None self._heartbeat_stop_event.set() if self._heartbeat_thread is not None and self._heartbeat_thread.is_alive(): self._heartbeat_thread.join(timeout=2.0) if self._heartbeat_thread.is_alive(): self.log.warning("[MCU] Heartbeat thread did not stop within 2s timeout") self._heartbeat_thread = None return self._heartbeat_thread = None self.log.debug("[MCU] Heartbeat stopped") def send_hardware_trigger(self, control_illumination=False, illumination_on_time_us=0, trigger_output_ch=0): illumination_on_time_us = int(illumination_on_time_us) cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SEND_HARDWARE_TRIGGER cmd[2] = (control_illumination << 7) + trigger_output_ch # MSB: whether illumination is controlled cmd[3] = illumination_on_time_us >> 24 cmd[4] = (illumination_on_time_us >> 16) & 0xFF cmd[5] = (illumination_on_time_us >> 8) & 0xFF cmd[6] = illumination_on_time_us & 0xFF self.send_command(cmd) def set_strobe_delay_us(self, strobe_delay_us, camera_channel=0): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_STROBE_DELAY cmd[2] = camera_channel cmd[3] = strobe_delay_us >> 24 cmd[4] = (strobe_delay_us >> 16) & 0xFF cmd[5] = (strobe_delay_us >> 8) & 0xFF cmd[6] = strobe_delay_us & 0xFF self.send_command(cmd) def set_axis_enable_disable(self, axis, status): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_AXIS_DISABLE_ENABLE cmd[2] = axis cmd[3] = status self.send_command(cmd) def set_completion_window(self, axis, window_mm): """Report a move on `axis` complete once |position - target| <= window_mm, while the ramp is still finishing (firmware >= 1.6; older firmware does not know the command, so callers gate on the version). 0 restores completion at the exact target with the ramp stopped. Encoded in 0.1 um, range 0 .. 6.5535 mm. For the filter wheels one "mm" is one revolution: pass degrees / 360. """ u = int(round(window_mm * 10000)) if not (0 <= u <= 0xFFFF): raise ValueError("completion window must be 0 .. 6.5535 mm (or rev)") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_COMPLETION_WINDOW cmd[2] = int(axis) cmd[3] = (u >> 8) & 0xFF cmd[4] = u & 0xFF self.send_command(cmd) def set_encoder_reporting(self, axis, mode=ENCODER_REPORTING.ENC_IN_THETA): """Put `axis`'s encoder into the status packet (firmware >= 1.6; callers gate on the version). A read-only diagnostic: it moves nothing. The encoder must have been set up with configure_stage_pid() (scale and direction; that engages nothing) for the values to be in microsteps. Afterwards encoder_pos / encoder_deviation / encoder_flags update every packet. ENCODER_REPORTING.OFF restores the shipping packet; RESET and INITIALIZE do too. """ if mode not in (ENCODER_REPORTING.OFF, ENCODER_REPORTING.ENC_IN_THETA, ENCODER_REPORTING.ENC_AS_POSITION): raise ValueError("encoder reporting mode must be ENCODER_REPORTING.OFF, ENC_IN_THETA or ENC_AS_POSITION") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_ENCODER_REPORTING cmd[2] = int(axis) cmd[3] = int(mode) self.send_command(cmd) def set_focus_wheel_mode(self, mode: int, save_as_power_up: bool = False): """Route the control panel's focus wheel (firmware >= FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE; callers gate on it). FOCUS_WHEEL_MODE.TO_HOST stops the wheel moving the Z stepper and reports its ticks in focus_wheel_count; DRIVES_Z lets it move the Z stepper. With save_as_power_up the controller also stores the mode (EEPROM, written only when it changes) and uses it at power-up and after RESET and INITIALIZE. """ if mode not in (FOCUS_WHEEL_MODE.DRIVES_Z, FOCUS_WHEEL_MODE.TO_HOST): raise ValueError("focus wheel mode must be FOCUS_WHEEL_MODE.DRIVES_Z or TO_HOST") saved = " (saved as the power-up mode)" if save_as_power_up else "" self.log.info(f"Set focus wheel mode: {mode}{saved}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_FOCUS_WHEEL_MODE cmd[2] = int(mode) cmd[3] = FOCUS_WHEEL_SAVE_AS_POWER_UP if save_as_power_up else 0 self.send_command(cmd) def set_panel_lock(self, locked: bool): """Lock (or unlock) the control panel: locked, its joystick reads centred and its wheel turns are dropped, so nothing on the panel moves the stage (firmware >= FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE; callers gate on supports_panel_lock()). Locking also stops a joystick move under way. Not saved: RESET, INITIALIZE and a controller power cycle unlock.""" self.log.info(f"Set control panel lock: {locked}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_PANEL_LOCK cmd[2] = 1 if locked else 0 self.send_command(cmd) def supports_panel_lock(self) -> bool: return tuple(self.firmware_version) >= FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE def unlock_panel(self) -> None: """Unlock the control panel on connect (--skip-init too, which sends no RESET), if the firmware has the lock.""" if self.supports_panel_lock(): self.set_panel_lock(False) self.wait_till_operation_is_completed() def apply_focus_wheel_power_up_mode(self) -> None: """Save the focus wheel's power-up mode for this configuration, if the firmware supports it. On a Z lift system whose wheel drives the V-308 (USE_Z_LIFT_STAGE and Z_LIFT_FOCUS_WHEEL_DRIVES_PI) the wheel must never move the lift, so TO_HOST is saved: it then moves nothing whenever Squid is not driving the V-308 with it (before start-up, after close, after a crash). Every other configuration saves DRIVES_Z, the firmware's own default, so a controller moved from a lift system back to a stock one gets the stock wheel. Run on every connect, --skip-init included; the controller writes EEPROM only when the mode changes. """ if not self.supports_focus_wheel_to_host(): return lift_wheel = control._def.USE_Z_LIFT_STAGE and control._def.Z_LIFT_FOCUS_WHEEL_DRIVES_PI mode = FOCUS_WHEEL_MODE.TO_HOST if lift_wheel else FOCUS_WHEEL_MODE.DRIVES_Z self.set_focus_wheel_mode(mode, save_as_power_up=True) self.wait_till_operation_is_completed() def supports_focus_wheel_to_host(self) -> bool: """True if the firmware has SET_FOCUS_WHEEL_MODE.""" return tuple(self.firmware_version) >= FOCUS_WHEEL_TO_HOST_MIN_FIRMWARE def get_encoder_state(self): """The last reported encoder reading: reporting / pid_enabled / axis (from byte 19), encoder_pos and deviation (ENC_POS - XACTUAL) in microsteps. `reporting` is False when the last packet carried no encoder; the two values are then the last ones seen.""" flags = self.encoder_flags return { "reporting": bool(flags & (1 << ENC_FLAG.REPORTING)), "pid_enabled": bool(flags & (1 << ENC_FLAG.PID_ENABLED)), "axis": (flags >> ENC_FLAG.AXIS_SHIFT) & 0x07, "encoder_pos": self.encoder_pos, "deviation": self.encoder_deviation, } def set_ramp_profile(self, axis, profile): """S-shaped (RAMP_PROFILE.SSHAPE, the firmware default) or trapezoidal ramp for `axis` (firmware >= 1.6; callers gate on the version). Takes effect at once; a RESET returns every axis to the S-shape.""" if profile not in (RAMP_PROFILE.TRAPEZOID, RAMP_PROFILE.SSHAPE): raise ValueError("ramp profile must be RAMP_PROFILE.TRAPEZOID or RAMP_PROFILE.SSHAPE") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_RAMP_PROFILE cmd[2] = int(axis) cmd[3] = int(profile) self.send_command(cmd) def set_trigger_mode(self, mode): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_TRIGGER_MODE cmd[2] = mode self.send_command(cmd) def _move_axis_usteps(self, usteps, axis_command_code): direction = np.sign(usteps) n_microsteps_abs = abs(usteps) # if n_microsteps_abs exceed the max value that can be sent in one go while n_microsteps_abs >= (2**32) / 2: n_microsteps_partial_abs = (2**32) / 2 - 1 n_microsteps_partial = direction * n_microsteps_partial_abs payload = self._int_to_payload(n_microsteps_partial, 4) cmd = bytearray(self.tx_buffer_length) cmd[1] = axis_command_code cmd[2] = payload >> 24 cmd[3] = (payload >> 16) & 0xFF cmd[4] = (payload >> 8) & 0xFF cmd[5] = payload & 0xFF # TODO(imo): Since this issues multiple commands, there's no way to check for and abort failed # ones mid-move. self.send_command(cmd) n_microsteps_abs = n_microsteps_abs - n_microsteps_partial_abs n_microsteps = direction * n_microsteps_abs payload = self._int_to_payload(n_microsteps, 4) cmd = bytearray(self.tx_buffer_length) cmd[1] = axis_command_code cmd[2] = payload >> 24 cmd[3] = (payload >> 16) & 0xFF cmd[4] = (payload >> 8) & 0xFF cmd[5] = payload & 0xFF self.send_command(cmd) def move_x_usteps(self, usteps): self._move_axis_usteps(usteps, CMD_SET.MOVE_X) def _move_axis_to_usteps(self, usteps, axis_command_code): payload = self._int_to_payload(usteps, 4) cmd = bytearray(self.tx_buffer_length) cmd[1] = axis_command_code cmd[2] = payload >> 24 cmd[3] = (payload >> 16) & 0xFF cmd[4] = (payload >> 8) & 0xFF cmd[5] = payload & 0xFF self.send_command(cmd) def move_x_to_usteps(self, usteps): self._move_axis_to_usteps(usteps, CMD_SET.MOVETO_X) def move_y_usteps(self, usteps): self._move_axis_usteps(usteps, CMD_SET.MOVE_Y) def move_y_to_usteps(self, usteps): self._move_axis_to_usteps(usteps, CMD_SET.MOVETO_Y) def move_z_usteps(self, usteps): self._move_axis_usteps(usteps, CMD_SET.MOVE_Z) def move_z_to_usteps(self, usteps): self._move_axis_to_usteps(usteps, CMD_SET.MOVETO_Z) def move_theta_usteps(self, usteps): self._move_axis_usteps(usteps, CMD_SET.MOVE_THETA) def move_w_usteps(self, usteps): self._move_axis_usteps(usteps, CMD_SET.MOVE_W) def move_w2_usteps(self, usteps): self._move_axis_usteps(usteps, CMD_SET.MOVE_W2) def move_w_to_usteps(self, usteps): self._move_axis_to_usteps(usteps, CMD_SET.MOVETO_W) def move_w2_to_usteps(self, usteps): self._move_axis_to_usteps(usteps, CMD_SET.MOVETO_W2) def set_off_set_velocity_x(self, off_set_velocity): # off_set_velocity is in mm/s cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_OFFSET_VELOCITY cmd[2] = AXIS.X off_set_velocity = off_set_velocity * 1000000 payload = self._int_to_payload(off_set_velocity, 4) cmd[3] = payload >> 24 cmd[4] = (payload >> 16) & 0xFF cmd[5] = (payload >> 8) & 0xFF cmd[6] = payload & 0xFF self.send_command(cmd) def set_off_set_velocity_y(self, off_set_velocity): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_OFFSET_VELOCITY cmd[2] = AXIS.Y off_set_velocity = off_set_velocity * 1000000 payload = self._int_to_payload(off_set_velocity, 4) cmd[3] = payload >> 24 cmd[4] = (payload >> 16) & 0xFF cmd[5] = (payload >> 8) & 0xFF cmd[6] = payload & 0xFF self.send_command(cmd) def home_x( self, homing_direction: HomingDirection = _default_x_homing_direction, *, objective_lowered: bool = False ): require_objective_lowered(objective_lowered, "Home X") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.X cmd[3] = homing_direction.value self.send_command(cmd) def home_y( self, homing_direction: HomingDirection = _default_y_homing_direction, *, objective_lowered: bool = False ): require_objective_lowered(objective_lowered, "Home Y") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.Y cmd[3] = homing_direction.value self.send_command(cmd) def home_z(self, homing_direction: HomingDirection = _default_z_homing_direction): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.Z cmd[3] = homing_direction.value self.send_command(cmd) def home_theta(self, homing_direction: HomingDirection = _default_theta_homing_direction): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = 3 cmd[3] = homing_direction.value self.send_command(cmd) def home_xy( self, homing_direction_x: HomingDirection = _default_x_homing_direction, homing_direction_y: HomingDirection = _default_y_homing_direction, *, objective_lowered: bool = False, ): require_objective_lowered(objective_lowered, "Home XY") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.XY cmd[3] = homing_direction_x.value cmd[4] = homing_direction_y.value self.send_command(cmd) def home_w(self, homing_direction: HomingDirection = _default_w_homing_direction): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.W cmd[3] = homing_direction.value self.send_command(cmd) def home_w2(self, homing_direction: HomingDirection = _default_w2_homing_direction): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.W2 cmd[3] = homing_direction.value self.send_command(cmd) def zero_x(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.X cmd[3] = HOME_OR_ZERO.ZERO self.send_command(cmd) def zero_y(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.Y cmd[3] = HOME_OR_ZERO.ZERO self.send_command(cmd) def zero_z(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.Z cmd[3] = HOME_OR_ZERO.ZERO self.send_command(cmd) def zero_w(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.W cmd[3] = HOME_OR_ZERO.ZERO self.send_command(cmd) def zero_w2(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.W2 cmd[3] = HOME_OR_ZERO.ZERO self.send_command(cmd) def zero_theta(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.HOME_OR_ZERO cmd[2] = AXIS.THETA cmd[3] = HOME_OR_ZERO.ZERO self.send_command(cmd) def configure_stage_pid(self, axis, transitions_per_revolution, flip_direction=False): if not isinstance(transitions_per_revolution, int): self.log.warning(f"transitions_per_revolution must be an integer, truncating: {transitions_per_revolution}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.CONFIGURE_STAGE_PID cmd[2] = axis cmd[3] = int(flip_direction) payload = self._int_to_payload(transitions_per_revolution, 2) cmd[4] = (payload >> 8) & 0xFF cmd[5] = payload & 0xFF self.send_command(cmd) def turn_on_stage_pid(self, axis): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.ENABLE_STAGE_PID cmd[2] = axis self.send_command(cmd) def turn_off_stage_pid(self, axis): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.DISABLE_STAGE_PID cmd[2] = axis self.send_command(cmd) def turn_off_all_pid(self): for primary_axis_id in [AXIS.X, AXIS.Y, AXIS.Z]: self.turn_off_stage_pid(primary_axis_id) self.wait_till_operation_is_completed() def set_pid_arguments(self, axis, pid_p, pid_i, pid_d): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_PID_ARGUMENTS cmd[2] = int(axis) cmd[3] = (int(pid_p) >> 8) & 0xFF cmd[4] = int(pid_p) & 0xFF cmd[5] = int(pid_i) cmd[6] = int(pid_d) self.send_command(cmd) def set_lim(self, limit_code, usteps): self.log.info(f"Set lim: {limit_code=}, {usteps=}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_LIM cmd[2] = limit_code payload = self._int_to_payload(usteps, 4) cmd[3] = payload >> 24 cmd[4] = (payload >> 16) & 0xFF cmd[5] = (payload >> 8) & 0xFF cmd[6] = payload & 0xFF self.send_command(cmd) def set_limit_switch_config(self, axis: int, config: int): """Send one axis's limit-switch config nibble (LIMIT_SWITCH_BITS); the firmware stores it in EEPROM.""" self.log.info(f"Set limit switch config: {axis=}, config=0x{config:02X}") cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_LIMIT_SWITCH_CONFIG cmd[2] = axis cmd[3] = config self.send_command(cmd) def set_home_safety_margin(self, axis, margin): margin = abs(margin) if margin > 0xFFFF: margin = 0xFFFF cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_HOME_SAFETY_MERGIN cmd[2] = axis cmd[3] = (margin >> 8) & 0xFF cmd[4] = (margin) & 0xFF self.send_command(cmd) def configure_motor_driver(self, axis, microstepping, current_rms, I_hold): # current_rms in mA # I_hold 0.0-1.0 cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.CONFIGURE_STEPPER_DRIVER cmd[2] = axis if microstepping == 1: cmd[3] = 0 elif microstepping == 256: cmd[3] = 255 # max of uint8 is 255 - will be changed to 255 after received by the MCU else: cmd[3] = microstepping cmd[4] = current_rms >> 8 cmd[5] = current_rms & 0xFF cmd[6] = int(I_hold * 255) self.send_command(cmd) def set_max_velocity_acceleration(self, axis, velocity, acceleration): # velocity: max 65535/100 mm/s # acceleration: max 65535/10 mm/s^2 cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_MAX_VELOCITY_ACCELERATION cmd[2] = axis cmd[3] = int(velocity * 100) >> 8 cmd[4] = int(velocity * 100) & 0xFF cmd[5] = int(acceleration * 10) >> 8 cmd[6] = int(acceleration * 10) & 0xFF self.send_command(cmd) def set_leadscrew_pitch(self, axis, pitch_mm): # pitch: max 65535/1000 = 65.535 (mm) cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_LEAD_SCREW_PITCH cmd[2] = axis cmd[3] = int(pitch_mm * 1000) >> 8 cmd[4] = int(pitch_mm * 1000) & 0xFF self.send_command(cmd) def configure_actuators(self): """Send the X, Y and Z pitch, driver, velocity/acceleration and home margin settings, each waited for. Every value is read through control._def when this runs, not from the `from control._def import *` binding taken at import: config_signature() reads control._def at call time, and the signature stored after this must describe exactly what the controller was sent. """ # lead screw pitch self.set_leadscrew_pitch(AXIS.X, control._def.SCREW_PITCH_X_MM) self.wait_till_operation_is_completed() self.set_leadscrew_pitch(AXIS.Y, control._def.SCREW_PITCH_Y_MM) self.wait_till_operation_is_completed() self.set_leadscrew_pitch(AXIS.Z, control._def.SCREW_PITCH_Z_MM) self.wait_till_operation_is_completed() # stepper driver (microstepping,rms current and I_hold) self.configure_motor_driver( AXIS.X, control._def.MICROSTEPPING_DEFAULT_X, control._def.X_MOTOR_RMS_CURRENT_mA, control._def.X_MOTOR_I_HOLD, ) self.wait_till_operation_is_completed() self.configure_motor_driver( AXIS.Y, control._def.MICROSTEPPING_DEFAULT_Y, control._def.Y_MOTOR_RMS_CURRENT_mA, control._def.Y_MOTOR_I_HOLD, ) self.wait_till_operation_is_completed() self.configure_motor_driver( AXIS.Z, control._def.MICROSTEPPING_DEFAULT_Z, control._def.Z_MOTOR_RMS_CURRENT_mA, control._def.Z_MOTOR_I_HOLD, ) self.wait_till_operation_is_completed() # max velocity and acceleration self.set_max_velocity_acceleration(AXIS.X, control._def.MAX_VELOCITY_X_mm, control._def.MAX_ACCELERATION_X_mm) self.wait_till_operation_is_completed() self.set_max_velocity_acceleration(AXIS.Y, control._def.MAX_VELOCITY_Y_mm, control._def.MAX_ACCELERATION_Y_mm) self.wait_till_operation_is_completed() self.set_max_velocity_acceleration(AXIS.Z, control._def.MAX_VELOCITY_Z_mm, control._def.MAX_ACCELERATION_Z_mm) self.wait_till_operation_is_completed() # home safety margin self.set_home_safety_margin(AXIS.X, int(control._def.X_HOME_SAFETY_MARGIN_UM)) self.wait_till_operation_is_completed() self.set_home_safety_margin(AXIS.Y, int(control._def.Y_HOME_SAFETY_MARGIN_UM)) self.wait_till_operation_is_completed() self.set_home_safety_margin(AXIS.Z, int(control._def.Z_HOME_SAFETY_MARGIN_UM)) self.wait_till_operation_is_completed() def configure_squidfilter(self, axis=AXIS.W): """Configure a filter wheel motor. The microstepping, current and velocity/acceleration are read through control._def rather than from the `from control._def import *` binding at the top of this module: that binding is taken at import time, so a profile changed while the software runs (the filter-wheel tuner's "Apply and save") would be ignored here while the host's slot arithmetic used the new value. They must be the same number. Args: axis: The axis to configure (AXIS.W or AXIS.W2). Defaults to AXIS.W. """ if axis not in (AXIS.W, AXIS.W2): raise ValueError(f"Unsupported filter wheel axis: {axis}. Expected AXIS.W or AXIS.W2.") self.set_leadscrew_pitch(axis, SCREW_PITCH_W_MM) self.wait_till_operation_is_completed() self.configure_motor_driver( axis, int(control._def.MICROSTEPPING_DEFAULT_W), control._def.W_MOTOR_RMS_CURRENT_mA, control._def.W_MOTOR_I_HOLD, ) self.wait_till_operation_is_completed() self.set_max_velocity_acceleration(axis, control._def.MAX_VELOCITY_W_mm, control._def.MAX_ACCELERATION_W_mm) self.wait_till_operation_is_completed() def ack_joystick_button_pressed(self): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.ACK_JOYSTICK_BUTTON_PRESSED self.send_command(cmd) def analog_write_onboard_DAC(self, dac, value): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.ANALOG_WRITE_ONBOARD_DAC cmd[2] = dac cmd[3] = (value >> 8) & 0xFF cmd[4] = value & 0xFF self.send_command(cmd) def set_piezo_um(self, z_piezo_um): dac = int(65535 * (z_piezo_um / OBJECTIVE_PIEZO_RANGE_UM)) dac = 65535 - dac if OBJECTIVE_PIEZO_FLIP_DIR else dac self.analog_write_onboard_DAC(OBJECTIVE_PIEZO_DAC_CHANNEL, dac) def startup_piezo_um(self) -> Optional[float]: """Where the objective piezo is by the startup reply's DAC code (set_piezo_um's conversion reversed); None when the controller reported no code.""" if self.startup_piezo_dac_code is None: return None dac = 65535 - self.startup_piezo_dac_code if OBJECTIVE_PIEZO_FLIP_DIR else self.startup_piezo_dac_code return OBJECTIVE_PIEZO_RANGE_UM * dac / 65535 def configure_dac80508_refdiv_and_gain(self, div, gains): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_DAC80508_REFDIV_GAIN cmd[2] = div cmd[3] = gains self.send_command(cmd) def set_pin_level(self, pin, level): cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_PIN_LEVEL cmd[2] = pin cmd[3] = level self.send_command(cmd) def turn_on_AF_laser(self): self.set_pin_level(MCU_PINS.AF_LASER, 1) def turn_off_AF_laser(self): self.set_pin_level(MCU_PINS.AF_LASER, 0) def send_command(self, command): with self._cmd_lock: self._cmd_id = (self._cmd_id + 1) % 256 if self._framing is None: # the connect handshake is pending: a packet echoing this id answers it self._handshake_cmd_ids.add(self._cmd_id) command[0] = self._cmd_id command[-1] = self.crc_calculator.calculate_checksum(command[:-1]) cmd_type = command[1] cmd_name = _CMD_NAMES.get(cmd_type, f"UNKNOWN({cmd_type})") self.log.debug(f"[MCU] >>> sending command {self._cmd_id}, type={cmd_name}") # Taken before the write: a reply can be parsed before write() returns (SimSerial answers inside it). with self._received_packet_cv: self._packet_seq_at_last_send = self._packet_seq self._serial.write(command, reconnect_tries=Microcontroller.MAX_RECONNECT_COUNT) self.mcu_cmd_execution_in_progress = True self.last_command = command self.last_command_send_timestamp = time.time() self.retry = 0 if self.last_command_aborted_error is not None: self.log.warning( "Last command aborted and not cleared before new command sent! %s", self.last_command_aborted_error ) self.last_command_aborted_error = None self._warn_if_reads_stale() def abort_current_command(self, reason, recoverable: bool = False): """Mark the current MCU command as aborted. Args: reason: Human-readable reason; surfaced in the CommandAborted exception. recoverable: If True, log at WARNING — caller will retry or handle the failure (e.g. a filter wheel resend on CMD_EXECUTION_ERROR). Also surfaced on the CommandAborted exception so callers can resend safely only in this case. If False (default), log at ERROR (operator attention warranted) and the motor state is uncertain. """ msg = f"[MCU] Command {self._cmd_id} ({self._last_command_name()}) aborted: {reason}" if recoverable: self.log.warning(msg) else: self.log.error(msg) self.last_command_aborted_error = CommandAborted( reason=reason, command_id=self._cmd_id, recoverable=recoverable ) self.mcu_cmd_execution_in_progress = False def acknowledge_aborted_command(self): if self.last_command_aborted_error is None: self.log.warning("Request to ack aborted command, but there is no aborted command.") self.last_command_aborted_error = None def resend_last_command(self): with self._cmd_lock: if self.last_command is not None: self._serial.write(self.last_command, reconnect_tries=Microcontroller.MAX_RECONNECT_COUNT) self.mcu_cmd_execution_in_progress = True # We use the retry count for both checksum errors, and to keep track of # timeout re-attempts. self.last_command_send_timestamp = time.time() self.retry = self.retry + 1 else: self.log.warning("resend requested with no last_command, something is wrong!") self.abort_current_command("Resend last requested with no last command") _FRAMING_VERIFIED = "verified" _FRAMING_LEGACY = "legacy" def _status_checksum_matches(self, window) -> bool: return self.crc_calculator_rx.calculate_checksum(window[:-1]) == window[-1] def _reset_status_stream(self): """Forget the bytes read so far (the serial input buffer was just discarded).""" self._rx.clear() self._handshake_position = 0 self._handshake_ends = {} def _next_status_packet(self): """The next status packet in the stream, as (packet, crc_matched); (None, False) when it needs more bytes. The controller sends 24-byte status packets back to back, with nothing marking where one starts, and the stream the host reads can start or resume anywhere: bytes waiting from before the port opened, text a firmware build printed on the same port, bytes lost on the way. Each packet ends in a CRC-8, but one that starts from zero, and most bytes of an idle controller's packet are zero: a window that starts in the middle of one packet and ends in the middle of the next then has a "matching" checksum too (both are zero). Firmware from before April 2025 sends a zero instead of a checksum, so for its sake any window that ends in zero used to count as a packet. Either way the host could read a firmware-version or CRC byte as the buttons byte and acknowledge a joystick press nobody made, or take every field from the wrong place for good. Two things replace that: - The connect handshake (_take_handshake_answer). Until a packet answers a command sent on this connection (it echoes that command's id; _detect_firmware_version sends them), nothing read is used. The answer is looked for at every byte offset, and taken where the first byte changes to the host's command id from one packet to the next. That fixes where packets start, and shows whether this firmware sends checksums. - Framing after it (_take_framed_packet). On firmware that sends checksums a window is a packet only if its checksum matches and its firmware-version byte is this connection's; the host drops a byte at a time until that holds again. The version byte is what a shifted window does not have: it is constant, not zero from firmware 1.0 on, and in one place. Firmware without checksums keeps the old rule. """ bytes_read = 0 while True: if self._framing is None: packet = self._take_handshake_answer() else: packet = self._take_framed_packet() if packet is not None: return packet if bytes_read >= Microcontroller.STATUS_STREAM_MAX_BYTES_PER_READ or self._serial.bytes_available() <= 0: return None, False self._rx.append(ord(self._serial.read())) bytes_read += 1 if self._framing is None: self._handshake_bytes_read += 1 self._last_byte_read_time = time.time() def _take_handshake_answer(self): """The handshake's answer from the bytes read so far, as (packet, crc_matched), or None if it is not there yet. Each 24-byte window is looked at once, in stream order. A window can be an answer if it is packet-shaped (its checksum matches, or it ends in the zero that firmware from before checksums sends instead) and echoes a command sent on this connection. That alone is not enough: a window that starts in the middle of a packet is often packet-shaped (see _next_status_packet), and its first byte is a piece of some field - a stage position byte of 0x01 is common, and equals the first command's id. What such a window cannot do is change its first byte from one packet to the next, to follow the host's commands. So the answer is taken where the window that ends at its start had a different first byte, and the two together are evidence: - that window has a verified checksum, and the answer's checksum matches. Verified means it matches and is not zero; a matching zero proves nothing, because an idle controller's packets shifted by a few bytes have one too. This is the normal start: the controller's last packet before it took the command, then its first one after; - or that window could be an answer too, to a different command of this connection, and the two are alike as two consecutive packets are (at most HANDSHAKE_MAX_BYTES_CHANGED bytes differ besides the first and last). This is what firmware from before checksums can show, and what settles a stream when nothing verifiable comes right before the answer: _detect_firmware_version sends its command again, first after HANDSHAKE_RESEND_INTERVAL_S, until the handshake is answered. It sends it with an id picked at random, so that a byte that merely counts up (the low byte of a moving stage's position) cannot follow it. One answer is taken with nothing before it: the first 24 bytes read, if their checksum is verified (a controller that had sent nothing yet, and the simulators). Everything before the answer - a previous session's last packets, bytes from the middle of a packet, text - is skipped, not parsed: none of it is acted on. """ length = self.rx_buffer_length rx = self._rx while len(rx) >= length: position = self._handshake_position window = rx[:length] crc_matched = self._status_checksum_matches(window) verified = crc_matched and window[-1] != 0 packet_shaped = crc_matched or window[-1] == 0 # the old framing's rule answers = packet_shaped and window[0] in self._handshake_cmd_ids previous = self._handshake_ends.pop(position, None) if answers: self._handshake_echoes_seen += 1 if verified and position == 0: return self._end_handshake(crc_matched, checksums=True) if previous is not None and previous[0][0] != window[0]: previous_window, previous_crc_matched, previous_verified, previous_answers = previous if previous_verified and crc_matched: return self._end_handshake(crc_matched, checksums=True) bytes_changed = sum(a != b for a, b in zip(previous_window[1:-1], window[1:-1])) if previous_answers and bytes_changed <= Microcontroller.HANDSHAKE_MAX_BYTES_CHANGED: # Checksums count only if both matched and this one is not a zero. return self._end_handshake(crc_matched, checksums=verified and previous_crc_matched) elif verified: self._handshake_last_skipped = (window[0], window[1]) if verified or answers: self._handshake_ends[position + length] = (bytes(window), crc_matched, verified, answers) del rx[:1] self._handshake_position += 1 return None def _end_handshake(self, crc_matched: bool, checksums: bool): """Take the window at the front of _rx as the handshake's answer; framing continues right after it. checksums: the firmware sends them, so packets are verified from here on (_FRAMING_VERIFIED). """ length = self.rx_buffer_length window = self._rx[:length] del self._rx[:length] self._handshake_ends = {} version_byte = window[RESPONSE_BYTE_FIRMWARE_VERSION] if checksums: self._framing = Microcontroller._FRAMING_VERIFIED self._rx_version_byte = version_byte else: self._framing = Microcontroller._FRAMING_LEGACY self.log.info( f"[MCU] status stream in step after {self._handshake_bytes_read} byte(s): firmware" f" {version_byte >> 4}.{version_byte & 0x0F}, " + ("checksums verified" if checksums else "no checksum to verify (older firmware's framing)") ) return list(window), crc_matched def _follow_firmware_change(self, version_byte: int, following) -> bool: """Whether the 24 bytes after a window that verifies with another firmware-version byte do so too. Then the controller was reflashed while connected, and that byte is this connection's from here on; one such window alone can be chance (1 stray window in 256).""" if not ( self._status_checksum_matches(following) and following[-1] != 0 and following[RESPONSE_BYTE_FIRMWARE_VERSION] == version_byte ): return False self.log.warning( f"[MCU] the controller's firmware changed from" f" {self._rx_version_byte >> 4}.{self._rx_version_byte & 0x0F} to" f" {version_byte >> 4}.{version_byte & 0x0F} while connected. Restart Squid: its start-up" " checks and the controller's settings were for the old firmware." ) self._rx_version_byte = version_byte return True def _take_framed_packet(self): """The next packet from the bytes read so far, as (packet, crc_matched), or None if there is none yet. After the handshake. While the window at the front is not a packet, drops its first byte and looks again. """ length = self.rx_buffer_length rx = self._rx while len(rx) >= length: window = rx[:length] crc_matched = self._status_checksum_matches(window) if self._framing == Microcontroller._FRAMING_VERIFIED: version_byte = window[RESPONSE_BYTE_FIRMWARE_VERSION] is_packet = crc_matched and version_byte == self._rx_version_byte if not is_packet and crc_matched and window[-1] != 0: # It verifies, with another firmware's version byte. The next 24 bytes tell whether that is a # reflashed controller: wait for them. if len(rx) < 2 * length: return None is_packet = self._follow_firmware_change(version_byte, rx[length : 2 * length]) else: # NOTE(imo): Before April 2025, we didn't send the crc from the micro. This is # here to support firmware that still sends 0 as the checksum. is_packet = crc_matched or window[-1] == 0 if is_packet: if self._rx_dropped: self.log.warning(f"[MCU] status stream back in step after dropping {self._rx_dropped} byte(s)") self._rx_dropped = 0 del rx[:length] return list(window), crc_matched if not self._rx_dropped: self.log.warning( f"[MCU] status stream out of step: {bytes(window).hex(' ')} is not a status packet" f" (checksum {'matches' if crc_matched else 'does not match'}); dropping bytes until one is" ) self._rx_dropped += 1 del rx[:1] if self._rx_dropped == Microcontroller.STATUS_STREAM_LOST_AFTER_BYTES: self.log.error( f"[MCU] status stream lost: no status packet in the last {self._rx_dropped} bytes from the mcu." " Its firmware changed while connected, or the link is corrupting data. Restart Squid." ) return None def read_received_packet(self): last_watchdog_fail_report = time.time() watchdog_fail_report_period = 5.0 while not self.terminate_reading_received_packet_thread: try: # If anything hangs, we may fall way behind reading the serial buffer. In that case, toss everything # in the read buffer and start over. This should always be safe to do because the micro sends updates # periodically without prompting, and so we'll always get more updates on the current micro state. if self._serial.bytes_available() >= BUFFER_SIZE_LIMIT: self._serial.reset_input_buffer() self._reset_status_stream() continue msg, crc_matched = self._next_status_packet() # No whole packet yet: there's no reason to waste our time, so wait here until more bytes arrive. if msg is None: if time.time() - last_watchdog_fail_report > watchdog_fail_report_period: last_watchdog_fail_report = time.time() self._warn_if_reads_stale() # Sleep a negligible amount of time just to give other threads time to run. Otherwise, # we run the rise of spinning forever here and not letting progress happen elsewhere. time.sleep(0.0001) if not self._serial.is_open(): if not self._serial.reconnect(attempts=Microcontroller.MAX_RECONNECT_COUNT): self.log.error( "In read loop, serial device failed to reconnect. Microcontroller is defunct!" ) continue # parse the message """ - byte 0: command ID (1 byte) - byte 1: execution status (1 byte) - bytes 2-5: X pos (4 bytes) - bytes 6-9: Y pos (4 bytes) - bytes 10-13: Z pos (4 bytes) - bytes 14-17: Theta (4 bytes) - byte 18: buttons and switches (1 byte) - bytes 19-21: reserved (3 bytes) - byte 22: firmware version, nibble-encoded (1 byte) - byte 23: CRC (1 byte) """ self._last_successful_read_time = time.time() self._cmd_id_mcu = msg[0] self._cmd_execution_status = msg[1] # Recorded before the branches below clear the host's in-progress flag, so a caller whose wait # ends on this packet already finds it in reported_idle_since_last_command(). with self._received_packet_cv: self._packet_seq += 1 self._last_packet_status = msg[1] self._last_packet_cmd_id = msg[0] # A startup verdict reply (QUERY_STARTUP_STATE). Not an execution status: none of the branches # below match it, so it neither completes, fails nor resends the command, and it is never idle # evidence (reported_idle_since_last_command). Taken only from a packet whose CRC matches: firmware # that answers the query always sends a real one, so a verdict status in a packet accepted on the # zero "checksum" (a misaligned read window, say) is not a verdict. if crc_matched and msg[1] in _STARTUP_VERDICT_STATUSES: piezo_dac_written = msg[19] & (1 << STARTUP_REPLY_FLAG_PIEZO_DAC_WRITTEN) self._startup_verdict_packet = ( msg[0], msg[1] - STARTUP_VERDICT_STATUS_BASE, (msg[20] << 8 | msg[21]) if piezo_dac_written else None, ) if (self._cmd_id_mcu == self._cmd_id) and ( self._cmd_execution_status == CMD_EXECUTION_STATUS.COMPLETED_WITHOUT_ERRORS ): if self.mcu_cmd_execution_in_progress: self.mcu_cmd_execution_in_progress = False elapsed_ms = (time.time() - self.last_command_send_timestamp) * 1000 self.log.debug( f"[MCU] <<< command {self._cmd_id} ({self._last_command_name()}) complete" f" (took {elapsed_ms:.1f}ms)" ) elif ( self.mcu_cmd_execution_in_progress and self._cmd_id_mcu != self._cmd_id and time.time() - self.last_command_send_timestamp > self.LAST_COMMAND_ACK_TIMEOUT and self.last_command is not None ): if self.retry > self.MAX_RETRY_COUNT: self.abort_current_command( reason=f"Command timed out without an ack after {self.LAST_COMMAND_ACK_TIMEOUT} [s], and {self.retry} retries" ) else: self.log.debug( f"[MCU] !!! command timed out without ack after {self.LAST_COMMAND_ACK_TIMEOUT}s, resending command" ) self.resend_last_command() elif ( self.mcu_cmd_execution_in_progress and self._cmd_execution_status == CMD_EXECUTION_STATUS.CMD_CHECKSUM_ERROR ): if self.retry > self.MAX_RETRY_COUNT: self.abort_current_command(reason=f"Checksum error and 10 retries for {self._cmd_id}") else: self.log.error("[MCU] !!! checksum error, resending command") self.resend_last_command() elif ( self.mcu_cmd_execution_in_progress and self._cmd_id_mcu == self._cmd_id and self._cmd_execution_status == CMD_EXECUTION_STATUS.CMD_EXECUTION_ERROR ): # Fail fast so callers don't wait the full ack timeout # for a completion the firmware says will never arrive. self.abort_current_command( reason="firmware reported CMD_EXECUTION_ERROR", recoverable=True, ) elif ( self.mcu_cmd_execution_in_progress and self._cmd_id_mcu != self._cmd_id and self._cmd_execution_status == CMD_EXECUTION_STATUS.COMPLETED_WITHOUT_ERRORS ): # Log when we receive an ACK for a different command than we're waiting for self.log.debug( f"[MCU] !!! received ack for command {self._cmd_id_mcu}, but waiting for command {self._cmd_id}" ) self.x_pos = self._payload_to_int( msg[2:6], MicrocontrollerDef.N_BYTES_POS ) # unit: microstep or encoder resolution self.y_pos = self._payload_to_int( msg[6:10], MicrocontrollerDef.N_BYTES_POS ) # unit: microstep or encoder resolution self.z_pos = self._payload_to_int( msg[10:14], MicrocontrollerDef.N_BYTES_POS ) # unit: microstep or encoder resolution theta_field = self._payload_to_int(msg[14:18], MicrocontrollerDef.N_BYTES_POS) # Firmware >= 1.6 with encoder reporting on: the theta field is the reported axis's # ENC_POS, byte 19 its flags and bytes 20-21 the clipped ENC_POS - XACTUAL. It is then # not a theta position, so theta_pos keeps its last value (a stage position readback # must not show a wheel encoder as an angle). With reporting off, and on older # firmware, byte 19 bit 0 is clear and the field is theta as it always was. # Firmware >= 1.8 with the focus wheel routed to the host: the field is the wheel's tick count, # flagged by FOCUS_WHEEL_FLAG_REPORTING (the firmware refuses this and encoder reporting together). if msg[1] in _STARTUP_VERDICT_STATUSES: # Firmware >= 1.9: a startup reply packet's bytes 14-21 are the reply (taken above), so these # fields keep their last values. pass elif msg[19] & (1 << ENC_FLAG.REPORTING): self.encoder_flags = msg[19] self.encoder_pos = theta_field self.encoder_deviation = self._payload_to_int(msg[20:22], 2) self.focus_wheel_count = None elif msg[19] & (1 << FOCUS_WHEEL_FLAG_REPORTING): self.encoder_flags = 0 self.focus_wheel_count = theta_field else: self.encoder_flags = 0 self.focus_wheel_count = None self.theta_pos = theta_field # unit: microstep or encoder resolution self.button_and_switch_state = msg[18] # joystick button tmp = self.button_and_switch_state & (1 << BIT_POS_JOYSTICK_BUTTON) joystick_button_pressed = tmp > 0 if self.joystick_button_pressed != joystick_button_pressed: if self.joystick_listener_events_enabled: for _, listener_fn in self.joystick_event_listeners: listener_fn(joystick_button_pressed) # The microcontroller wants us to send an ack back only when we see a False -> True # transition. handle that here. if joystick_button_pressed: self.ack_joystick_button_pressed() self.joystick_button_pressed = joystick_button_pressed # switch tmp = self.button_and_switch_state & (1 << BIT_POS_SWITCH) self.switch_state = tmp > 0 # Z limit switches (firmware >= LIMIT_SWITCH_CONFIG_MIN_FIRMWARE; older firmware leaves the bits 0) self.z_limit_left_triggered, self.z_limit_right_triggered = decode_z_limits( self.button_and_switch_state ) # Firmware version from byte 22: high nibble = major, low nibble = minor # Legacy firmware (pre-v1.0) sends 0x00, which gives version (0, 0) version_byte = msg[RESPONSE_BYTE_FIRMWARE_VERSION] self.firmware_version = (version_byte >> 4, version_byte & 0x0F) with self._received_packet_cv: self._handshake_answered = True self._received_packet_cv.notify_all() if self.new_packet_callback_external is not None: self.new_packet_callback_external(self) except Exception as e: self.log.error("Read loop failed, continuing to loop to see if anything can recover.", exc_info=e) def get_pos(self): return self.x_pos, self.y_pos, self.z_pos, self.theta_pos def _detect_firmware_version(self): """Detect firmware version by sending a harmless command: the connect handshake. Sends TURN_OFF_ALL_PORTS (a safe no-op if ports are already off) and waits for the first status packet that answers it, which the reader finds wherever in the stream it starts (_next_status_packet); the version is in that packet. Normally that is the controller's next packet. When the reader has nothing verifiable right before it to go by (stray bytes ran up to it, or the firmware is from before checksums), the command is sent again, first after HANDSHAKE_RESEND_INTERVAL_S and each time with an id picked at random, until the echoed id following these commands shows where packets start. An answer echoes one of these commands' ids, or the id of a command sent after them. It does not have to report the command complete: every packet carries the version, and a controller still busy with a move from a previous session answers IN_PROGRESS (with the newest command id) until RESET. Nothing read before the answer is used or acted on, so a packet queued before the write, which echoes an older command's id, is never taken; one echoing the same id (a previous session's, after the ids wrapped) comes from the same firmware, so its version is right too. This ensures supports_multi_port() returns accurate results immediately after Microcontroller initialization. """ timeout_s = Microcontroller.HANDSHAKE_TIMEOUT_S deadline = time.time() + timeout_s resend_interval_s = Microcontroller.HANDSHAKE_RESEND_INTERVAL_S sent = 0 while True: if sent: with self._cmd_lock: # send_command takes the next id self._cmd_id = self._handshake_resend_cmd_id() - 1 self.turn_off_all_ports() sent += 1 wait_s = min(resend_interval_s, max(deadline - time.time(), 0)) resend_interval_s = min(2 * resend_interval_s, Microcontroller.HANDSHAKE_RESEND_INTERVAL_MAX_S) with self._received_packet_cv: if self._received_packet_cv.wait_for(lambda: self._handshake_answered, timeout=wait_s): break if time.time() >= deadline: raise TimeoutError( f"No status packet within {timeout_s} [s] of asking for the firmware version ({sent} time(s))." f" {self._mcu_state()}" ) self.log.debug(f"Detected firmware version: {self.firmware_version}") def _handshake_resend_cmd_id(self) -> int: """The id for the handshake's next command: one this connection has not used, picked at random.""" unused = [i for i in Microcontroller.HANDSHAKE_RESEND_CMD_IDS if i not in self._handshake_cmd_ids] return random.choice(unused) def _handshake_state(self) -> str: """_mcu_state while no packet has answered the connect handshake: what the reader has seen instead.""" state = ( f"Sent cmd {self._cmd_id} ({self._last_command_name()});" f" read {self._handshake_bytes_read} byte(s) from the mcu, none of them a status packet answering it." ) if self._handshake_bytes_read == 0: return state + " The mcu is silent - check the serial connection." if self._handshake_echoes_seen: return state + ( f" {self._handshake_echoes_seen} time(s) something in them echoed a command of this connection, but" " never in a way that shows where its status packets start." ) if self._handshake_last_skipped is None: return state + " Nothing in them was a status packet with a valid checksum." cmd_id, status = self._handshake_last_skipped status_name = _CMD_EXECUTION_STATUS_NAMES.get(status, status) return state + ( f" The last status packet with a valid checksum echoed cmd {cmd_id} status={status_name}: the mcu is" " talking but did not take the command." ) def supports_multi_port(self) -> bool: """Check if firmware supports multi-port illumination commands. Multi-port illumination was added in firmware version 1.0. Legacy firmware (version 0.0) only supports single-source illumination. Returns: True if firmware version >= 1.0, False otherwise. """ return self.firmware_version >= (1, 0) def supports_limit_switch_config(self) -> bool: """True if the firmware has SET_LIMIT_SWITCH_CONFIG.""" return tuple(self.firmware_version) >= LIMIT_SWITCH_CONFIG_MIN_FIRMWARE def supports_startup_state(self) -> bool: """True if the firmware has STORE_CONFIG_SIGNATURE and QUERY_STARTUP_STATE.""" return tuple(self.firmware_version) >= STARTUP_STATE_MIN_FIRMWARE def _startup_state_command( self, command_code: int, signature: int, signature_format: int, required_axes_mask: int ) -> bytearray: """STORE_CONFIG_SIGNATURE or QUERY_STARTUP_STATE: [2..5] the signature (big-endian), [6] (format << 4) | mask. Older firmware would answer either with a success that does nothing, so refuse it here.""" if not self.supports_startup_state(): raise RuntimeError( f"Firmware {self.firmware_version[0]}.{self.firmware_version[1]} cannot store or report the startup " f"state (needs {STARTUP_STATE_MIN_FIRMWARE[0]}.{STARTUP_STATE_MIN_FIRMWARE[1]})." ) if not 0 <= signature <= 0xFFFFFFFF: raise ValueError(f"Configuration signature {signature} does not fit in 32 bits.") if not 0 <= signature_format <= 0x0F: raise ValueError(f"Signature format {signature_format} does not fit in a nibble.") if not 0 <= required_axes_mask <= 0b111: raise ValueError(f"Required axes mask {required_axes_mask:#b} has bits beyond X, Y and Z.") cmd = bytearray(self.tx_buffer_length) cmd[1] = command_code cmd[2:6] = signature.to_bytes(4, "big") cmd[6] = (signature_format << 4) | required_axes_mask return cmd def store_config_signature(self, signature: int, signature_format: int) -> None: """Store the signature of the configuration just sent (STORE_CONFIG_SIGNATURE) and wait for completion. A different signature or format than the one stored, or none stored (after power-up, INITIALIZE or a changed covered setting), clears every homed flag in the controller. """ self.send_command(self._startup_state_command(CMD_SET.STORE_CONFIG_SIGNATURE, signature, signature_format, 0)) self.wait_till_operation_is_completed() def query_startup_state( self, signature: int, signature_format: int, required_axes_mask: int, timeout_s: float = 2 ) -> StartupVerdict: """Ask the controller whether the stage is still homed under this configuration (QUERY_STARTUP_STATE). Returns the verdict from the first packet echoing this query's command id with a verdict status (STARTUP_VERDICT_STATUS_BASE + verdict), whatever the controller is busy with: the firmware sends the verdict in place of IN_PROGRESS, so a controller still running a crashed session's move answers too (as in _detect_firmware_version). It does not wait for completion: a verdict status is not one, so the host's in-progress flag stays as the packet left it, and RESET is the next command on either path. The earlier reply is cleared before the send, so a stale tuple can never match this query's id. The query must not be interleaved with other senders: any command the controller receives after it (HEARTBEAT included) ends the verdict reply. The heartbeat starts only after the constructor's query. The reply's piezo DAC code goes to startup_piezo_dac_code. Raises RuntimeError if no verdict arrives within timeout_s. """ cmd = self._startup_state_command(CMD_SET.QUERY_STARTUP_STATE, signature, signature_format, required_axes_mask) with self._received_packet_cv: self._startup_verdict_packet = None self.send_command(cmd) cmd_id = cmd[0] # as sent: another sender (the read loop's joystick ack) may have taken a newer id since with self._received_packet_cv: if not self._received_packet_cv.wait_for( lambda: self._startup_verdict_packet is not None and self._startup_verdict_packet[0] == cmd_id, timeout=timeout_s, ): raise RuntimeError(f"controller sent no startup verdict within {timeout_s} [s]. {self._mcu_state()}") verdict = StartupVerdict(self._startup_verdict_packet[1]) self.startup_piezo_dac_code = self._startup_verdict_packet[2] self.log.debug(f"Startup verdict: {verdict.name}") return verdict def _ask_startup_verdict(self) -> Optional[StartupVerdict]: """The constructor's startup query (QUERY_STARTUP_STATE) with this configuration's signature and the axes startup homes, and the log line saying which startup path it leads to and why. None, a normal startup, when the firmware cannot report the startup state, when startup homes no stage axis (not asked: with no axis required to be homed, the controller's homed check would pass on anything), or when no verdict arrived (another sender ended the reply, or a timeout): an unnecessary home at worst. """ if not self.supports_startup_state(): self.log.info( f"Firmware {self.firmware_version[0]}.{self.firmware_version[1]} cannot report homing state: " f"normal startup" ) return None required_axes_mask = required_homed_axes_mask() if required_axes_mask == 0: self.log.info("Startup homes no stage axis: normal startup") return None try: verdict = self.query_startup_state(config_signature(), CONFIG_SIGNATURE_FORMAT, required_axes_mask) except RuntimeError as e: self.log.warning(f"Asked the controller for its startup state and got none ({e}): normal startup") return None self.log.info(_STARTUP_VERDICT_LOG[verdict]) return verdict def check_limit_switch_compatibility(self) -> None: """Raise LimitSwitchConfigError if [LIMIT_SWITCHES] is invalid, or not the default and the firmware cannot apply it. Invalid content (an unknown key, a value that is not True or False) is refused first and on every serial device, simulated ones included: it would otherwise be ignored or read by truthiness. Older firmware answers SET_LIMIT_SWITCH_CONFIG with a success that does nothing, so its limit switches would stay at the stock settings while the configuration says otherwise. """ problems = limit_switch_config_problems() if problems: raise LimitSwitchConfigError( f"The configuration's [LIMIT_SWITCHES] section is invalid: {'; '.join(problems)}. Its keys are " f"__active_high and __enabled (axis x, y or z; side left or right), each " f"True or False." ) if self.supports_limit_switch_config(): return if self._is_simulated: self.log.info( "Simulated controller: skipping the [LIMIT_SWITCHES] firmware check (it models no limit switches)." ) return if all(limit_switch_config_byte(axis) == LIMIT_SWITCH_DEFAULT_CONFIG for axis in "xyz"): return settings = [] for axis in "XYZ": for side in ("LEFT", "RIGHT"): for setting in ("ENABLED", "ACTIVE_HIGH"): default = bool(LIMIT_SWITCH_DEFAULT_CONFIG & getattr(LIMIT_SWITCH_BITS, f"{side}_{setting}")) value = getattr(LIMIT_SWITCHES, f"{axis}_{side}_{setting}") if bool(value) != default: settings.append(f"{axis}_{side}_{setting}".lower() + f" = {value}") raise LimitSwitchConfigError( f"The configuration's [LIMIT_SWITCHES] section sets {', '.join(settings)}, but the controller runs " f"firmware {self.firmware_version[0]}.{self.firmware_version[1]}, which cannot apply limit-switch " f"settings. Flash firmware {LIMIT_SWITCH_CONFIG_MIN_FIRMWARE[0]}.{LIMIT_SWITCH_CONFIG_MIN_FIRMWARE[1]} " f"or newer onto the controller." ) def apply_limit_switch_config(self) -> None: """Send [LIMIT_SWITCHES] for X, Y and Z, defaults included, if the firmware supports it. On older firmware this does nothing: check_limit_switch_compatibility() has already refused a non-default configuration there. """ if not self.supports_limit_switch_config(): return for axis, name in ((AXIS.X, "x"), (AXIS.Y, "y"), (AXIS.Z, "z")): self.set_limit_switch_config(axis, limit_switch_config_byte(name)) self.wait_till_operation_is_completed() def get_button_and_switch_state(self): return self.button_and_switch_state def is_busy(self): return self.mcu_cmd_execution_in_progress def reported_idle_since_last_command(self) -> bool: """True only if the controller itself said, after the host's last command, that no command is in progress. That needs a packet received since the last send, echoing that command's id (so the firmware had read the command when it built the packet), with COMPLETED_WITHOUT_ERRORS or CMD_EXECUTION_ERROR: the two statuses the firmware sends only when nothing is in progress. IN_PROGRESS, CMD_CHECKSUM_ERROR (which masks the in-progress state), no packet since the send (a lost link) and is_busy() (the host's own flag, which abort_current_command() clears without stopping anything) are not evidence. """ with self._received_packet_cv: return ( self._packet_seq > self._packet_seq_at_last_send and self._last_packet_cmd_id == self._cmd_id and self._last_packet_status in (CMD_EXECUTION_STATUS.COMPLETED_WITHOUT_ERRORS, CMD_EXECUTION_STATUS.CMD_EXECUTION_ERROR) ) def set_callback(self, function): self.new_packet_callback_external = function def wait_till_operation_is_completed(self, timeout_limit_s=5): """ Wait for the current command to complete. If the wait times out, the current command isn't touched. To abort it, you should call the abort_current_command(...) method. """ with self._received_packet_cv: def still_busy(): return self.is_busy() and self.last_command_aborted_error is None self._received_packet_cv.wait_for(lambda: not still_busy(), timeout=timeout_limit_s) if still_busy(): raise TimeoutError(f"Current mcu operation timed out after {timeout_limit_s} [s]. {self._mcu_state()}") if self.last_command_aborted_error is not None: raise self.last_command_aborted_error def _last_command_name(self) -> str: cmd_type = self.last_command[1] if self.last_command is not None else -1 return _CMD_NAMES.get(cmd_type, f"UNKNOWN({cmd_type})") def _mcu_state(self) -> str: """Describe the last thing the mcu told us, for wait-timeout and stale-read messages.""" if self._framing is None: return self._handshake_state() status_name = _CMD_EXECUTION_STATUS_NAMES.get(self._cmd_execution_status, self._cmd_execution_status) since_read_s = time.time() - self._last_successful_read_time state = ( f"Sent cmd {self._cmd_id} ({self._last_command_name()}); mcu reports cmd {self._cmd_id_mcu}" f" status={status_name}; {since_read_s:.1f} [s] since a valid packet." ) if since_read_s > Microcontroller.STALE_READ_TIMEOUT: if self._rx_dropped: return state + ( f" The mcu is sending bytes, but none of the last {self._rx_dropped} is a status packet: the" " status stream is out of step." ) return state + " The mcu has gone quiet - check the serial connection." if self._cmd_id_mcu == self._cmd_id and self._cmd_execution_status == CMD_EXECUTION_STATUS.IN_PROGRESS: # Matches none of the read loop's recovery branches (ids match, so no ack-timeout resend; no # error status, so no abort), and every later blocking command will hit the same wall. return state + ( " The mcu is still talking but reports this command as in progress, so the firmware never" " finished a move and every command after it will time out too. Home the stage to clear it." ) return state @staticmethod def _int_to_payload(signed_int, number_of_bytes) -> int: actually_signed_int = int(round(signed_int)) if actually_signed_int >= 0: payload = actually_signed_int else: payload = 2 ** (8 * number_of_bytes) + actually_signed_int # find two's complement return int(payload) @staticmethod def _payload_to_int(payload, number_of_bytes) -> int: signed = 0 for i in range(number_of_bytes): signed = signed + int(payload[i]) * (256 ** (number_of_bytes - 1 - i)) if signed >= 256**number_of_bytes / 2: signed = signed - 256**number_of_bytes return int(signed) @staticmethod def _illumination_factor_byte(illumination_intensity_factor: float) -> int: """The byte the firmware receives: clamped as before, then int(round(f, 2) * 100) - which truncates (0.57 -> 56); kept exactly as master sends it.""" if illumination_intensity_factor > 1: illumination_intensity_factor = 1 if illumination_intensity_factor < 0: illumination_intensity_factor = 0.01 return int(round(illumination_intensity_factor, 2) * 100) def set_dac80508_scaling_factor_for_illumination(self, illumination_intensity_factor): """Set the illumination intensity scaling factor on the MCU. This factor scales the DAC output voltage for ALL illumination commands (both legacy single-source and new multi-port commands). Recommended values for different hardware: 0.6 = Squid LEDs (0-1.5V output range) 0.8 = Squid laser engine (0-2V output range) 1.0 = Full range (0-2.5V output, when DAC gain is 1 instead of 2) Args: illumination_intensity_factor: Scaling factor (0.01-1.0, clamped) """ factor_byte = self._illumination_factor_byte(illumination_intensity_factor) cmd = bytearray(self.tx_buffer_length) cmd[1] = CMD_SET.SET_ILLUMINATION_INTENSITY_FACTOR cmd[2] = factor_byte self.send_command(cmd) self.illumination_intensity_factor = factor_byte / 100.0