def set_buffers(self): """ Set and populate the buffer from the active communication channels of the Picoscope 5000A. See Also -------- daq_utils.ThreadCommand, get_active_channels """ #set buffers self.buffers = [] channels = self.get_active_channels() for ind_segment in range( self.settings.child('main_settings', 'Nsegments').value()): buffer_tmp = [] for channel in channels: ind_channel = picoscope.DAQ_Picoscope_trigger_channel[ channel].value status = self.pico.set_buffer(self.Nsample_available, channel=ind_channel, ind_segment=ind_segment, downsampling_mode=0) if status[0] != "PICO_OK": self.emit_status( ThreadCommand('Update_Status', [status[0], 'log'])) else: buffer_tmp.append(status[1]) self.buffers.append(buffer_tmp)
def move_Abs(self, command=ThreadCommand()): """ """ if command.command == "move_Abs": self.check_moving = True self.setpoint_sb.setValue(command.attributes[0]) QtWidgets.QApplication.processEvents()
def commit_settings(self,param): """ Activate parameters changes on the hardware. =============== ================================ =========================== **Parameters** **Type** **Description** *param* instance of pyqtgraph Parameter the parameter to activate =============== ================================ =========================== See Also -------- """ try: if param.name() == 'open_settings': if param.value(): self.controller.set(OpenCVProp['CV_CAP_PROP_SETTINGS'].value, 1) #param.setValue(False) elif param.name() == 'colors': pass else: self.controller.set(OpenCVProp['CV_CAP_' + param.name()].value, param.value()) val = self.controller.get(OpenCVProp['CV_CAP_' + param.name()].value) param.setValue(val) except Exception as e: self.emit_status(ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log']))
def run_PID(self): if self.run_action.isChecked(): self.run_action.setIcon(self.icon_stop) self.command_pid.emit( ThreadCommand('start_PID', [self.model_class.curr_input])) QtWidgets.QApplication.processEvents() QtWidgets.QApplication.processEvents() self.command_pid.emit( ThreadCommand('run_PID', [self.model_class.curr_output])) else: self.run_action.setIcon(self.iconrun) self.command_pid.emit(ThreadCommand('stop_PID')) QtWidgets.QApplication.processEvents()
def commit_settings(self,param): """ Activate parameters changes on the hardware from parameter's name. see documentation :ref:`hardware_settings` """ try: ############################################################### ##################to modify below ############################### if param.name()=='set_point': self.controller.SetTemperature(param.value()) elif param.name() == 'readout' or param.name() in custom_parameter_tree.iter_children(self.settings.child('camera_settings', 'readout_settings')): self.update_read_mode() elif param.name()=='exposure': self.controller.SetExposureTime(self.settings.child('camera_settings','exposure').value()/1000) #temp should be in s (err, timings) = self.controller.GetAcquisitionTimings() self.settings.child('camera_settings','exposure').setValue(timings['exposure']*1000) #################################################################### ######################################################################### except Exception as e: self.emit_status(ThreadCommand('Update_Status',[str(e),'log']))
def read_info(self, sock, dtype=np.float64): """ """ try: ##first get the info type length_bytes = check_received_length(sock, 4) length = np.frombuffer(length_bytes, dtype='>i4')[0] # big endian 4 bytes==uint32 swaped message = check_received_length(sock, length).decode() # get data length length_bytes = check_received_length(sock, 4) length = np.frombuffer(length_bytes, dtype='>i4')[0] ##then get data data_bytes = check_received_length(sock, length) data = np.frombuffer(data_bytes, dtype=dtype) data = data.newbyteorder()[0] # convert it to big endian try: self.settings.child('infos', message).setValue(data) except Exception as e: self.emit_status(ThreadCommand('Update_Status', [str(e), 'log'])) except Exception as e: data = 0 return data
def commit_settings(self, param): """ Activate parameters changes on the hardware. =============== ================================ =========================== **Parameters** **Type** **Description** *param* instance of pyqtgraph Parameter the parameter to activate =============== ================================ =========================== See Also -------- set_Mock_data """ try: if param.parent().name() == 'cam_settings': getattr(self.controller, param.name()).value = param.value() param.setValue(getattr(self.controller, param.name()).value) elif param.name() == 'video_formats': self.controller.stop_live() self.controller.set_video_format(param.value().encode()) # if 'Y' in param.value(): # self.controller.set_format(0) # else: # self.controller.set_format(1) self.controller.start_live() except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log']))
def set_exposure_ms(self, exposure): self.settings.child('camera_settings', 'exposure').setValue(exposure) QtWidgets.QApplication.processEvents() self.emit_status( ThreadCommand( 'exposure_ms', [self.settings.child('camera_settings', 'exposure').value()]))
def emit_data(self): """ Fonction used to emit data obtained by callback. See Also -------- daq_utils.ThreadCommand """ try: self.ind_grabbed += 1 sizey = self.settings.child('camera_settings', 'image_size', 'Ny').value() sizex = self.settings.child('camera_settings', 'image_size', 'Nx').value() self.controller.GetAcquiredDataNumpy(self.data_pointer, sizex * sizey) self.data_grabed_signal.emit([ DataFromPlugins(name='Camera', data=[ np.squeeze( self.data.reshape( (sizey, sizex)).astype(np.float)) ], dim=self.data_shape) ]) QtWidgets.QApplication.processEvents( ) # here to be sure the timeevents are executed even if in continuous grab mode except Exception as e: self.emit_status(ThreadCommand('Update_Status', [str(e), 'log']))
def commit_settings(self, param): """ | Activate any parameter changes on the PI_GCS2 hardware. | | Called after a param_tree_changed signal from DAQ_Move_main. =============== ================================ ======================== **Parameters** **Type** **Description** *param* instance of pyqtgraph Parameter The parameter to update =============== ================================ ======================== See Also -------- daq_utils.ThreadCommand, DAQ_Move_PI.enumerate_devices """ try: if param.name() == 'stage': self.controller.stage = param.value() elif param.name() == 'controller_address': self.controller.MMC_select(param.value()) self.check_position() except Exception as e: self.emit_status( ThreadCommand("Update_Status", [getLineInfo() + str(e), 'log']))
def timerEvent(self, event): """ | Called by set timers (only one for this self). | =============== ==================== ============================================== **Parameters** **Type** **Description** *event* QTimerEvent object Containing id from timer issuing this event =============== ==================== ============================================== """ try: #this is used to update image area if any call of the controller within multiple instance has been triggered and image size has been changed sizex, sizey = self.controller.getImageSize() if sizex != self.settings.child('pixels_settings','Nx').value() or sizey != self.settings.child('pixels_settings','Ny').value(): #try: # self.settings.sigTreeStateChanged.disconnect(self.send_param_status) #except: pass self.controller.setImageSize(sizex,sizey) self.controller.setImageArea(sizex, sizey, 0, sizex, 0, sizey) self.settings.child('pixels_settings','Nx').setValue(sizex) self.settings.child('pixels_settings','Ny').setValue(sizey) if self.settings.child('multiaxes','axis').value()==self.stage_names[0]: self.settings.child('bounds','max_bound').setValue(sizex-1) else: self.settings.child('bounds','max_bound').setValue(sizey-1) #self.settings.sigTreeStateChanged.connect(self.send_param_status) except Exception as e: self.emit_status(ThreadCommand('Update_Status',[getLineInfo()+ str(e),"log"]))
def emit_data(self): """ Fonction used to emit data obtained by callback. See Also -------- daq_utils.ThreadCommand """ try: self.ind_grabbed += 1 sizey = self.settings.child('camera_settings', 'image_size', 'Ny').value() sizex = self.settings.child('camera_settings', 'image_size', 'Nx').value() self.controller.GetAcquiredDataNumpy(self.data_pointer, sizex * sizey) self.data_grabed_signal.emit([ OrderedDict(name='Camera', data=[ np.squeeze( self.data.reshape( (sizey, sizex)).astype(np.float)) ], type=self.data_shape) ]) except Exception as e: self.emit_status(ThreadCommand('Update_Status', [str(e), 'log']))
def emit_data(self): """ """ try: mode = self.settings.child('acquisition', 'acq_type').value() if mode == 'Counting' or mode == 'Histo' or mode == 'T3': super().emit_data() elif mode == 'FLIM': self.stop_scanner.emit() self.h5saver.h5_file.flush() datas = self.process_histo_from_h5_and_correct_shifts( self.Nx, self.Ny, channel=0, marker=65) self.data_grabed_signal.emit([ DataFromPlugins(name='TH260', data=datas, dim='DataND', nav_axes=(0, 1), nav_x_axis=self.get_nav_xaxis(), nav_y_axis=self.get_nav_yaxis(), xaxis=self.get_xaxis(), external_h5=self.h5saver.h5_file) ]) self.stop() except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log']))
def emit_data(self): """ Function used to emit data when data ready. optional see Plugins documentation """ try: ########################## to modify below ##################### ################################################################# self.ind_grabbed += 1 sizey = self.settings.child('camera_settings', 'image_size', 'Ny').value() sizex = self.settings.child('camera_settings', 'image_size', 'Nx').value() self.controller.GetAcquiredDataNumpy(self.data_pointer, sizex * sizey) self.data_grabed_signal.emit([ OrderedDict(name='Camera', data=[ np.squeeze( self.data.reshape( (sizey, sizex)).astype(np.float)) ], type=self.data_shape) ]) ####################################################################### ################################################################## except Exception as e: self.emit_status(ThreadCommand('Update_Status', [str(e), 'log']))
def process_tcpip_cmds(self, status): if 'move_abs' in status.command: self.move_Abs(status.attributes[0], send_to_tcpip=True) elif 'move_rel' in status.command: self.move_Rel(status.attributes[0], send_to_tcpip=True) elif 'move_home' in status.command: self.move_Home(send_to_tcpip=True) elif 'check_position' in status.command: self.send_to_tcpip = True self.command_stage.emit(ThreadCommand('check_position')) elif status.command == 'connected': self.settings.child('main_settings', 'tcpip', 'tcp_connected').setValue(True) elif status.command == 'disconnected': self.settings.child('main_settings', 'tcpip', 'tcp_connected').setValue(False) elif status.command == 'Update_Status': self.thread_status(status) elif status.command == 'set_info': param_dict = ioxml.XML_string_to_parameter(status.attributes[1])[0] param_tmp = Parameter.create(**param_dict) param = self.settings.child('move_settings', *status.attributes[0][1:]) param.restoreState(param_tmp.saveState())
def send_command(self, sock, command="move_at"): """ Send one of the message contained in self.message_list toward a socket with identity socket_type. First send the length of the command with 4bytes. =============== =========== ========================== **Parameters** **Type** **Description** *sock* ??? The current socket *command* string The command as a string =============== =========== ========================== See Also -------- utility_classes.DAQ_Viewer_base.emit_status, daq_utils.ThreadCommand, message_to_bytes """ if command not in self.message_list: self.emit_status( ThreadCommand("Update_Status", [ f'Command: {command} is not in the specified list: {self.message_list}', 'log' ])) return if sock is not None: sock.send_string(command)
def ini_stage(self, params_state=None, controller=None): """ Init a stage updating the hardware and sending an hardware move_done signal. =============== =================================== ========================================================================================================================== **Parameters** **Type** **Description** *params_state* ordered dictionnary list The parameter state of the hardware class composed by a list representing the tree to keep a temporary save of the tree *controller* one or many instance of DAQ_Move The controller id of the hardware *stage* instance of DAQ_Move Defining axes and motors =============== =================================== ========================================================================================================================== See Also -------- DAQ_utils.ThreadCommand, DAQ_Move """ status=edict(initialized=False,info="") try: class_=getattr(getattr(plugins,'daq_move_'+self.stage_name),'DAQ_Move_'+self.stage_name) self.hardware=class_(self,params_state) status.update(self.hardware.ini_stage(controller)) #return edict(info="", controller=, stage=) self.hardware.Move_Done_signal.connect(self.Move_Done) #status.initialized=True return status except Exception as e: self.status_sig.emit(ThreadCommand("Update_Status",[str(e),'log'])) return status
def emit_data(self): """ Fonction used to emit data obtained by dataUnlocker callback. See Also -------- DAQ_utils.ThreadCommand """ try: self.ind_grabbed+=1 #print(self.ind_grabbed) if self.settings.child('camera_mode_settings', 'camera_mode').value()=="Camera": if self.camera_done: self.data_grabed_signal.emit([OrderedDict(name='Camera '+self.settings.child(('model')).value(),data=[self.data.reshape((self.settings.child('image_size','Ny').value(),self.settings.child('image_size','Nx').value()))], type='Data2D')]) else:#spim mode #print("spimmode") if self.spectrum_done: #print("spectrum done") if not self.spim_done: self.spectrum_done=False self.data_grabed_signal_temp.emit([OrderedDict(name='SPIM ',data=[self.spimdata.reshape((self.settings.child('image_size','Nx').value(),self.settings.child('camera_mode_settings','spim_y').value(),self.settings.child('camera_mode_settings','spim_x').value()))], type='DataND'), OrderedDict(name='Spectrum',data=[self.spectrumdata], type='Data1D') ]) elif self.spim_done: #print('spimdone') self.data_grabed_signal.emit([OrderedDict(name='SPIM ',data=[self.spimdata.reshape((self.settings.child('image_size','Nx').value(),self.settings.child('camera_mode_settings','spim_y').value(),self.settings.child('camera_mode_settings','spim_x').value()))], type='DataND'), OrderedDict(name='Spectrum',data=[self.spectrumdata], type='Data1D') ]) self.spectrum_done=False self.spim_done=False except Exception as e: self.emit_status(ThreadCommand('Update_Status',[getLineInfo()+ str(e),'log']))
def commit_settings(self, param): """ Activate parameters changes on the hardware. =============== ================================ =========================== **Parameters** **Type** **Description** *param* instance of pyqtgraph Parameter the parameter to activate =============== ================================ =========================== See Also -------- set_Mock_data """ try: if param.name() in putils.iter_children( self.settings.child(('cam_settings')), []): self.stop() while self.controller.is_acquiring_images: self.stop() QtWidgets.QApplication.processEvents() feature = self.controller.device.node_map.get_node( param.name()) interface_type = feature.node.principal_interface_type if interface_type == EInterfaceType.intfIInteger: val = int((param.value() // param.opts['step']) * param.opts['step']) else: val = param.value() feature.value = val #set the desired value param.setValue(feature.value) # retrieve the actually set one #self.update_features() if param.name() in ['Height', 'Width', 'OffsetX', 'OffsetY']: if param.name() in ['Height', 'Width' ] and not self.settings.child( 'ROIselect', 'use_ROI').value(): self.width = self.controller.device.node_map.get_node( 'Width').value self.height = self.controller.device.node_map.get_node( 'Height').value self.data = np.zeros((self.height, self.width)) if param.name() in putils.iter_children( self.settings.child(('ROIselect')), []): while self.controller.is_acquiring_images: QThread.msleep(50) self.stop() QtWidgets.QApplication.processEvents() self.set_ROI() except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log']))
def ini_detector(self, controller=None): """ Initialisation procedure of the detector. See Also -------- daq_utils.ThreadCommand """ self.status.update( edict(initialized=False, info="", x_axis=None, y_axis=None, controller=None)) try: if self.settings.child(('controller_status')).value() == "Slave": if controller is None: raise Exception( 'no controller has been defined externally while this detector is a slave one' ) else: self.task = controller else: self.update_task() return self.status except Exception as e: self.emit_status(ThreadCommand('Update_Status', [str(e), 'log'])) self.status.info = str(e) self.status.initialized = False return self.status
def ini_detector(self, controller=None): """ Initialisation procedure of the detector updating the status dictionnary. See Also -------- set_Mock_data, daq_utils.ThreadCommand """ self.status.update(edict(initialized=False,info="",x_axis=None,y_axis=None,controller=None)) try: if self.settings.child(('controller_status')).value()=="Slave": if controller is None: raise Exception('no controller has been defined externally while this detector is a slave one') else: self.controller=controller else: self.controller="Mock controller" self.set_x_axis() self.set_Mock_data() # initialize viewers with the future type of data self.data_grabed_signal_temp.emit([DataFromPlugins(name='Mock1', data=self.data_mock, dim='Data1D', x_axis= self.x_axis, labels=['Mock1', 'label2']),]) self.status.initialized=True self.status.controller=self.controller self.status.x_axis = self.x_axis return self.status except Exception as e: self.emit_status(ThreadCommand('Update_Status',[getLineInfo()+ str(e),'log'])) self.status.info=getLineInfo()+ str(e) self.status.initialized=False return self.status
def enumerate_devices(self): """ Enumerate PI_GCS2 devices from the connection type. Returns ------- string list The list of the devices port. See Also -------- daq_utils.ThreadCommand """ try: devices = [] if self.settings.child(('connect_type')).value() == 'USB': devices = self.controller.EnumerateUSB() elif self.settings.child(('connect_type')).value() == 'TCP/IP': devices = self.controller.EnumerateTCPIPDevices() elif self.settings.child(('connect_type')).value() == 'RS232': devices = [ str(port) for port in list(self.list_ports.comports()) ] self.settings.child(('devices')).setLimits(devices) return devices except Exception as e: self.emit_status( ThreadCommand("Update_Status", [getLineInfo() + str(e), 'log']))
def command_to_from_client(self, command): sock = self.find_socket_within_connected_clients(self.client_type) if sock is not None: # if client 'ACTUATOR' is connected then send it the command if command == 'position_is': pos = get_scalar(sock) pos = self.get_position_with_scaling(pos) self.current_position = pos self.emit_status(ThreadCommand('check_position', [pos])) elif command == 'move_done': pos = get_scalar(sock) pos = self.get_position_with_scaling(pos) self.current_position = pos self.emit_status(ThreadCommand('move_done', [pos]))
def set_referencing(self, axes): """ Set the referencement statement into the hardware device. ============== ============== =========================================== **Parameters** **Type** **Description** *axes* string list Representing connected axes on controller ============== ============== =========================================== """ try: if not isinstance(axes, list): axes = [axes] for axe in axes: #set referencing mode if isinstance(axe, str): if self.is_referenced(axe): if self.controller.HasRON(): self.controller.RON(axe, True) self.controller.FRF(axe) except Exception as e: self.emit_status( ThreadCommand('Update_Status', [ getLineInfo() + str(e) + " / Referencing not enabled with this dll", 'log' ]))
def commit_settings(self, param): """ Activate the parameters changes in the hardware. =============== ================================= ============================ **Parameters** **Type** **Description** *param* instance of pyqtgraph.parameter The parameter to be checked. =============== ================================= ============================ See Also -------- daq_utils.ThreadCommand """ try: self.status_timer.stop() if 'diag_' in param.name(): id = int(param.name().split('diag_')[1]) diag = self.controller.get_diag_from_id(id) self.controller.set_diag(id, int(param.value() * diag['divider']).to_bytes(diag['reply'], 'big')) QThread.msleep(200) self.update_diag(id) elif param.name() == 'timeout': self.controller.timeout = param.value() param.setValue(self.controller.timeout) elif param.name() == 'update_diags': self.update_all_diags() self.update_status() elif param.name() == 'laser': self.controller.set_laser(param.value()) elif param.name() == 'shutter': self.controller.set_shutter(param.value()) self.status_timer.start(1000) except Exception as e: self.emit_status(ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log']))
def grab_data(self, Naverage=1, **kwargs): """ """ try: datas = [] for ind_spectro in range(len(self.spectro_names)): if self.settings.child('spectrometers', 'spectro{:d}'.format(ind_spectro), 'grab').value(): self.controller.setScansToAverage(ind_spectro, Naverage) data_chelou = self.controller.getSpectrum(ind_spectro) data = np.array( [data_chelou[ind] for ind in range(len(data_chelou))]) datas.append( DataFromPlugins(name=self.spectro_names[ind_spectro], data=[data], dim='Data1D')) QtWidgets.QApplication.processEvents() self.data_grabed_signal.emit(datas) except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), "log"]))
def queue_command(self, command=ThreadCommand()): """ """ if command.command == "start_PID": self.start_PID(*command.attributes) elif command.command == "run_PID": self.run_PID(*command.attributes) elif command.command == "pause_PID": self.pause_PID(*command.attributes) elif command.command == "stop_PID": self.stop_PID() elif command.command == 'update_options': self.set_option(**command.attributes) elif command.command == 'input': self.update_input(*command.attributes) elif command.command == 'update_timer': if command.attributes[0] == 'refresh_plot_time': self.killTimer(self.timer) self.refreshing_ouput_time = command.attributes[1] self.timer = self.startTimer(self.refreshing_ouput_time) elif command.attributes[0] =='timeout': self.timeout_timer.setInterval(command.attributes[1]) elif command.command == 'update_filter': self.filter = command.attributes[0]
def grab_data(self, Naverage=1, **kwargs): """ Start new acquisition. Grabbed indice is used to keep track of the current image in the average. ============== ========== ============================== **Parameters** **Type** **Description** *Naverage* int Number of images to average ============== ========== ============================== See Also -------- utility_classes.DAQ_TCP_server.process_cmds """ try: self.ind_grabbed = 0 # to keep track of the current image in the average self.Naverage = Naverage self.process_cmds("Send Data {:s}".format(self.grabber_type)) # self.command_server.emit(["process_cmds","Send Data 2D"]) except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), "log"]))
def ini_stage(self, controller=None): """ Initialize the controller and stages (axes) with given parameters. ============== ================================================ ========================================================================================== **Parameters** **Type** **Description** *controller* instance of the specific controller object If defined this hardware will use it and will not initialize its own controller instance ============== ================================================ ========================================================================================== Returns ------- Easydict dictionnary containing keys: * *info* : string displaying various info * *controller*: instance of the controller object in order to control other axes without the need to init the same controller twice * *stage*: instance of the stage (axis or whatever) object * *initialized*: boolean indicating if initialization has been done corretly See Also -------- daq_utils.ThreadCommand """ try: # initialize the stage and its controller status # controller is an object that may be passed to other instances of DAQ_Move_Mock in case # of one controller controlling multiaxes self.status.update( edict(info="", controller=None, initialized=False)) #check whether this stage is controlled by a multiaxe controller (to be defined for each plugin) # if mutliaxes then init the controller here if Master state otherwise use external controller if self.settings.child( 'multiaxes', 'ismultiaxes').value() and self.settings.child( 'multiaxes', 'multi_status').value() == "Slave": if controller is None: raise Exception( 'no controller has been defined externally while this axe is a slave one' ) else: self.controller = controller else: #Master stage self.controller = "master_controller" #any object that will control the stages info = "Mock stage" self.status.info = info self.status.controller = self.controller self.status.initialized = True return self.status except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log'])) self.status.info = getLineInfo() + str(e) self.status.initialized = False return self.status
def test_init_connection(self, mock_Socket, mock_select, mock_events): mock_Socket.return_value = Socket(MockPythonSocket()) mock_select.side_effect = [([], [], []), Exception] mock_events.side_effect = [TypeError] test_TCP_Client = TCPClient() cmd_signal = mock.Mock() cmd_signal.emit.side_effect = [None, Expected_1] test_TCP_Client.cmd_signal = cmd_signal with pytest.raises(Expected_1): test_TCP_Client.init_connection( extra_commands=[ThreadCommand('test')]) assert not test_TCP_Client.connected test_TCP_Client = TCPClient() test_Socket = Socket(MockPythonSocket()) test_Socket.send_string('init') mock_Socket.return_value = test_Socket mock_select.side_effect = [(['init'], [], ['error'])] test_TCP_Client.init_connection() assert not test_TCP_Client.connected mock_Socket.side_effect = [ConnectionRefusedError] cmd_signal = mock.Mock() cmd_signal.emit.side_effect = [None, Expected_2] test_TCP_Client.cmd_signal = cmd_signal with pytest.raises(Expected_2): test_TCP_Client.init_connection()