def open_instrument(self, model=None) -> None: """Doc.""" # auto-find serial connection for depletion laser if model is not None: self.autofind_address(model) try: # open self._rsrc = self._rm.open_resource( self.address, read_termination=self.read_termination, write_termination=self.write_termination, timeout=50, # ms open_timeout=50, # ms ) except AttributeError: # failed to auto-find address for depletion laser raise IOError( f"{self.log_ref} couldn't be opened - it is either turned off, unplugged or the address is used by another process" ) except ValueError: raise IOError( f"{self.log_ref} is unplugged or the address ({self.address}) is wrong." ) except visa.errors.VisaIOError: raise IOError( f"{self.log_ref} was manually disconnected while opening the instrument." )
def close_instrument(self) -> None: """Doc.""" try: self._rsrc.close() except AttributeError: raise IOError(f"{self.log_ref} was never opened") except visa.errors.VisaIOError: raise IOError(f"{self.log_ref} disconnected during operation.")
def get_latest_frame(self) -> np.ndarray: """Doc.""" try: return self._inst.latest_frame(copy=False) except uc480.UC480Error: raise IOError(f"{self.log_ref} disconnected after initialization.")
def create_ai_task( self, name: str, address: str, chan_specs: List[dict], samp_clk_cnfg: dict = {}, timing_params: dict = {}, ): """Doc.""" task = ni.Task(new_task_name=name) try: for chan_spec in chan_specs: task.ai_channels.add_ai_voltage_chan(**chan_spec) if samp_clk_cnfg: task.timing.cfg_samp_clk_timing(**samp_clk_cnfg) for key, val in timing_params.items(): setattr(task.timing, key, val) except ni.errors.DaqError: task.close() raise IOError( f"NI device address ({address}) is wrong, or data acquisition board is unplugged" ) else: self.tasks.ai.append(task)
def grab_image(self) -> np.ndarray: """Doc.""" try: return self._inst.grab_image( copy=False, exposure_time=self._inst._get_exposure()) except uc480.UC480Error: raise IOError(f"{self.log_ref} disconnected after initialization.")
def __init__(self, param_dict): [setattr(self, key, val) for key, val in param_dict.items()] self.log_ref = param_dict["log_ref"] self._inst = None if not list_instruments(module="cameras"): exc = IOError("No UC480 cameras detected.") err_hndlr(exc, sys._getframe(), locals(), dvc=self)
def open_instrument(self): """Doc.""" try: self._inst = uc480.UC480_Camera(serial=self.serial.encode(), reopen_policy="new") except Exception as exc: # general 'Exception' is due to bad exception handeling in instrumental-lib... raise IOError(f"{self.log_ref} disconnected - {exc}")
def flush(self) -> None: """Doc.""" mask = visa.constants.BufferOperation( 4) | visa.constants.BufferOperation(6) try: self._rsrc.flush(mask) except visa.errors.VisaIOError: raise IOError( f"{self.log_ref} disconnected! Reconnect and restart.")
def set_auto_exposure(self, should_turn_on: bool) -> None: """Doc.""" try: self._inst.set_auto_exposure(should_turn_on) except uc480.UC480Error: exc = IOError( f"{self.log_ref} was not properly closed.\nRestart to fix.") err_hndlr(exc, sys._getframe(), locals(), dvc=self) else: self.is_auto_exposure_on = should_turn_on
def open_instrument(self): """Doc.""" try: self._inst = ftd2xx.ftd2xx.openEx(self.serial) # self._inst = ftd2xx.aio.openEx(self.serial) except AttributeError: raise IOError(f"{self.log_ref} is not plugged in.") self._inst.setBitMode(255, self.bit_mode) # unsure about 255/0 self._inst.setTimeouts(self.timeout_ms, self.timeout_ms) self._inst.setLatencyTimer(self.ltncy_tmr_val) self._inst.setFlowControl(self.flow_ctrl) self._inst.setUSBParameters(self.tx_size)
def toggle(self, is_being_switched_on): """Doc.""" try: self.digital_write(self.address, is_being_switched_on) except DaqError: exc = IOError( f"NI device address ({self.address}) is wrong, or data acquisition board is unplugged" ) err_hndlr(exc, sys._getframe(), locals(), dvc=self) else: self.toggle_led_and_switch(is_being_switched_on) self.state = is_being_switched_on
def query(self, cmnd: str) -> float: """Doc.""" try: response = self._rsrc.query(cmnd) except visa.errors.VisaIOError: raise IOError( f"{self.log_ref} disconnected! Reconnect and restart.") else: try: extracted_float_string = re.findall(r"-?\d+\.?\d*", response)[0] except IndexError: # rarely happens return 0 return float(extracted_float_string)
def toggle(self, is_being_switched_on): """Doc.""" try: if is_being_switched_on: self._start_co_clock_sync() else: self.close_all_tasks() except DaqError: exc = IOError( f"NI device address ({self.address}) is wrong, or data acquisition board is unplugged" ) err_hndlr(exc, sys._getframe(), locals(), dvc=self) else: self.toggle_led_and_switch(is_being_switched_on) self.state = is_being_switched_on
def toggle_video_mode(self, should_turn_on: bool) -> None: """Doc.""" try: if should_turn_on: if self.is_auto_exposure_on: self._inst.start_live_video() self._inst.set_auto_exposure(True) else: self._inst.start_live_video( exposure_time=self._inst._get_exposure()) else: self._inst.stop_live_video() except uc480.UC480Error: raise IOError(f"{self.log_ref} disconnected after initialization.") else: self.is_in_video_mode = should_turn_on
def autofind_address(self, model: str) -> None: """Doc.""" # list all resource addresses resource_address_tuple = self._rm.list_resources() # open and save the opened ones in a list inst_list = [] for resource_name in resource_address_tuple: with suppress(visa.errors.VisaIOError): # VisaIOError - failed to open instrument, skip # try to open instrument inst = self._rm.open_resource( resource_name, read_termination=self.read_termination, write_termination=self.write_termination, timeout=50, # ms open_timeout=50, # ms ) # managed to open instrument, add to list. inst_list.append(inst) # 'model_query' the opened devices, and whoever responds is the one for idx, inst in enumerate(inst_list): try: self.model = inst.query(model) except visa.errors.VisaIOError as exc: if exc.abbreviation == "VI_ERROR_RSRC_BUSY": raise IOError( f"{self.log_ref} couldn't be opened - a restart might help!" ) else: pass else: self.address = resource_address_tuple[idx] break # close all saved resources with suppress(visa.errors.VisaIOError): # VisaIOError - this happens if device was disconnected during the autofind process... [inst.close() for inst in inst_list]
def set_parameter(self, name, value) -> None: """Doc.""" if name not in {"pixel_clock", "framerate", "exposure"}: raise ValueError(f"Unknown parameter '{name}'.") valid_value = Limits(getattr(self, f"{name}_range")).clamp(value) try: if name == "pixel_clock": self._inst._dev.PixelClock(uc480.lib.PIXELCLOCK_CMD_SET, int(valid_value)) self.update_parameter_ranges() elif name == "framerate": self._inst._dev.SetFrameRate(valid_value) self.update_parameter_ranges() elif name == "exposure": self._inst._set_exposure(f"{valid_value}ms") except uc480.UC480Error: exc = IOError( f"{self.log_ref} was not properly closed.\nRestart to fix.") err_hndlr(exc, sys._getframe(), locals(), dvc=self)