def stopFilm(self, message): """ Handle the 'stop film' message. """ if self.run_shutters: for task in [self.ct_task, self.ao_task, self.do_task]: if task is not None: try: task.stopTask() task.clearTask() except nicontrol.NIException as e: hdebug.logText("stop / clear failed for task " + str(task) + " with " + str(e)) # Need to explicitly clear these so that PyDAQmx will release the resources. self.ao_task = None self.ct_task = None self.do_task = None # Restore functionalities & notify modules that were using them. for waveform in self.analog_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(False) for waveform in self.digital_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(False) # This frees the waveform arrays & reset the oversampling attribute. super().stopFilm(message)
def dropEvent(self, event): # Initialize filenames variable filenames = [] # Tranfer urls to filenames for url in event.mimeData().urls(): filenames.append(str(url.toLocalFile())) # Sort file names filenames = sorted(filenames) # Identify first type name, firstType = os.path.splitext(filenames[0]) # Check to see if all types are the same sameType = [] for filename in filenames: name, fileType = os.path.splitext(filename) sameType.append(fileType == firstType) # If not, raise an error and abort load if not all(sameType): hdebug.logText(" Loaded mixed file types") QtGui.QMessageBox.information(self, "Too many file types", "") return # Load files if (firstType == '.dax'): # Load dax files self.loadMovie(filenames) elif (firstType == '.msc'): # Load mosaics for filename in sorted(filenames): self.loadMosaic(filename) else: hdebug.logText(" " + firstType + " is not recognized") QtGui.QMessageBox.information(self, "File type not recognized", "")
def fitAFunctionLS(data, params, fn): """ Does least squares fitting of a function. """ start_time = time.time() result = params errorfunction = lambda p: numpy.ravel( fn(*p)(*numpy.indices(data.shape)) - data) good = True [result, cov_x, infodict, mesg, success] = scipy.optimize.leastsq(errorfunction, params, full_output=1, maxfev=500) if (success < 1) or (success > 4): hdebug.logText("Fitting problem: " + mesg) #print "Fitting problem:", mesg good = False end_time = time.time() if (infodict["nfev"] > 70) or ((end_time - start_time) > 0.1): global last_warning_time if last_warning_time is None or ( (time.time() - last_warning_time) > 2.0): if False: print("> QPD-480 Slow fitting detected") print(">", infodict["nfev"], time.time() - start_time) print(">", params) print(">", result) print() last_warning_time = time.time() return [result, good]
def stopFilm(self, message): """ Handle the 'stop film' message. """ if self.run_shutters: self.errorDAQ = False #default error is False for task in [self.ct_task, self.ao_task, self.do_task]: if task is not None: try: task.stopTask() task.clearTask() errorDAQ_ = task.errorDAQ if errorDAQ_: self.errorDAQ = True except nicontrol.NIException as e: hdebug.logText("stop / clear failed for task " + str(task) + " with " + str(e)) #####BB patch to test DAQ error fid = open("C:\Data\errorDAQ.txt", 'w') fid.write(str(self.errorDAQ)) fid.close() # Need to explicitly clear these so that PyDAQmx will release the resources. self.ao_task = None self.ct_task = None self.do_task = None # Restore functionalities & notify modules that were using them. for waveform in self.analog_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(False) for waveform in self.digital_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(False) # This frees the waveform arrays & reset the oversampling attribute. super().stopFilm(message)
def stopFilm(self, message): """ Handle the 'stop film' message. """ if self.run_shutters: for task in [self.ct_task, self.ao_task, self.do_task]: if task is not None: try: task.stopTask() task.clearTask() except nicontrol.NIException as e: hdebug.logText("stop / clear failed for task " + str(task) + " with " + str(e)) # Need to explicitly clear these so that PyDAQmx will release the resources. self.ao_task = None self.ct_task = None self.do_task = None # Restore functionalities & notify modules that were using them. for waveform in self.analog_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(False) for waveform in self.digital_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(False) # This frees the waveform arrays & reset the oversampling attribute. super().stopFilm(message)
def fitAFunctionLS(data, params, fn): """ Does least squares fitting of a function. """ start_time = time.time() result = params errorfunction = lambda p: numpy.ravel(fn(*p)(*numpy.indices(data.shape)) - data) good = True [result, cov_x, infodict, mesg, success] = scipy.optimize.leastsq(errorfunction, params, full_output = 1, maxfev = 500) if (success < 1) or (success > 4): hdebug.logText("Fitting problem: " + mesg) #print "Fitting problem:", mesg good = False end_time = time.time() if (infodict["nfev"] > 70) or ((end_time - start_time) > 0.1): global last_warning_time if last_warning_time is None or ((time.time() - last_warning_time) > 2.0): print("> QPD-480 Slow fitting detected") print(">", infodict["nfev"], time.time() - start_time) print(">", params) print(">", result) print() last_warning_time = time.time() return [result, good]
def setupDigital1(self, frequency, wv_clock): self.do_task1 = None if (len(self.digital_waveforms) > 0): # Mark all the functionalities whose resources we'll need during # filming, and have them emit the 'filming' signal. for waveform in self.digital_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(True) # Sort by board, channel. digital_data = sorted(self.digital_waveforms, key=lambda x: x.getSource()) # Set waveforms. digital_data_temp = [] for data in digital_data: if data.getSource().rsplit('/')[1] == "Dev2": digital_data_temp.append(data) digital_data = digital_data_temp waveforms = [] for data in digital_data: waveforms.append(data.getWaveform()) print('test is here4') print(data.getWaveform()) def startDoTask(): try: # Create channels. self.do_task1 = nicontrol.DigitalWaveformOutput( source=digital_data[0].getSource()) for i in range(len(digital_data) - 1): self.do_task1.addChannel( source=digital_data[i + 1].getSource()) # Add waveform self.do_task1.setWaveforms(waveforms=waveforms, sample_rate=frequency, clock=wv_clock) # Start task. self.do_task1.startTask() except nicontrol.NIException as exception: print(exception) return True return False iters = 0 while (iters < 5) and startDoTask(): hdebug.logText("startDoTask failed " + str(iters)) time.sleep(0.1) iters += 1 if iters == 5: hdebug.logText("startDoTask critical failure") raise NidaqModuleException( "NIException: startDoTask critical failure")
def newParameters(self, parameters): if self.spinning_disk: try: self.spinning_disk.newParameters(parameters) # Pass all parameters except halExceptions.HardwareException as error: error_message = "newParameters error in spinning disk control: \n" + str(error) hdebug.logText(error_message) raise halModule.NewParametersException(error_message)
def decRefCount(self, name = None): # This is helpful for debugging who has not responded to the message. if True: hdebug.logText(",".join(["handled by", str(self.m_id), str(name), self.m_type])) self.ref_count -= 1 if (self.ref_count == 0): self.processed.emit(self)
def getData(self): if self.task is None: self.createTask() try: return self.task.getData() except nicontrol.NIException as exception: hdebug.logText("AITaskFunctionality Error", str(exception)) self.task.stopTask() self.createTask()
def getSettings(self): if not self.tcp_client.isConnected(): hdebug.logText("getSettings: not connected to HAL.") return self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage(True)) self.sendFirstMessage()
def getSettings(self): if not self.tcp_client.isConnected(): hdebug.logText("getSettings: not connected to HAL.") return self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage(True)) self.sendFirstMessage()
def getData(self): if self.task is None: self.createTask() try: return self.task.getData() except nicontrol.NIException as exception: hdebug.logText("AITaskFunctionality Error", str(exception)) self.task.stopTask() self.createTask()
def printException(self): e_msg = "\n" e_msg += "Got an exception from '" + self.source + "' of type '" + self.message + "'!\n" e_msg += "\n" e_msg += "Traceback when the exception occurred:" e_msg += "\n" e_msg += self.stack_trace e_msg += "\n" print(e_msg) hdebug.logText(e_msg)
def newParameters(self, parameters): if self.spinning_disk: try: self.spinning_disk.newParameters( parameters) # Pass all parameters except halExceptions.HardwareException as error: error_message = "newParameters error in spinning disk control: \n" + str( error) hdebug.logText(error_message) raise halModule.NewParametersException(error_message)
def output(self, voltage): super().output(voltage) if self.task is None: self.createTask() try: self.task.output(voltage) except nicontrol.NIException as exception: hdebug.logText("AOTaskFunctionality Error", str(exception)) self.task.stopTask() self.createTask()
def output(self, voltage): super().output(voltage) if self.task is None: self.createTask() try: self.task.output(voltage) except nicontrol.NIException as exception: hdebug.logText("AOTaskFunctionality Error", str(exception)) self.task.stopTask() self.createTask()
def gotoPosition(self, stagex, stagey): if not self.tcp_client.isConnected(): hdebug.logText("gotoPosition: not connected to HAL.") return if not self.got_settings: self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage()) self.messages.append(moveStageMessage(stagex, stagey, True)) self.sendFirstMessage()
def getPosition(self): if not self.tcp_client.isConnected(): hdebug.logText("getPosition: not connected to HAL.") return if not self.got_settings: self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage()) self.messages.append(getPositionMessage()) self.sendFirstMessage()
def gotoPosition(self, stagex, stagey): if not self.tcp_client.isConnected(): hdebug.logText("gotoPosition: not connected to HAL.") return if not self.got_settings: self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage()) self.messages.append(moveStageMessage(stagex, stagey, True)) self.sendFirstMessage()
def setupAnalog(self, frequency, wv_clock): """ Configures for analog waveform output. """ self.ao_task = None if (len(self.analog_waveforms) > 0): # Mark all the functionalities whose resources we'll need during # filming, and have them emit the 'filming' signal. for waveform in self.analog_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(True) # Sort by source. analog_data = sorted(self.analog_waveforms, key=lambda x: x.getSource()) # Set waveforms. waveforms = [] for data in analog_data: waveforms.append(data.getWaveform()) def startAoTask(): try: # Create channels. self.ao_task = nicontrol.AnalogWaveformOutput( source=analog_data[0].getSource()) for i in range(len(analog_data) - 1): self.ao_task.addChannel( source=analog_data[i + 1].getSource()) # Add waveforms self.ao_task.setWaveforms(waveforms=waveforms, sample_rate=frequency, clock=wv_clock) # Start task. self.ao_task.startTask() except nicontrol.NIException as exception: print(exception) return True return False iters = 0 while (iters < 5) and startAoTask(): hdebug.logText("startAoTask failed " + str(iters)) time.sleep(0.1) iters += 1 if (iters == 5): hdebug.logText("startAoTask critical failure") raise NidaqModuleException( "NIException: startAoTask critical failure")
def getPosition(self): if not self.tcp_client.isConnected(): hdebug.logText("getPosition: not connected to HAL.") return if not self.got_settings: self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage()) self.messages.append(getPositionMessage()) self.sendFirstMessage()
def position(self): if self.live: try: [self.x, self.y] = map(lambda x: float(x) * self.unit_to_um, self.commWithResp("W X Y").split(" ")[1:3]) except: hdebug.logText(" Warning: Bad position from ASI stage.") return [self.x, self.y, 0.0] else: return [0.0, 0.0, 0.0]
def stopFilm(self): """ Called at the end of filming (when shutters are active). """ illuminationHardware.DaqModulation.stopFilm(self) for task in [self.ct_task, self.ao_task, self.do_task]: if task: try: task.stopTask() task.clearTask() except nicontrol.NIException as e: hdebug.logText("stop / clear failed for task " + str(task) + " with " + str(e))
def stopFilm(self): """ Called at the end of filming (when shutters are active). """ illuminationHardware.DaqModulation.stopFilm(self) for task in [self.ct_task, self.ao_task, self.do_task]: if task: try: task.stopTask() task.clearTask() except nicontrol.NIException as e: hdebug.logText("stop / clear failed for task " + str(task) + " with " + str(e))
def setupAnalog(self, frequency, wv_clock): """ Configures for analog waveform output. """ self.ao_task = None if (len(self.analog_waveforms) > 0): # Mark all the functionalities whose resources we'll need during # filming, and have them emit the 'filming' signal. for waveform in self.analog_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(True) # Sort by source. analog_data = sorted(self.analog_waveforms, key = lambda x: x.getSource()) # Set waveforms. waveforms = [] for data in analog_data: waveforms.append(data.getWaveform()) def startAoTask(): try: # Create channels. self.ao_task = nicontrol.AnalogWaveformOutput(source = analog_data[0].getSource()) for i in range(1, len(analog_data)): self.ao_task.addChannel(source = analog_data[i].getSource()) # Add waveforms self.ao_task.setWaveforms(waveforms = waveforms, sample_rate = frequency, clock = wv_clock) # Start task. self.ao_task.startTask() except nicontrol.NIException as exception: print(exception) return True return False iters = 0 while (iters < 5) and startAoTask(): hdebug.logText("startAoTask failed " + str(iters)) time.sleep(0.1) iters += 1 if (iters == 5): hdebug.logText("startAoTask critical failure") raise NidaqModuleException("NIException: startAoTask critical failure")
def handleProcessed(self, message): """ Removes a processed message from the queue of sent messages and performs message finalization. """ # Remove message from list of sent messages. self.sent_messages.remove(message) # Disconnect messages processed signal. message.processed.disconnect(self.handleProcessed) # Call message finalizer. message.finalize() # Always exit on exceptions in strict mode. if self.strict and message.hasErrors(): for m_error in message.getErrors(): if m_error.hasException(): m_error.printException() self.cleanUp() return # Notify the sender if errors occured while processing the # message and exit if the sender doesn't handle the error. if message.hasErrors(): if not message.getSource().handleErrors(sent_message): self.cleanUp() return # Check the responses if we are in strict mode. if self.strict: validator = halMessage.valid_messages[message.m_type].get("resp") for response in message.getResponses(): halMessage.validateResponse(validator, message, response) # Notify the sender of any responses to the message. message.getSource().handleResponses(message) # Print a warning if the message was 'get functionality' # and there were no responses. if message.isType("get functionality") and not message.hasResponses(): print(">> Warning functionality '" + message.getData()["name"] + "' not found!") hdebug.logText("no functionality " + message.getData()["name"]) # Start message processing timer in case there are other messages # waiting for this message to get finalized. self.startMessageTimer()
def handleProcessed(self, message): """ Removes a processed message from the queue of sent messages and performs message finalization. """ # Remove message from list of sent messages. self.sent_messages.remove(message) # Disconnect messages processed signal. message.processed.disconnect(self.handleProcessed) # Call message finalizer. message.finalize() # Always exit on exceptions in strict mode. if self.strict and message.hasErrors(): for m_error in message.getErrors(): if m_error.hasException(): m_error.printException() self.cleanUp() return # Notify the sender if errors occured while processing the # message and exit if the sender doesn't handle the error. if message.hasErrors(): if not message.getSource().handleErrors(sent_message): self.cleanUp() return # Check the responses if we are in strict mode. if self.strict: validator = halMessage.valid_messages[message.m_type].get("resp") for response in message.getResponses(): halMessage.validateResponse(validator, message, response) # Notify the sender of any responses to the message. message.getSource().handleResponses(message) # Print a warning if the message was 'get functionality' # and there were no responses. if message.isType("get functionality") and not message.hasResponses(): print(">> Warning functionality '" + message.getData()["name"] + "' not found!") hdebug.logText("no functionality " + message.getData()["name"]) # Start message processing timer in case there are other messages # waiting for this message to get finalized. self.startMessageTimer()
def handleMosaicViewDropEvent(self, filenames_list): file_type = os.path.splitext(filenames_list[0])[1] # Check for .dax files. if (file_type == '.dax') or (file_type == ".tif"): self.image_capture.loadMovies(filenames_list, 0) # Check for mosaic files. elif (file_type == '.msc'): for filename in sorted(filenames_list): self.loadMosaic(filename) else: hdebug.logText(" " + file_type + " is not recognized") QtGui.QMessageBox.information(self, "File type not recognized", "")
def handleMessageReceived(self, message): if message.hasError(): hdebug.logText("tcp error: " + message.getErrorMessage()) self.messages = [] self.waiting_for_response = False return # # If the message does not involve taking a movie and there are no more # messages then emit the otherComplete signal. # if (message.getData("is_other") == True) and (len(self.messages) == 0): self.otherComplete.emit() if (message.getType() == "Get Mosaic Settings"): self.got_settings = True #coord.Point.pixels_to_um = message.getResponse("pixels_to_um") i = 1 while message.getResponse("obj" + str(i)) is not None: self.newObjectiveData.emit( message.getResponse("obj" + str(i)).split(",")) i += 1 if (message.getType() == "Get Objective"): if self.curr_objective is None or ( self.curr_objective != message.getResponse("objective")): self.curr_objective = message.getResponse("objective") self.changeObjective.emit(self.curr_objective) if (message.getType() == "Get Stage Position"): a_point = coord.Point(message.getResponse("stage_x"), message.getResponse("stage_y"), "um") self.getPositionComplete.emit(a_point) # # self.loadImage() will emit the captureComplete signal. # if (message.getType() == "Take Movie"): self.loadImage(self.directory + message.getData("name") + ".dax") if (len(self.messages) > 0): self.tcp_client.sendMessage(self.messages.pop(0)) else: self.waiting_for_response = False
def captureStart(self, stagex, stagey): print("captureStart", stagex, stagey) with contextlib.suppress(FileNotFoundError): os.remove(self.fullname()) os.remove(self.fullname(extension=".xml")) if not self.tcp_client.isConnected(): hdebug.logText("captureStart: not connected to HAL.") return False if not self.got_settings: self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage()) self.messages.append(moveStageMessage(stagex, stagey)) self.messages.append(movieMessage(self.filename, self.directory)) self.sendFirstMessage() return True
def position(self): if True: #self.live try: pos = self.connection.commWithResp("2HW X Y") # print(pos) [posX, posY] = pos.split(" ")[1:3] # why the answer is only 1:3 here and 2:4 above I don't know self.x = float(posX)*self.unit_to_um self.y = float(posY)*self.unit_to_um except: print('error') hdebug.logText(" Warning: Bad position from ASI stage.") return {"x" : self.x, "y" : self.y} # return [self.x, self.y, 0.0] else: return {"x" : 0, "y" : 0}
def handleMessageReceived(self, message): if message.hasError(): hdebug.logText("tcp error: " + message.getErrorMessage()) self.messages = [] self.waiting_for_response = False return # # If the message does not involve taking a movie and there are no more # messages then emit the otherComplete signal. # if (message.getData("is_other") == True) and (len(self.messages) == 0): self.otherComplete.emit() if (message.getType() == "Get Mosaic Settings"): self.got_settings = True #coord.Point.pixels_to_um = message.getResponse("pixels_to_um") i = 1 while message.getResponse("obj" + str(i)) is not None: self.newObjectiveData.emit(message.getResponse("obj" + str(i)).split(",")) i += 1 if (message.getType() == "Get Objective"): if self.curr_objective is None or (self.curr_objective != message.getResponse("objective")): self.curr_objective = message.getResponse("objective") self.changeObjective.emit(self.curr_objective) if (message.getType() == "Get Stage Position"): a_point = coord.Point(message.getResponse("stage_x"), message.getResponse("stage_y"), "um") self.getPositionComplete.emit(a_point) # # self.loadImage() will emit the captureComplete signal. # if (message.getType() == "Take Movie"): self.loadImage(self.directory + message.getData("name") + ".dax") if (len(self.messages) > 0): self.tcp_client.sendMessage(self.messages.pop(0)) else: self.waiting_for_response = False
def captureStart(self, stagex, stagey): print("captureStart", stagex, stagey) if os.path.exists(self.fullname()): os.remove(self.fullname()) os.remove(self.fullname(extension = ".xml")) if not self.tcp_client.isConnected(): hdebug.logText("captureStart: not connected to HAL.") return False if not self.got_settings: self.messages.append(mosaicSettingsMessage()) self.messages.append(objectiveMessage()) self.messages.append(moveStageMessage(stagex, stagey)) self.messages.append(movieMessage(self.filename, self.directory)) self.sendFirstMessage() return True
def __init__(self, camera_id, ini_file="uc480_settings.ini"): super().__init__(camera_id) # Initialize camera. check(uc480.is_InitCamera(ctypes.byref(self), ctypes.wintypes.HWND(0)), "is_InitCamera") #check(uc480.is_SetErrorReport(self, IS_ENABLE_ERR_REP)) # Get some information about the camera. self.info = CameraProperties() check(uc480.is_GetSensorInfo(self, ctypes.byref(self.info)), "is_GetSensorInfo") self.im_width = self.info.nMaxWidth self.im_height = self.info.nMaxHeight # Initialize some general camera settings. if (os.path.exists(ini_file)): self.loadParameters(ini_file) hdebug.logText("uc480 loaded parameters file " + ini_file, to_console=False) else: check(uc480.is_SetColorMode(self, IS_SET_CM_Y8), "is_SetColorMode") check(uc480.is_SetGainBoost(self, IS_SET_GAINBOOST_OFF), "is_SetGainBoost") check(uc480.is_SetGamma(self, 1), "is_SetGamma") check( uc480.is_SetHardwareGain(self, 0, IS_IGNORE_PARAMETER, IS_IGNORE_PARAMETER, IS_IGNORE_PARAMETER), "is_SetHardwareGain") hdebug.logText("uc480 used default settings.", to_console=False) # Setup capture parameters. self.bitpixel = 8 # This is correct for a BW camera anyway.. self.cur_frame = 0 self.data = False self.id = 0 self.image = False self.running = False self.setBuffers()
def setupCounter(self, frequency): """ Configures the counter for filming. """ self.ct_task = None if (self.oversampling > 1): def startCtTask(): try: self.ct_task = nicontrol.CounterOutput( source=self.timing.get("counter"), frequency=frequency, duty_cycle=0.5) self.ct_task.setCounter(number_samples=self.oversampling) rising_edge = True if self.timing.has("rising_edge"): rising_edge = self.timing.get("rising_edge") self.ct_task.setTrigger( trigger_source=self.timing.get("camera_fire_pin"), rising_edge=rising_edge) self.ct_task.startTask() except nicontrol.NIException as exception: print(exception) return True return False iters = 0 while (iters < 5) and startCtTask(): hdebug.logText("startCtTask failed " + str(iters)) time.sleep(0.5) iters += 1 if (iters == 5): hdebug.logText("startCtTask critical failure") raise NidaqModuleException( "NIException: startCtTask critical failure")
def dropEvent(self, event): # Initialize filenames variable filenames = [] # Tranfer urls to filenames for url in event.mimeData().urls(): filenames.append(str(url.toLocalFile())) # Sort file names filenames = sorted(filenames) # Identify first type name, firstType = os.path.splitext(filenames[0]) # Check to see if all types are the same sameType = [] for filename in filenames: name, fileType = os.path.splitext(filename) sameType.append(fileType == firstType) # If not, raise an error and abort load if not all(sameType): hdebug.logText(" Loaded mixed file types") QtGui.QMessageBox.information(self, "Too many file types", "") return # Load files if (firstType == '.dax'): # Load dax files self.loadMovie(filenames) elif (firstType == '.msc'): # Load mosaics for filename in sorted(filenames): self.loadMosaic(filename) else: hdebug.logText(" " + firstType + " is not recognized") QtGui.QMessageBox.information(self, "File type not recognized", "")
def __init__(self, camera_id, ini_file = "uc480_settings.ini"): super().__init__(camera_id) # Initialize camera. check(uc480.is_InitCamera(ctypes.byref(self), ctypes.wintypes.HWND(0)), "is_InitCamera") #check(uc480.is_SetErrorReport(self, IS_ENABLE_ERR_REP)) # Get some information about the camera. self.info = CameraProperties() check(uc480.is_GetSensorInfo(self, ctypes.byref(self.info)), "is_GetSensorInfo") self.im_width = self.info.nMaxWidth self.im_height = self.info.nMaxHeight # Initialize some general camera settings. if (os.path.exists(ini_file)): self.loadParameters(ini_file) hdebug.logText("uc480 loaded parameters file " + ini_file, to_console = False) else: check(uc480.is_SetColorMode(self, IS_SET_CM_Y8), "is_SetColorMode") check(uc480.is_SetGainBoost(self, IS_SET_GAINBOOST_OFF), "is_SetGainBoost") check(uc480.is_SetGamma(self, 1), "is_SetGamma") check(uc480.is_SetHardwareGain(self, 0, IS_IGNORE_PARAMETER, IS_IGNORE_PARAMETER, IS_IGNORE_PARAMETER), "is_SetHardwareGain") hdebug.logText("uc480 used default settings.", to_console = False) # Setup capture parameters. self.bitpixel = 8 # This is correct for a BW camera anyway.. self.cur_frame = 0 self.data = False self.id = 0 self.image = False self.running = False self.setBuffers()
def setupCounter(self, frequency): """ Configures the counter for filming. """ self.ct_task = None if (self.oversampling > 1): def startCtTask(): try: self.ct_task = nicontrol.CounterOutput(source = self.timing.get("counter"), frequency = frequency, duty_cycle = 0.5) self.ct_task.setCounter(number_samples = self.oversampling) rising_edge = True if self.timing.has("rising_edge"): rising_edge = self.timing.get("rising_edge") self.ct_task.setTrigger( trigger_source = self.timing.get("camera_fire_pin"), rising_edge = rising_edge) self.ct_task.startTask() except nicontrol.NIException as exception: print(exception) return True return False iters = 0 while (iters < 5) and startCtTask(): hdebug.logText("startCtTask failed " + str(iters)) time.sleep(0.5) iters += 1 if (iters == 5): hdebug.logText("startCtTask critical failure") raise NidaqModuleException("NIException: startCtTask critical failure")
def handleMessageReceived(self, message): self.busy = False # Save this property of the message as the message finalizer # could change self.current_message by creating a new message. disconnect = self.current_message.getDisconnect() # HAL only sends messages in response to requests, so we can # assume that the message we received is a response to the # last message that we sent. if not (message.getID() == self.current_message.getMessageID()): warnings.warn("Received a response to a different message.") elif message.hasError(): err_msg = "tcp error: " + message.getErrorMessage() warnings.warn(err_msg) hdebug.logText(err_msg) else: # Warning! This can change self.current_message. self.current_message.finalizer(message) # Disconnect from HAL if requested. Note that if the message # finalizer created a new message this will be a NOP. if disconnect: self.stopCommunication()
def run(self): while True: # Block here waiting for a connection. [client_sock, client_info] = self.server_sock.accept() # Initialization of a new connection. hdebug.logText("Bluetooth: Connected.") self.mutex.lock() self.client_sock = client_sock connected = True self.connected = True self.images_sent = 0 self.start_time = time.time() # Send initial configuration information. if self.filming: self.messages.append("startfilm") else: self.messages.append("stopfilm") self.mutex.unlock() while connected: # Block here waiting for a string from the paired device. data = self.client_sock.recv(1024) if (len(data) == 0): self.mutex.lock() connect = False self.connected = False self.drag_gain = 1.0 self.messages = [] self.show_camera = True images_per_second = float( self.images_sent) / float(time.time() - self.start_time) hdebug.logText("Bluetooth: Disconnected") hdebug.logText( "Bluetooth: Sent {0:.2f} images per second.".format( images_per_second)) self.mutex.unlock() else: for datum in data.split("<>"): if (len(datum) > 0): self.newData.emit(datum) self.mutex.lock() connected = self.connected self.mutex.unlock()
def check(fn_return, fn_name = ""): if not (fn_return == IS_SUCCESS): hdebug.logText("uc480: Call failed with error " + str(fn_return) + " " + fn_name)
def setupDigital(self, frequency, wv_clock): self.do_task = None if (len(self.digital_waveforms) > 0): # Mark all the functionalities whose resources we'll need during # filming, and have them emit the 'filming' signal. for waveform in self.digital_waveforms: self.daq_fns_by_source[waveform.getSource()].setFilming(True) # Sort by board, channel. digital_data = sorted(self.digital_waveforms, key=lambda x: x.getSource()) # Set waveforms. waveforms = [] source_list = [] for data in digital_data: waveforms.append(data.getWaveform()) source_list.append(data.getSource().rsplit('/')[1]) source_list_unified = list(OrderedDict.fromkeys(source_list)) source_list_dict = {i: source_list.count(i) for i in source_list} def startDoTask(): try: # Create channels. for ii in range(len(source_list_unified)): if ii == 0: digital_data_temp = digital_data[:source_list_dict[ source_list_unified[0]]] else: digital_data_temp = digital_data[ source_list_dict[source_list_unified[0]]:] # Create channels. self.do_task = nicontrol.DigitalWaveformOutput( source=digital_data_temp[0].getSource()) for i in range(len(digital_data_temp) - 1): self.do_task.addChannel( source=digital_data_temp[i + 1].getSource()) # Add waveform self.do_task.setWaveforms(waveforms=waveforms, sample_rate=frequency, clock=wv_clock) # Start task. self.do_task.startTask() except nicontrol.NIException as exception: print(exception) return True return False iters = 0 while (iters < 5) and startDoTask(): hdebug.logText("startDoTask failed " + str(iters)) time.sleep(0.1) iters += 1 if iters == 5: hdebug.logText("startDoTask critical failure") raise NidaqModuleException( "NIException: startDoTask critical failure")
def __init__(self, hardware, parameters, parent): QtCore.QThread.__init__(self, parent) halModule.HalModule.__init__(self) self.click_step = 1.0 self.click_timer = QtCore.QTimer(self) self.click_x = 0.0 self.click_y = 0.0 self.client_sock = False self.connected = False self.default_image = QtGui.QImage("bt_image.png") self.drag_gain = 1.0 self.drag_multiplier = 100.0 self.drag_x = 0.0 self.drag_y = 0.0 self.filming = False self.image_is_new = True self.images_sent = 0 self.is_down = False self.is_drag = False self.lock_jump_size = 0.025 self.messages = [] self.mutex = QtCore.QMutex() self.send_pictures = hardware.get("send_pictures") self.show_camera = True self.start_time = 0 self.which_camera = "camera1" parameters.add( "bluetooth.z_step", params.ParameterRangeFloat("Z step size in um", "z_step", 0.025, 0.0, 1.0)) # Set current image to default. self.current_image = self.default_image # Setup bluetooth socket. have_bluetooth = True try: self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.server_sock.bind(("", bluetooth.PORT_ANY)) self.server_sock.listen(1) port = self.server_sock.getsockname()[1] hdebug.logText( "Bluetooth: Listening on RFCOMM channel {0:d}".format(port)) uuid = "3e1f9ea8-9c11-11e3-b248-425861b86ab6" bluetooth.advertise_service( self.server_sock, "halServer", service_id=uuid, service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS], profiles=[bluetooth.SERIAL_PORT_PROFILE], ) except: print traceback.format_exc() hdebug.logText("Failed to start Bluetooth") have_bluetooth = False if have_bluetooth: # Setup timer. self.click_timer.setInterval(200) self.click_timer.timeout.connect(self.handleClickTimer) self.click_timer.setSingleShot(True) # Connect signals. self.newData.connect(self.handleNewData) self.start(QtCore.QThread.NormalPriority)
def logEvent(self, event_name): hdebug.logText(",".join([event_name, str(self.m_id), self.source.module_name, self.m_type]))
def check(fn_return, fn_name=""): if not (fn_return == IS_SUCCESS): hdebug.logText("uc480: Call failed with error " + str(fn_return) + " " + fn_name)
def startFilm(self, frames_per_second, oversampling): """ Called at the start of filming (when shutters are active). """ super().startFilm(frames_per_second, oversampling) # Calculate frequency. This is set slightly higher than the camere # frequency so that we are ready at the start of the next frame. frequency = (1.01 * seconds_per_frame) * float(oversampling) # If oversampling is 1 then just trigger the ao_task # and do_task directly off the camera fire pin. wv_clock = self.waveform_clock if (oversampling == 1): wv_clock = "PFI" + str(self.counter_trigger) # Setup the counter. if self.counter_board and (oversampling > 1): def startCtTask(): try: self.ct_task = nicontrol.CounterOutput( self.counter_board, self.counter_id, frequency, 0.5) self.ct_task.setCounter(oversampling) self.ct_task.setTrigger(self.counter_trigger) self.ct_task.startTask() except nicontrol.NIException: return True return False iters = 0 while (iters < 5) and startCtTask(): hdebug.logText("startCtTask failed " + str(iters)) self.ct_task.clearTask() time.sleep(0.5) iters += 1 if iters == 5: hdebug.logText("startCtTask critical failure") raise nicontrol.NIException( "NIException: startCtTask critical failure") else: self.ct_task = False # Setup analog waveforms. if (len(self.analog_data) > 0): # Sort by board, channel. analog_data = sorted(self.analog_data, key=lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(analog_data)): waveform += analog_data[i][2] def startAoTask(): try: # Create channels. self.ao_task = nicontrol.AnalogWaveformOutput( analog_data[0][0], analog_data[0][1]) for i in range(len(analog_data) - 1): self.ao_task.addChannel(analog_data[i + 1][0], analog_data[i + 1][1]) # Add waveform self.ao_task.setWaveform(waveform, frequency, clock=wv_clock) # Start task. self.ao_task.startTask() except nicontrol.NIException: return True return False iters = 0 while (iters < 5) and startAoTask(): hdebug.logText("startAoTask failed " + str(iters)) self.ao_task.clearTask() time.sleep(0.1) iters += 1 if iters == 5: hdebug.logText("startAoTask critical failure") raise nicontrol.NIException( "NIException: startAoTask critical failure") else: self.ao_task = False # Setup digital waveforms. if (len(self.digital_data) > 0): # Sort by board, channel. digital_data = sorted(self.digital_data, key=lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(digital_data)): waveform += digital_data[i][2] def startDoTask(): try: # Create channels. self.do_task = nicontrol.DigitalWaveformOutput( digital_data[0][0], digital_data[0][1]) for i in range(len(digital_data) - 1): self.do_task.addChannel(digital_data[i + 1][0], digital_data[i + 1][1]) # Add waveform self.do_task.setWaveform(waveform, frequency, clock=wv_clock) # Start task. self.do_task.startTask() except nicontrol.NIException: return True return False iters = 0 while (iters < 5) and startDoTask(): hdebug.logText("startDoTask failed " + str(iters)) self.do_task.clearTask() time.sleep(0.1) iters += 1 if iters == 5: hdebug.logText("startDoTask critical failure") raise nicontrol.NIException( "NIException: startDoTask critical failure") else: self.do_task = False
def startFilm(self, frames_per_second, oversampling): """ Called at the start of filming (when shutters are active). """ super().startFilm(frames_per_second, oversampling) # Calculate frequency. This is set slightly higher than the camere # frequency so that we are ready at the start of the next frame. frequency = (1.01 * seconds_per_frame) * float(oversampling) # If oversampling is 1 then just trigger the ao_task # and do_task directly off the camera fire pin. wv_clock = self.waveform_clock if (oversampling == 1): wv_clock = "PFI" + str(self.counter_trigger) # Setup the counter. if self.counter_board and (oversampling > 1): def startCtTask(): try: self.ct_task = nicontrol.CounterOutput(self.counter_board, self.counter_id, frequency, 0.5) self.ct_task.setCounter(oversampling) self.ct_task.setTrigger(self.counter_trigger) self.ct_task.startTask() except nicontrol.NIException: return True return False iters = 0 while (iters < 5) and startCtTask(): hdebug.logText("startCtTask failed " + str(iters)) self.ct_task.clearTask() time.sleep(0.5) iters += 1 if iters == 5: hdebug.logText("startCtTask critical failure") raise nicontrol.NIException("NIException: startCtTask critical failure") else: self.ct_task = False # Setup analog waveforms. if (len(self.analog_data) > 0): # Sort by board, channel. analog_data = sorted(self.analog_data, key = lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(analog_data)): waveform += analog_data[i][2] def startAoTask(): try: # Create channels. self.ao_task = nicontrol.AnalogWaveformOutput(analog_data[0][0], analog_data[0][1]) for i in range(len(analog_data) - 1): self.ao_task.addChannel(analog_data[i+1][0], analog_data[i+1][1]) # Add waveform self.ao_task.setWaveform(waveform, frequency, clock = wv_clock) # Start task. self.ao_task.startTask() except nicontrol.NIException: return True return False iters = 0 while (iters < 5) and startAoTask(): hdebug.logText("startAoTask failed " + str(iters)) self.ao_task.clearTask() time.sleep(0.1) iters += 1 if iters == 5: hdebug.logText("startAoTask critical failure") raise nicontrol.NIException("NIException: startAoTask critical failure") else: self.ao_task = False # Setup digital waveforms. if (len(self.digital_data) > 0): # Sort by board, channel. digital_data = sorted(self.digital_data, key = lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(digital_data)): waveform += digital_data[i][2] def startDoTask(): try: # Create channels. self.do_task = nicontrol.DigitalWaveformOutput(digital_data[0][0], digital_data[0][1]) for i in range(len(digital_data) - 1): self.do_task.addChannel(digital_data[i+1][0], digital_data[i+1][1]) # Add waveform self.do_task.setWaveform(waveform, frequency, clock = wv_clock) # Start task. self.do_task.startTask() except nicontrol.NIException: return True return False iters = 0 while (iters < 5) and startDoTask(): hdebug.logText("startDoTask failed " + str(iters)) self.do_task.clearTask() time.sleep(0.1) iters += 1 if iters == 5: hdebug.logText("startDoTask critical failure") raise nicontrol.NIException("NIException: startDoTask critical failure") else: self.do_task = False
def startFilm(self, seconds_per_frame, oversampling): illuminationHardware.DaqModulation.startFilm(self, seconds_per_frame, oversampling) # Calculate frequency. This is set slightly higher than the camere # frequency so that we are ready at the start of the next frame. frequency = (1.01 / seconds_per_frame) * float(oversampling) # Setup analog waveforms. print "analog" if (len(self.analog_data) > 0): # Sort by board, channel. analog_data = sorted(self.analog_data, key=lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(analog_data)): waveform += analog_data[i][2] # Check if we already have a task for this waveform. waveform_hash = hashlib.md5("".join( str(elt) for elt in waveform)).hexdigest() if waveform_hash in self.ao_tasks: self.ao_task = self.ao_tasks[waveform_hash] self.ao_task.reserveTask() print "using recycled ao_task", waveform_hash else: def initAoTask(): # Create channels. self.ao_task = nicontrol.AnalogWaveformOutput( analog_data[0][0], analog_data[0][1]) for i in range(len(analog_data) - 1): self.ao_task.addChannel(analog_data[i + 1][0], analog_data[i + 1][1]) # Add waveform return self.ao_task.setWaveform(waveform, frequency, clock=self.waveform_clock) iters = 0 valid = initAoTask() while (iters < 5) and (not valid): hdebug.logText("initAoTask failed " + str(iters)) self.ao_task.clearTask() time.sleep(0.1) valid = initAoTask() iters += 1 if valid: self.ao_tasks[waveform_hash] = self.ao_task else: self.ao_task = False # Setup digital waveforms print "digital" if (len(self.digital_data) > 0): # Sort by board, channel. digital_data = sorted(self.digital_data, key=lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(digital_data)): waveform += digital_data[i][2] # Check if we already have a task for this waveform. waveform_hash = hashlib.md5("".join( str(elt) for elt in waveform)).hexdigest() if waveform_hash in self.do_tasks: self.do_task = self.do_tasks[waveform_hash] self.do_task.reserveTask() print "using recycled do_task", waveform_hash else: def initDoTask(): # Create channels. self.do_task = nicontrol.DigitalWaveformOutput( digital_data[0][0], digital_data[0][1]) for i in range(len(digital_data) - 1): self.do_task.addChannel(digital_data[i + 1][0], digital_data[i + 1][1]) # Add waveform return self.do_task.setWaveform(waveform, frequency, clock=self.waveform_clock) iters = 0 valid = initDoTask() while (iters < 5) and (not valid): hdebug.logText("initDoTask failed " + str(iters)) self.do_task.clearTask() time.sleep(0.1) valid = initDoTask() iters += 1 if valid: self.do_tasks[waveform_hash] = self.do_task else: self.do_task = False # Setup the counter. print "counter" if self.counter_board: ct_hash = str(frequency) + str(oversampling) if ct_hash in self.ct_tasks: self.ct_task = self.ct_tasks[ct_hash] self.ct_task.reserveTask() print "using recycled ct_task", ct_hash else: def initCtTask(): self.ct_task = nicontrol.CounterOutput( self.counter_board, self.counter_id, frequency, 0.5) self.ct_task.setCounter(oversampling) self.ct_task.setTrigger(self.counter_trigger) print self.ct_task.verifyTask() return self.ct_task iters = 0 valid = initCtTask() while (iters < 5) and (not valid): hdebug.logText("initCtTask failed " + str(iters)) self.ct_task.clearTask() time.sleep(0.1) valid = initCtTask() iters += 1 if valid: self.ct_tasks[ct_hash] = self.ct_task else: self.ct_task = False # Start tasks for task in [self.ct_task, self.ao_task, self.do_task]: if task: task.startTask()
def startFilm(self, seconds_per_frame, oversampling): illuminationHardware.DaqModulation.startFilm(self, seconds_per_frame, oversampling) # Calculate frequency. This is set slightly higher than the camere # frequency so that we are ready at the start of the next frame. frequency = (1.01 / seconds_per_frame) * float(oversampling) # Setup analog waveforms. print "analog" if (len(self.analog_data) > 0): # Sort by board, channel. analog_data = sorted(self.analog_data, key = lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(analog_data)): waveform += analog_data[i][2] # Check if we already have a task for this waveform. waveform_hash = hashlib.md5("".join(str(elt) for elt in waveform)).hexdigest() if waveform_hash in self.ao_tasks: self.ao_task = self.ao_tasks[waveform_hash] self.ao_task.reserveTask() print "using recycled ao_task", waveform_hash else: def initAoTask(): # Create channels. self.ao_task = nicontrol.AnalogWaveformOutput(analog_data[0][0], analog_data[0][1]) for i in range(len(analog_data) - 1): self.ao_task.addChannel(analog_data[i+1][0], analog_data[i+1][1]) # Add waveform return self.ao_task.setWaveform(waveform, frequency, clock = self.waveform_clock) iters = 0 valid = initAoTask() while (iters < 5) and (not valid): hdebug.logText("initAoTask failed " + str(iters)) self.ao_task.clearTask() time.sleep(0.1) valid = initAoTask() iters += 1 if valid: self.ao_tasks[waveform_hash] = self.ao_task else: self.ao_task = False # Setup digital waveforms print "digital" if (len(self.digital_data) > 0): # Sort by board, channel. digital_data = sorted(self.digital_data, key = lambda x: (x[0], x[1])) # Set waveforms. waveform = [] for i in range(len(digital_data)): waveform += digital_data[i][2] # Check if we already have a task for this waveform. waveform_hash = hashlib.md5("".join(str(elt) for elt in waveform)).hexdigest() if waveform_hash in self.do_tasks: self.do_task = self.do_tasks[waveform_hash] self.do_task.reserveTask() print "using recycled do_task", waveform_hash else: def initDoTask(): # Create channels. self.do_task = nicontrol.DigitalWaveformOutput(digital_data[0][0], digital_data[0][1]) for i in range(len(digital_data) - 1): self.do_task.addChannel(digital_data[i+1][0], digital_data[i+1][1]) # Add waveform return self.do_task.setWaveform(waveform, frequency, clock = self.waveform_clock) iters = 0 valid = initDoTask() while (iters < 5) and (not valid): hdebug.logText("initDoTask failed " + str(iters)) self.do_task.clearTask() time.sleep(0.1) valid = initDoTask() iters += 1 if valid: self.do_tasks[waveform_hash] = self.do_task else: self.do_task = False # Setup the counter. print "counter" if self.counter_board: ct_hash = str(frequency) + str(oversampling) if ct_hash in self.ct_tasks: self.ct_task = self.ct_tasks[ct_hash] self.ct_task.reserveTask() print "using recycled ct_task", ct_hash else: def initCtTask(): self.ct_task = nicontrol.CounterOutput(self.counter_board, self.counter_id, frequency, 0.5) self.ct_task.setCounter(oversampling) self.ct_task.setTrigger(self.counter_trigger) print self.ct_task.verifyTask() return self.ct_task iters = 0 valid = initCtTask() while (iters < 5) and (not valid): hdebug.logText("initCtTask failed " + str(iters)) self.ct_task.clearTask() time.sleep(0.1) valid = initCtTask() iters += 1 if valid: self.ct_tasks[ct_hash] = self.ct_task else: self.ct_task = False # Start tasks for task in [self.ct_task, self.ao_task, self.do_task]: if task: task.startTask()