def list_instruments(): """Get a list of all power supplies currently attached""" paramsets = [] search_string = "ASRL?*" rm = ResourceManager() raw_spec_list = rm.list_resources(search_string) for spec in raw_spec_list: try: inst = rm.open_resource(spec, read_termination='\n', write_termination='\n') idn = inst.query("*IDN?") manufacturer, model, serial, version = idn.rstrip().split(',', 4) if re.match('DP7[0-9]{2}', model): paramsets.append( ParamSet(DP700, asrl=spec, manufacturer=manufacturer, serial=serial, model=model, version=version)) except pyvisa.errors.VisaIOError as vio: # Ignore unknown serial devices pass return paramsets
def __init__(self, signal_interface: SignalInterface, path: str, contacts: Tuple[str, str], v: float = 0.0, i: float = 1e-6, n: int = 100, nplc: int = 1, comment: str = '', gate_voltage: float = 0.0, sd_current_range: float = 0.0, gd_current_range: float = 0.0, symmetric: bool = False) -> None: super().__init__(signal_interface, path, contacts) self._max_voltage = v self._current_limit = i self._number_of_points = n self._nplc = nplc self._comment = comment self._gate_voltage = gate_voltage resource_man = ResourceManager(self.VISA_LIBRARY) resource = resource_man.open_resource(self.GPIB_RESOURCE, query_delay=self.QUERY_DELAY) self._device = Sourcemeter2636A(resource, sub_device=SMUChannel.channelA) self._device.voltage_driven(0, i, nplc, range=sd_current_range) self._gate = Sourcemeter2636A(resource, sub_device=SMUChannel.channelB) self._gate.voltage_driven(0, i, nplc, range=gd_current_range) self._temperature_controller = Model340(self.TEMP_ADDR) self._symmetric = symmetric
def test_sanity(): register_resources(instruments.resources) rc = ResourceManager(visa_library="@mock") res = rc.open_resource("MOCK0::mock1::INSTR") res.write(":INSTR:CHANNEL1:VOLT 2.3") reply = res.query(":INSTR:CHANNEL1:VOLT?") assert reply == '2.3'
def __init__(self, address, reset=True): '''Initialization sequence for the SourceMeter''' # Open the K2400SM self.inst = ResourceManager().open_resource(address) #Shorthand self.w = self.inst.write self.r = self.inst.read self.q = self.inst.query #Print K2400SM string for confirmation print(self.q('*IDN?')) if reset: self.w('*RST')
def refresh_resources(n): list_of_resources = ResourceManager().list_resources() default_resources = [s for s in list_of_resources if 'GPIB' in s] if len(default_resources) > 1: sourcemeter_resource = default_resources[0] multimeter_resource = default_resources[1] else: sourcemeter_resource = None multimeter_resource = None options = [{'label': name, 'value': name} for name in list_of_resources] return multimeter_resource, options, sourcemeter_resource, options
def update_devices(self): rm = ResourceManager('@py') try: self._resources = [x for x in rm.list_resources() if 'GPIB' in x] except: self._resources = [] self._combobox.clear() for item in self._resources: self._combobox.addItem(item) rm.close()
def __init__(self, signal_interface: SignalInterface, path: str, contacts: Tuple[str, str], v: float = 0.0, i: float = 1e-6, nplc: int = 3, comment: str = '', time_difference: float=0, gpib: str='GPIB0::10::INSTR', temperatures: str = '[2,10,100,300]'): super().__init__(signal_interface, path, contacts) self._max_voltage = v self._current_limit = i self._nplc = nplc self._comment = comment self._time_difference = time_difference self._gpib = gpib resource_man = ResourceManager('@py') resource = resource_man.open_resource(self._gpib) resource.timeout = 30000 self._device = SMUTempSweepIV._get_sourcemeter(resource) self._device.voltage_driven(0, i, nplc) self._temp = ITC(get_gpib_device(24)) step1 = np.linspace(0, self._max_voltage, 25, endpoint=False) step2 = np.linspace(self._max_voltage, -self._max_voltage, 50, endpoint=False) step3 = np.linspace(-self._max_voltage, 0, 25) self._voltages = np.concatenate((step1, step2, step3)) try: self._temperatures = literal_eval(temperatures) except: print('ERROR', 'Malformed String for Temperatures') self.abort() return if type(self._temperatures) is not list: print('ERROR', 'Temperature String is not a List') self.abort() return for k in self._temperatures: t = type(k) if t is not int and t is not float: print('ERROR', 'Temperature List does not only contain ints or floats') self.abort() return self._temperatures = np.array(self._temperatures)
def list_instruments(): """Get a list of all spectrometers currently attached""" paramsets = [] search_string = "USB?*?{VI_ATTR_MANF_ID==0x1313 && ((VI_ATTR_MODEL_CODE==0x8081) || (VI_ATTR_MODEL_CODE==0x8083) || (VI_ATTR_MODEL_CODE==0x8085) || (VI_ATTR_MODEL_CODE==0x8087) || (VI_ATTR_MODEL_CODE==0x8089))}" rm = ResourceManager() try: raw_spec_list = rm.list_resources(search_string) except: return paramsets for spec in raw_spec_list: _, _, model, serial, _ = spec.split('::', 4) model = SpecTypes(int(model, 0)) paramsets.append(ParamSet(CCS, usb=spec, serial=serial, model=model)) return paramsets
def __init__(self, ip_address): """ Constructor for scope object Resets scope :param ip_address: Ethernet address of scope """ if not ip_address: print("No ip address specified. Running in test mode.") return self.inst = ResourceManager("@py").open_resource("TCPIP0::" + ip_address + "::inst0::INSTR") if "LECROY" in self.inst.query("*IDN?;"): print("Connected to LeCroy WavePro") self.inst.timeout = 60000
def __init__(self, signal_interface: SignalInterface, path: str, contacts: Tuple[str, str], v: float = 0.0, i: float = 1e-6, n: int = 100, nplc: int = 1, comment: str = '', range:float=1e-8) -> None: super().__init__(signal_interface, path, contacts) self._max_voltage = v self._current_limit = i self._number_of_points = n self._nplc = nplc self._comment = comment resource_man = ResourceManager(self.VISA_LIBRARY) resource = resource_man.open_resource(self.GPIB_RESOURCE, query_delay=self.QUERY_DELAY) self._device = Sourcemeter2602A(resource) self._device.voltage_driven(0, i, nplc, range=range)
def list_instruments(): """Get a list of all spectrometers currently attached""" paramsets = [] model_string = '|'.join('{:04X}'.format(spec.value) for spec in SpecTypes) search_string = "USB[0-9]*::0x{:04X}::0x({})".format(MANUFACTURER_ID, model_string) rm = ResourceManager() try: raw_spec_list = rm.list_resources(search_string) except: return paramsets for spec in raw_spec_list: _, _, model, serial, _ = spec.split('::', 4) model = SpecTypes(int(model, 0)) paramsets.append(ParamSet(DG800, usb=spec, serial=serial, model=model)) return paramsets
def _init_smus(self): rm = ResourceManager('@py') dev1 = rm.open_resource(self.GPIB_RESOURCE_2400) dev2 = rm.open_resource(self.GPIB_RESOURCE_2636A) dev3 = rm.open_resource(self.GPIB_RESOURCE_2602A) self._smus = [ Sourcemeter2400(dev1), Sourcemeter2636A(dev2, sub_device=SMUChannel.channelA), Sourcemeter2636A(dev2, sub_device=SMUChannel.channelB), Sourcemeter2602A(dev3, sub_device=SMUChannel.channelA), Sourcemeter2602A(dev3, sub_device=SMUChannel.channelB) ] for index, smu in enumerate(self._smus): sample = self._samples[index] smu.voltage_driven(sample['v'], current_limit=sample['i'], nplc=sample['nplc'])
def __init__(self, signal_interface: SignalInterface, path: str, contacts: Tuple[str, str], v: float = 0.0, i: float = 1e-6, n: int = 100, nplc: int = 1, comment: str = '', gpib: str = '') -> None: super().__init__(signal_interface, path, contacts) self._max_voltage = v self._current_limit = i self._number_of_points = n self._nplc = nplc self._comment = comment resource_man = ResourceManager(self.VISA_LIBRARY) resource = resource_man.open_resource(gpib, query_delay=self.QUERY_DELAY) try: self._device = SMU2Probe._get_sourcemeter(resource) except visa.VisaIOError: # Should only occur when pyvisa-sim is used: self._device = Sourcemeter2400(resource) self._device.voltage_driven(0, i, nplc)
def list_instruments(): """ Get a list of all spectrometers currently attached. """ spectrometers = [] search_string = "USB?*?{VI_ATTR_MANF_ID==0x1313 && ((VI_ATTR_MODEL_CODE==0x8081) || (VI_ATTR_MODEL_CODE==0x8083) || (VI_ATTR_MODEL_CODE==0x8085) || (VI_ATTR_MODEL_CODE==0x8087) || (VI_ATTR_MODEL_CODE==0x8089))}" rm = ResourceManager() try: raw_spec_list = rm.list_resources(search_string) except: return spectrometers for spec in raw_spec_list: _, _, model, serial_number, _ = spec.split("::") model = SpecTypes(int(model, 0)) params = _ParamDict("<Thorlabs_CCS_Spectrometer '{}-{}'>".format( model.name, serial_number)) params.module = 'spectrometers.thorlabs_ccs' params['ccs_usb_address'] = spec params['ccs_model'] = model params['ccs_serial_number'] = serial_number spectrometers.append(params) return spectrometers
def __init__(self, signal_interface: SignalInterface, path: str, contacts: Tuple[str, str], v: float = 0.0, i: float = 1e-6, nplc: int = 3, comment: str = '', time_difference: float = 0, gpib: str = 'GPIB0::10::INSTR'): super().__init__(signal_interface, path, contacts) self._max_voltage = v self._current_limit = i self._nplc = nplc self._comment = comment self._time_difference = time_difference self._gpib = gpib resource_man = ResourceManager('@py') resource = resource_man.open_resource(self._gpib) self._device = SMU2ProbeIvt._get_sourcemeter(resource) self._device.voltage_driven(0, i, nplc)
def __init__(self, signal_interface: SignalInterface, path: str, contacts: Tuple[str, str, str, str], comment: str = '', gpib: str='GPIB0::12::INSTR', sweep_rate:float = 1.0, temperature_end: float = 2, nplc: int = 3, voltage:float = 0.1, current_limit: float=1e-6): super().__init__(signal_interface, path, contacts) self._comment = comment self._temp = ITC(get_gpib_device(24)) self._sweep_rate = sweep_rate self._voltage = voltage self._current_limit = current_limit self._gpib = gpib if not (0 <= temperature_end <= 299): print("end temperature too high or too low. (0 ... 299)") self.abort() return if not (0 <= sweep_rate <= 2.5): print("you're insane! sweep rate is too high. (0 ... 2.5)") self.abort() return resource_man = ResourceManager('@py') resource = resource_man.open_resource(self._gpib) self._device = SMU2ProbeIvTBlue._get_sourcemeter(resource) self._device.voltage_driven(0, current_limit, nplc) self._temperature_end = temperature_end self._last_toggle = time() sleep(1)
def list_instruments(): """Get a list of all spectrometers currently attached""" paramsets = [] model_string = '' for spec in SpecTypes: model_string += '(VI_ATTR_MODEL_CODE==0x{:04X}) || '.format(spec.value) model_string = model_string.rstrip(' || ') search_string = "USB?*?{{VI_ATTR_MANF_ID==0x{:04X} && ({})}}".format( MANUFACTURER_ID, model_string) rm = ResourceManager() try: raw_spec_list = rm.list_resources(search_string) except: return paramsets for spec in raw_spec_list: _, _, model, serial, _ = spec.split('::', 4) model = SpecTypes(int(model, 0)) paramsets.append(ParamSet(DG800, usb=spec, serial=serial, model=model)) return paramsets
class DAQ_0DViewer_LockIn7270(DAQ_Viewer_base): """ ==================== ======================== **Attributes** **Type** *data_grabed_signal* instance of pyqtSignal *VISA_rm* ResourceManager *com_ports* *params* dictionnary list *inst* *settings* ==================== ======================== """ data_grabed_signal = pyqtSignal(list) channels_single_mode = ['X', 'Y', 'MAG', 'PHA'] channels_dual_mode = [ 'X1', 'Y1', 'MAG1', 'PHA1', 'X2', 'Y2', 'MAG2', 'PHA2' ] ##checking VISA ressources try: from visa import ResourceManager VISA_rm = ResourceManager() devices = list(VISA_rm.list_resources(query=u'?*::RAW')) except: devices = [] params = comon_parameters + [ { 'title': 'VISA:', 'name': 'VISA_ressources', 'type': 'list', 'values': devices }, { 'title': 'Manufacturer:', 'name': 'manufacturer', 'type': 'str', 'value': "" }, { 'title': 'Serial number:', 'name': 'serial_number', 'type': 'str', 'value': "" }, { 'title': 'Model:', 'name': 'model', 'type': 'str', 'value': "" }, { 'title': 'Timeout (ms):', 'name': 'timeout', 'type': 'int', 'value': 2000, 'default': 2000, 'min': 1000 }, { 'title': 'Configuration:', 'name': 'config', 'type': 'group', 'children': [ { 'title': 'Mode:', 'name': 'mode', 'type': 'list', 'values': ReferenceModes.names() }, { 'title': 'Channels in separate viewer:', 'name': 'separate_viewers', 'type': 'bool', 'value': True }, { 'title': 'Channels:', 'name': 'channels', 'type': 'itemselect', 'value': dict(all_items=channels_single_mode, selected=['MAG', 'PHA']) }, ] }, ] def __init__(self, parent=None, params_state=None): super(DAQ_0DViewer_LockIn7270, self).__init__(parent, params_state) self.inst = None def query_data(self, cmd): try: res = self.inst.query(cmd) searched = re.search('\n', res) status_byte = res[searched.start() + 1] overload_byte = res[searched.start() + 3] if searched.start != 0: data = np.array( [float(x) for x in res[0:searched.start()].split(",")]) else: data = None return (status_byte, overload_byte, data) except: return ('\x01', '\x00', None) def query_string(self, cmd): try: res = self.inst.query(cmd) searched = re.search('\n', res) status_byte = res[searched.start() + 1] overload_byte = res[searched.start() + 3] if searched.start != 0: str = res[0:searched.start()] else: str = "" return (status_byte, overload_byte, str) except: return ('\x01', '\x00', "") def ini_detector(self, controller=None): """ Initialisation procedure of the detector. Returns ------- The initialized status. 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.inst = controller else: self.inst = self.VISA_rm.open_resource( self.settings.child(('VISA_ressources')).value()) self.inst.timeout = self.settings.child(('timeout')).value() self.settings.child( ('manufacturer')).setValue(self.inst.manufacturer_name) self.settings.child( ('serial_number')).setValue(self.inst.serial_number) self.settings.child(('model')).setValue(self.query_string('ID')[2]) self.settings.child('config', 'mode').setValue( ReferenceModes(int(self.query_string('REFMODE')[2])).name) self.status.controller = self.inst 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 grab_data(self, Naverage=1, **kwargs): """ | Start new acquisition. | grab the current values. | Send the data_grabed_signal once done. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int Number of values to average =============== ======== =============================================== """ data_tot = [] for channel in self.settings.child('config', 'channels').value()['selected']: if self.settings.child('config', 'separate_viewers').value(): data_tot.append( OrderedDict(name=channel, data=[self.query_data(channel + '.')[2]], type='Data0D')) else: data_tot.append(self.query_data(channel + '.')[2]) if self.settings.child('config', 'separate_viewers').value(): self.data_grabed_signal.emit(data_tot) else: self.data_grabed_signal.emit( [OrderedDict(name='Keithley', data=data_tot, type='Data0D')]) 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: if param.name() == 'timeout': self.inst.timeout = self.settings.child(('timeout')).value() elif param.name() == 'mode': self.query_str('REFMODE {}'.format( ReferenceModes[param.value()].value)) elif param.name() == 'channels': data_init = [] for channel in param.value()['selected']: if self.settings.child('config', 'separate_viewers').value(): data_init.append( OrderedDict(name=channel, data=[np.array([0])], type='Data0D')) else: data_init.append(np.array([0])) if self.settings.child('config', 'separate_viewers').value(): self.data_grabed_signal_temp.emit(data_init) else: self.data_grabed_signal_temp.emit([ OrderedDict(name='Keithley', data=data_init, type='Data0D') ]) except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log'])) def close(self): """ close the current instance of the visa session. """ self.inst.close()
class DAQ_0DViewer_Keithley_Pico(DAQ_Viewer_base): """ ==================== ======================== **Attributes** **Type** *data_grabed_signal* instance of pyqtSignal *VISA_rm* ResourceManager *com_ports* *params* dictionnary list *keithley* *settings* ==================== ======================== """ data_grabed_signal = pyqtSignal(list) ##checking VISA ressources from visa import ResourceManager VISA_rm = ResourceManager() com_ports = list(VISA_rm.list_resources()) # import serial.tools.list_ports; # com_ports=[comport.device for comport in serial.tools.list_ports.comports()] params = comon_parameters + [ { 'title': 'VISA:', 'name': 'VISA_ressources', 'type': 'list', 'values': com_ports }, { 'title': 'Keithley Type:', 'name': 'keithley_type', 'type': 'list', 'values': DAQ_0DViewer_Keithley_Pico_type.names() }, { 'title': 'Id:', 'name': 'id', 'type': 'text', 'value': "" }, { 'title': 'Timeout (ms):', 'name': 'timeout', 'type': 'int', 'value': 10000, 'default': 10000, 'min': 2000 }, { 'title': 'Configuration:', 'name': 'config', 'type': 'group', 'children': [ { 'title': 'Meas. type:', 'name': 'meas_type', 'type': 'list', 'value': 'CURR', 'default': 'CURR', 'values': ['CURR', 'VOLT', 'RES', 'CHAR'] }, ] }, ] def __init__(self, parent=None, params_state=None): super(DAQ_0DViewer_Keithley_Pico, self).__init__(parent, params_state) from visa import ResourceManager self.VISA_rm = ResourceManager() self.controller = None def ini_detector(self, controller=None): """ Initialisation procedure of the detector. Returns ------- The initialized status. 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.controller = controller else: self.controller = self.VISA_rm.open_resource( self.settings.child(('VISA_ressources')).value(), read_termination='\r') self.controller.timeout = self.settings.child(('timeout')).value() self.controller.write("*rst; status:preset; *cls;") txt = self.controller.query('*IDN?') self.settings.child(('id')).setValue(txt) self.controller.write( 'CONF:' + self.settings.child('config', 'meas_type').value()) self.controller.write(':FORM:ELEM READ;DATA ASC;') self.controller.write('ARM:SOUR IMM;') self.controller.write('ARM:COUNt 1;') self.controller.write('TRIG:SOUR IMM;') #%% data = self.controller.query_ascii_values('READ?') self.status.initialized = True self.status.controller = self.controller 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 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: if param.name() == 'timeout': self.controller.timeout = self.settings.child( ('timeout')).value() elif param.name() == 'meas_type': self.controller.write('CONF:' + param.value()) except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log'])) def close(self): """ close the current instance of Keithley viewer. """ self.controller.close() def grab_data(self, Naverage=1, **kwargs): """ | Start new acquisition. | grab the current values with keithley profile procedure. | Send the data_grabed_signal once done. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int Number of values to average =============== ======== =============================================== """ data_tot = [] self.controller.write('ARM:SOUR IMM;') self.controller.write('ARM:COUNt 1;') self.controller.write('TRIG:SOUR IMM;') self.controller.write('TRIG:COUN {:};'.format(Naverage)) data_tot = self.controller.query_ascii_values('READ?') #for ind in range(Naverage): # data_tot.append(self.controller.query_ascii_values('READ?')[0]) data_tot = [np.array([np.mean(np.array(data_tot))])] self.data_grabed_signal.emit( [DataFromPlugins(name='Keithley', data=data_tot, dim='Data0D')]) def stop(self): """ not implemented? """ return ""
def __init__(self, parent=None, params_state=None): super(DAQ_1DViewer_Tektronix, self).__init__(parent, params_state) from visa import ResourceManager self.VISA_rm = ResourceManager() self.controller = None
class DAQ_1DViewer_Tektronix(DAQ_Viewer_base): """ ==================== ======================== **Attributes** **Type** *data_grabed_signal* instance of pyqtSignal *VISA_rm* ResourceManager *com_ports* *params* dictionnary list *keithley* *settings* ==================== ======================== """ data_grabed_signal = pyqtSignal(list) ##checking VISA ressources from visa import ResourceManager VISA_rm = ResourceManager() com_ports = list(VISA_rm.list_resources()) params = comon_parameters + [ { 'title': 'VISA:', 'name': 'VISA_ressources', 'type': 'list', 'values': com_ports }, { 'title': 'Id:', 'name': 'id', 'type': 'text', 'value': "" }, { 'title': 'Channels:', 'name': 'channels', 'type': 'itemselect', 'value': dict(all_items=['CH1', 'CH2', 'CH3', 'CH4'], selected=['CH1']) }, ] def __init__(self, parent=None, params_state=None): super(DAQ_1DViewer_Tektronix, self).__init__(parent, params_state) from visa import ResourceManager self.VISA_rm = ResourceManager() self.controller = None def ini_detector(self, controller=None): """ Initialisation procedure of the detector. Returns ------- The initialized status. 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.controller = controller else: self.controller = self.VISA_rm.open_resource( self.settings.child(('VISA_ressources')).value(), read_termination='\n') txt = self.controller.query('*IDN?') self.settings.child(('id')).setValue(txt) Nchannels = self.number_of_channel() if Nchannels == 2: self.settings.child(('channels')).setValue( dict(all_items=['CH1', 'CH2'], selected=['CH1'])) else: self.settings.child(('channels')).setValue( dict(all_items=['CH1', 'CH2', 'CH3', 'CH4'], selected=['CH1'])) self.status.initialized = True self.status.controller = self.controller 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 number_of_channel(self): """Return the number of available channel on the scope (4 or 2)""" if ':CH4:SCA' in self.get_setup_dict().keys(): return 4 else: return 2 def load_setup(self): l = self.controller.query('SET?') dico = dict( [e.split(' ') for e in l.split(';')[1:] if len(e.split(' ')) == 2]) self.dico = dico def get_setup_dict(self, force_load=False): """Return the dictionnary of the setup By default, the method does not load the setup from the instrument unless it has not been loaded before or force_load is set to true. """ if not hasattr(self, 'dico') or force_load: self.load_setup() return self.dico 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: pass except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log'])) def close(self): """ close the current instance. """ self.controller._inst.close( ) #the close method has not been written in tektronix object def grab_data(self, Naverage=1, **kwargs): """ | Start new acquisition. | grab the current values with keithley profile procedure. | Send the data_grabed_signal once done. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int Number of values to average =============== ======== =============================================== """ data_tot = [] x_axis = None for ind, channel in enumerate( self.settings.child(('channels')).value()['selected']): if ind == 0: x_axis, data_tmp = self.read_channel_data(channel, x_axis_out=True) else: data_tmp = self.read_channel_data(channel, x_axis_out=False) data_tot.append(data_tmp) self.data_grabed_signal.emit([ DataFromPlugins(name='Tektronix', data=data_tot, dim='Data1D', x_axis=Axis(data=x_axis, label='Time', units='s')) ]) def get_out_waveform_horizontal_sampling_interval(self): return float(self.controller.query('WFMO:XIN?')) def get_out_waveform_horizontal_zero(self): return float(self.controller.query('WFMO:XZERO?')) def get_out_waveform_vertical_scale_factor(self): return float(self.controller.query('WFMO:YMUlt?')) def get_out_waveform_vertical_position(self): return float(self.controller.query('WFMO:YOFf?')) def get_data_start(self): return int(self.controller.query('DATA:START?')) def get_horizontal_record_length(self): return int(self.controller.query("horizontal:recordlength?")) def get_data_stop(self): return int(self.controller.query('DATA:STOP?')) def set_data_source(self, name): self.controller.write('DAT:SOUR ' + str(name)) def read_channel_data(self, channel, x_axis_out=False): self.controller.write("DATA:ENCDG ASCII") self.controller.write("DATA:WIDTH 2") if channel is not None: self.set_data_source(channel) self.offset = self.get_out_waveform_vertical_position() self.scale = self.get_out_waveform_vertical_scale_factor() if x_axis_out: self.data_start = self.get_data_start() self.data_stop = self.get_data_stop() self.x_0 = self.get_out_waveform_horizontal_zero() self.delta_x = self.get_out_waveform_horizontal_sampling_interval() X_axis = self.x_0 + np.arange( 0, self.get_horizontal_record_length()) * self.delta_x res = np.array(self.controller.query_ascii_values('CURVE?')) #res = np.frombuffer(buffer, dtype=np.dtype('int16').newbyteorder('<'), # offset=0) # The output of CURVE? is scaled to the display of the scope # The following converts the data to the right scale Y_axis = (res - self.offset) * self.scale if x_axis_out: return X_axis, Y_axis else: return Y_axis def stop(self): """ not implemented? """ return ""
def initialise(self): rm = ResourceManager() self.handle = rm.open_resource(self.address)
resolution_parameter)) self.dev.write('SENS:{:s}:NPLC {:f}'.format(method_string, integration_time)) def get_errors(self): return self.dev.query('SYST:ERR?') def read(self): return self.dev.query('READ?') @property def resistance(self) -> float: return float(self.read()) if __name__ == '__main__': from visa import ResourceManager from time import sleep rm = ResourceManager('@py') dev = rm.open_resource('GPIB0::9::INSTR') mux = Multimeter34401A(dev) mux.set_sense(SenseMethod.four_probe_resistance) print(mux.get_errors()) print(mux.read())
class DAQ_0DViewer_LockInSR830(DAQ_Viewer_base): """ ==================== ======================== **Attributes** **Type** *data_grabed_signal* instance of pyqtSignal *VISA_rm* ResourceManager *com_ports* *params* dictionnary list *inst* *settings* ==================== ======================== """ data_grabed_signal = pyqtSignal(list) channels = [ 'X', 'Y', 'MAG', 'PHA', 'Aux In 1', 'Aux In 2', 'Aux In 3', 'Aux In 4', 'Ref frequency', 'CH1 display', 'CH2 display' ] ##checking VISA ressources try: from visa import ResourceManager VISA_rm = ResourceManager() devices = list(VISA_rm.list_resources()) device = '' for dev in devices: if 'GPIB' in dev: device = dev break except Exception as e: devices = [] device = '' raise e params = comon_parameters + [ { 'title': 'VISA:', 'name': 'VISA_ressources', 'type': 'list', 'values': devices, 'value': device }, { 'title': 'Manufacturer:', 'name': 'manufacturer', 'type': 'str', 'value': "" }, { 'title': 'Serial number:', 'name': 'serial_number', 'type': 'str', 'value': "" }, { 'title': 'Model:', 'name': 'model', 'type': 'str', 'value': "" }, { 'title': 'Timeout (ms):', 'name': 'timeout', 'type': 'int', 'value': 2000, 'default': 2000, 'min': 1000 }, { 'title': 'Configuration:', 'name': 'config', 'type': 'group', 'children': [{ 'title': 'Channels in separate viewer:', 'name': 'separate_viewers', 'type': 'bool', 'value': True }, { 'title': 'Channels:', 'name': 'channels', 'type': 'itemselect', 'value': dict(all_items=channels, selected=['MAG', 'PHA']) }, { 'title': 'Setup:', 'name': 'setup', 'type': 'group', 'children': [ { 'title': 'Setup number:', 'name': 'setup_number', 'type': 'int', 'value': 0 }, { 'title': 'Save setup:', 'name': 'save_setup', 'type': 'bool', 'value': False }, { 'title': 'Load setup:', 'name': 'load_setup', 'type': 'bool', 'value': False }, ] }] }, ] def __init__(self, parent=None, params_state=None): super(DAQ_0DViewer_LockInSR830, self).__init__(parent, params_state) self.controller = None def query_data(self, cmd): try: res = self.controller.query(cmd) searched = re.search('\n', res) status_byte = res[searched.start() + 1] overload_byte = res[searched.start() + 3] if searched.start != 0: data = np.array( [float(x) for x in res[0:searched.start()].split(",")]) else: data = None return (status_byte, overload_byte, data) except: return ('\x01', '\x00', None) def query_string(self, cmd): try: res = self.controller.query(cmd) searched = re.search('\n', res) status_byte = res[searched.start() + 1] overload_byte = res[searched.start() + 3] if searched.start != 0: str = res[0:searched.start()] else: str = "" return (status_byte, overload_byte, str) except: return ('\x01', '\x00', "") def ini_detector(self, controller=None): """ Initialisation procedure of the detector. Returns ------- The initialized status. 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.controller = controller else: self.controller = self.VISA_rm.open_resource( self.settings.child(('VISA_ressources')).value()) self.controller.timeout = self.settings.child(('timeout')).value() idn = self.controller.query('OUTX1;*IDN?;') idn = idn.rstrip('\n') idn = idn.rsplit(',') if len(idn) >= 0: self.settings.child(('manufacturer')).setValue(idn[0]) if len(idn) >= 1: self.settings.child(('model')).setValue(idn[1]) if len(idn) >= 2: self.settings.child(('serial_number')).setValue(idn[2]) self.reset() 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 reset(self): self.controller.write('*RST') def grab_data(self, Naverage=1, **kwargs): """ | Start new acquisition. | grab the current values. | Send the data_grabed_signal once done. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int Number of values to average =============== ======== =============================================== """ data_tot = [] data = self.controller.query_ascii_values('SNAP ? 1,2,3,4,5,6') data.extend(self.controller.query_ascii_values('SNAP ? 7,8,9,10,11')) selected_channels = self.settings.child('config', 'channels').value()['selected'] data_to_export = [ np.array([data[ind]]) for ind in [self.channels.index(sel) for sel in selected_channels] ] if self.settings.child('config', 'separate_viewers').value(): for ind_channel, dat in enumerate(data_to_export): data_tot.append( DataFromPlugins(name=selected_channels[ind_channel], data=[dat], dim='Data0D', labels=[selected_channels[ind_channel]])) self.data_grabed_signal.emit(data_tot) else: self.data_grabed_signal.emit([ DataFromPlugins(name='SR830', data=data_to_export, dim='Data0D', labels=selected_channels) ]) 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: if param.name() == 'timeout': self.controller.timeout = self.settings.child( ('timeout')).value() if param.name() == 'load_setup': self.controller.write('RSET{:d};'.format( self.settings.child('config', 'setup', 'setup_number').value())) param.setValue(False) if param.name() == 'save_setup': self.controller.write('SSET{:d};'.format( self.settings.child('config', 'setup', 'setup_number').value())) param.setValue(False) elif param.name() == 'channels': data_init = [] for channel in param.value()['selected']: if self.settings.child('config', 'separate_viewers').value(): data_init.append( DataFromPlugins(name=channel, data=[np.array([0])], dim='Data0D')) else: data_init.append(np.array([0])) if self.settings.child('config', 'separate_viewers').value(): self.data_grabed_signal_temp.emit(data_init) else: self.data_grabed_signal_temp.emit([ DataFromPlugins(name='SR830', data=data_init, dim='Data0D') ]) except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log'])) def close(self): """ close the current instance of the visa session. """ self.controller.close()
import dash_html_components as html import dash_daq as daq from dash.dependencies import Input, Output, State from pyInstruments.pid import TemperatureController from threading import Thread from collections import deque from visa import ResourceManager import getopt import sys global N_CLICK_PREVIOUS, MAX_LENGTH N_CLICK_PREVIOUS = 0 MAX_LENGTH = 500 # Listing the available resources lresources = ResourceManager().list_resources() # Initialize the pid task p = TemperatureController() # Preparing the plot plot_layout = dict(margin = {'l': 60, 'r': 60, 'b': 60, 't': 20},\ legend = {'x': 0, 'y': 1, 'xanchor': 'left'},\ xaxis = dict(title = "Timestamp", font = dict(size = 24)),\ yaxis = dict( title = "Temperature (°C)", font = dict(size = 24)) ) calc_status = lambda x: bool(abs(int((1j**x).real))) external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
class MMC_Wrapper(object): """ Wrapper to the MMC dll from Physik Instrumente """ stages = { 'M521DG': dict(cts_units_num=2458624, cts_units_denom=81, units="mm") } VISA_rm = ResourceManager() ress = VISA_rm.list_resources_info() aliases = [] ports = [] for key in ress.keys(): if 'COM' in ress[key].alias: aliases.append(ress[key].alias) ports.append(ress[key].interface_board_number) baudrates = [9600, 19200] def __init__(self, stage='M521DG', com_port='COM1', baud_rate=9600): if stage not in self.stages.keys(): raise Exception('not valid stage') if com_port not in self.aliases: raise IOError('invalid com port') if baud_rate not in self.baudrates: raise IOError('invalid baudrate') self.stage = stage super(MMC_Wrapper, self).__init__() self._comport = com_port self._baudrate = baud_rate self._dll = windll.LoadLibrary( os.path.join(os.path.split(__file__)[0], 'MMC.dll')) @property def comport(self): return self._comport @comport.setter def comport(self, port): if not isinstance(port, str): raise TypeError( "not a valid port type, should be a string: 'COM6'") if port not in self.ports: raise IOError('{} is an invalid COM port'.format(port)) self._comport = port @property def baudrate(self): return self._comport @baudrate.setter def baudrate(self, rate): if not isinstance(rate, int): raise TypeError("not a valid baudrate") if rate not in self.baudrates: raise IOError('{} is an invalid baudrate'.format(rate)) self._baudrate = rate def counts_to_units(self, counts): return counts * 1 / (self.stages[self.stage]['cts_units_num'] / self.stages[self.stage]['cts_units_denom']) def units_to_counts(self, units): return int(units / (self.stages[self.stage]['cts_units_denom'] / self.stages[self.stage]['cts_units_num'])) def moveAbs(self, axis, units): """ displacement in the selected stage units Parameters ---------- units: (float) """ self.MMC_moveA(axis, self.units_to_counts(units)) def moveRel(self, axis, units): """ displacement in the selected stage units Parameters ---------- units: (float) """ self.MMC_moveR(axis, self.units_to_counts(units)) def getPos(self): return self.counts_to_units(self.MMC_getPos()) def open(self): port = self.ports[self.aliases.index(self._comport)] self.MMC_COM_open(port, self._baudrate) def find_home(self): self.MMC_sendCommand('FE1') def moving(self): target = self.MMC_getVal(2) self.MMC_sendCommand('TE') st = self.MMC_getStringCR() if '-' in st: pos = -int(st.split('E:-')[1]) else: pos = int(st.split('E:+')[1]) return abs(target - pos) > 100 def MMC_getStringCR(self): st = create_string_buffer(128) res = self._dll.MMC_getStringCR(byref(st)) if res != 0: return st.decode() else: raise IOError('wrong return from dll') def MMC_COM_open(self, port_number, baudrate): res = self._dll.MMC_COM_open(port_number, baudrate) if res != 0: raise IOError('wrong return from dll') def MMC_COM_close(self): """ Closes the COM port previously opened by the MMC_COM_open function. """ res = self._dll.MMC_COM_close() if res != 0: raise IOError('wrong return from dll') def MMC_COM_EOF(self): """ Returns the number of characters available in the COM-port input buffer Returns ------- int: Number of characters in the input buffer """ res = self._dll.MMC_COM_EOF() return res def MMC_COM_clear(self): """ Clears the COM-port input buffer. """ res = self._dll.MMC_COM_clear() if res != 0: raise IOError('wrong return from dll') def MMC_getDLLversion(self): """ Delivers the version number of the DLL Returns ------- int: version number as integer """ res = self._dll.MMC_getDLLversion() return res def MMC_getPos(self): """ Reads the current motor position of the currently selected Mercury™ controller. The reading process does not interrupt running compound commands. Returns ------- int: Current motor position in counts/steps or error code. The error code is derived from maximum integer value minus the error number: 2,147,483,647 (maxint) : Wrong Content 2,147,483,646 (maxint-1) : Error in _getString 2,147,483,645 (maxint-2) : Error in _sendString 2,147,483,644 (maxint-3) : Error during conversion """ res = self._dll.MMC_getPos() return res def MDC_getPosErr(self): """ Reads the current motor-position error of the currently selected Mercury™ controller. Returns ------- int: Current motor position error in counts or error code. The error code is derived from maximum integer value minus the error number: 2,147,483,647 (maxint) : Wrong Content 2,147,483,646 (maxint-1) : Error in _getString 2,147,483,645 (maxint-2) : Error in _sendString 2,147,483,644 (maxint-3) : Error during conversion """ res = self._dll.MDC_getPosErr() return res def MMC_getVal(self, command_ID: int): """ Reads the value of the requested parameter. The function can be called on the fly. Running compound commands or macros are not interrupted. Parameters ---------- command_ID: (int) Identifier for the requested item: 1 = TP (Tell Position) 2 = TT (Tell Target) 3 = TF (Tell profile following error) 4 = TE (Tell distance to target) 5 = TY (Tell velocity setting) 6 = TL (Tell acceleration setting) 7 = GP (Get p-term setting) 8 = GI (Get i-term setting) 9 = GD (Get d-term setting) 10 = GL (Get i-limit setting) Returns ------- int: The requested value or error code is returned as 32-bit integer. Error codes: 2,147,483,647 (MaxInt) = content error 2,147,483,646 (MaxInt-1) = getString error 2,147,483,645 (MaxInt-2) = sendString error 2,147,483,644 (MaxInt-3) = conversion error """ res = self._dll.MMC_getVal(command_ID) return res def MMC_initNetwork(self, maxAxis: int = 16): """ Searches all addresses, starting at address maxAxis down to 1 for Mercury™ devices connected. If a Mercury™ device (can be C-862, C-863, C-663 or C-170) is found, it is registered so as to allow access through the MMC_select() function. The function MMC_initNetwork is optional. If it is not used, devices can be activated anyway using the MMC_setDevice function. Parameters ---------- maxAxis: (int) This parameter represents the highest device number from which the search is to run, continuing downwards. If you have 3 Mercury™s connected at the addresses 0,1 and 2 (this equals the device numbers 1,2 and 3) you may call the function as MMC_initNetwork(3). If you do no know what addresses the controllers are set to, call the function with maxAxis = 16 to find all devices connected. (Remember that valid device numbers range from 1 to 16.) The range of maxAxis is 1 to 16 Because scanning each address takes about 0.5 seconds, it saves time to not start at device numbers higher than required. Returns ------- list: list of integers corresponding to the connected devices """ devices = [] res = self._dll.MMC_initNetwork(maxAxis) if res < 0: raise IOError('wrong return from dll') if res > 0: bits = Bits(int=res, length=32).bin for ind in range(maxAxis): if bits[-1 - ind] == '1': devices.append(ind + 1) return devices def MMC_moveA(self, axis: int = 0, position: int = 0): """ Moves the motor of the specified axis (device number) to specified position. Parameters ---------- axis: (int) If this parameter is 0 then the move command is sent to the currently selected device. If it is >0 then an address selection code will be sent for the specified axis addressed before the move command is sent. position: (int) The new target position Returns ------- int: Error codes: 0: No error 1: Error, wrong axis 2: Error, not connected 3: Error, sendString """ res = self._dll.MMC_moveA(axis, position) return res def MMC_moveR(self, axis: int = 0, shift: int = 0): """ Moves the motor of the specified axis (device number) relative to its current position by shift counts or steps. Parameters ---------- axis: (int) If this parameter is 0 then the move command is sent to the currently selected device. If it is >0 then an address selection code will be sent for the specified axis before the move command is sent. shift: (int) Position increment added to the current position. Returns ------- int: Error codes: 0: No error 1: Error, wrong axis 2: Error, not connected 3: Error, sendString """ res = self._dll.MMC_moveR(axis, shift) return res def MDC_moving(self): """ Returns the motion status of the currently selected C-862 or C-863 Mercury™ DC motor controller. For C-663 Mercury™-Step controllers, an equivalent function is available. Returns ------- bool: moving status 0: Not moving 1: moving """ res = self._dll.MDC_moving() if res < 0: raise IOError('wrong return from dll') else: return bool(res) def MST_moving(self): """ Returns the moving status of the currently selected Mercury™-Step controller. For Mercury™ DC motor controllers, an equivalent function is available. Returns ------- bool: moving status 0: Not moving 1: moving """ res = self._dll.MST_moving() if res < 0: raise IOError('wrong return from dll') else: return bool(res) def MMC_setDevice(self, axis: int = 0): """ Addresses the selected axis (controller). This function works anytime and it is not required to have registered the devices connected with the MMC_intNetwork function. See also -------- MMC_select() Parameters ---------- axis: (int) Range 1 to 16, Device number of the controller that shall be selected for communication. The device number or address can be set by the controller's front panel DIP switches. """ res = self._dll.MMC_setDevice(axis) if res == 1: raise IOError('Wrong axis number') def MMC_select(self, axis: int = 0): """ Selects the specified axis (device) to enable communication with it. Unlike the MMC_setDevice function, here the registration status is checked, so this function requires that the MMC_initNetwork function have been called previously at the beginning of the program. Parameters ---------- axis: (int) range 1 to 16 Device number of the controller that is to be selected for communication. """ res = self._dll.MMC_select(axis) if res == 1: raise IOError('Wrong axis number') elif res == 2: raise IOError('axis not registered') def MMC_sendCommand(self, cmd): c_cmd = create_string_buffer(cmd.encode()) res = self._dll.MMC_sendCommand(byref(c_cmd)) if res == 114: raise IOError('Write error') elif res == 116: raise IOError('Length Error') def MDC_waitStop(self): """ For C-862 Mercury™ (DC motor) C-863 Mercury™ (DC motor) Waits until the current move has terminated or interrupted by user command (function MCC_GlobalBreak). """ res = self._dll.MDC_waitStop() if res == 1: raise IOError('Error, query') elif res == 2: raise IOError('User break') def MST_waitStop(self): """ For C-663 Mercury™-Step Waits until the current move has terminated or interrupted by user command (function MCC_GlobalBreak). """ res = self._dll.MST_waitStop() if res == 1: raise IOError('Error, query') elif res == 2: raise IOError('User break') def MMC_globalBreak(self): """ This function interrupts pending operations waiting for termination of a move. Can be used with _moving() or _waitStop functions. """ res = self._dll.MMC_globalBreak() if res != 0: raise IOError('wrong return from dll')
def __init__(self, address): rm = ResourceManager() self.device = rm.open_resource(address) idn = self.query('*IDN?') assert '34970A' in idn, 'invalid device identity: %s' % idn
def __init__(self, ip): rm = ResourceManager() self.device = rm.open_resource('TCPIP::%s' % ip)
from visa import ResourceManager from time import sleep rm = ResourceManager() ip = "192.168.0.6" pna = rm.open_resource("TCPIP0::%s::hpib7,16::INSTR" %ip) pna.read_termination = '\n' pna.timeout = 8000 #milisecond pna.write("*RST") pna.write("FORMat:DATA ASCII,0") status = pna.query("CALC1:PAR:CAT?") Catalog = status.replace('"', '').split(',') print(Catalog) Mname = Catalog[0] print("Mname: %s" %Mname) # sweeping type pna.write("SENS:SWE:TYPE CW") sweep_type = pna.query("SENS:SWE:TYPE?") print("sweep type is %s" %sweep_type) #sweeping point pna.write("SENSe:SWEep:POINTs 1001") point = pna.query("SENSe:SWEep:POINTs?") print("point = %s" %point) #sweep frequency pna.write("SENS:FREQuency:STARt 1e9")
class DAQ_1DViewer_LecroyWaverunner6Zi(DAQ_Viewer_base): """ ==================== ======================== **Attributes** **Type** *data_grabed_signal* instance of pyqtSignal *VISA_rm* ResourceManager *com_ports* *params* dictionnary list *keithley* *settings* ==================== ======================== """ data_grabed_signal = pyqtSignal(list) ##checking VISA ressources VISA_rm = ResourceManager() resources = list(VISA_rm.list_resources()) params = comon_parameters + [ { 'title': 'VISA:', 'name': 'VISA_ressources', 'type': 'list', 'values': resources }, { 'title': 'Channels:', 'name': 'channels', 'type': 'itemselect', 'value': dict(all_items=["C1", "C2", "C3", "C4", "F1", "F2", "F3", "F4"], selected=["C1"]) }, ] def __init__(self, parent=None, params_state=None): super(DAQ_1DViewer_LecroyWaverunner6Zi, self).__init__(parent, params_state) self.controller = None def ini_detector(self, controller=None): """ Initialisation procedure of the detector. Returns ------- The initialized status. 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.controller = controller else: self.controller = active_dso usb_address = "USBTMC:" + self.settings.child( ('VISA_ressources')).value() self.controller.MakeConnection(usb_address) # set the timeout of the scope to 10 seconds # may be not needed self.controller.setTimeout(10) self.status.initialized = True self.status.controller = self.controller 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 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: pass except Exception as e: self.emit_status( ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log'])) def grab_data(self, Naverage=1, **kwargs): """ | Start new acquisition. | Grab the current values. | Send the data_grabed_signal once done. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int Number of values to average =============== ======== =============================================== """ channel = self.settings.child(('channels')).value()['selected'] # The WaitForOPC method is used to wait for previous commands to be interpreted before continuing # It may be not needed here if not self.controller.WaitForOPC(): raise Exception("Wait for OPC error") waveform = self.controller.GetScaledWaveformWithTimes( channel[0], 1e8, 0) # The ErrorFlag property checks that there is no error concerning ActiveDSO. # If the user changes some parameters on the oscilloscope (for example the horizontal scale) while pymodaq # acquisition is running, it will raise this error. We do not know how to deal with this problem. # If the error is raised you will probably have to restart the oscilloscope to get the communication back. # Restarting can be done with a little script using the DeviceClear(True) method of ActiveDSO. It is much # faster than doing it manually. # # To prevent the error, the user should use the STOP button on pymodaq GUI, then change the parameter of his # choice on the oscilloscope and then RUN pymodaq acquisition. if self.controller.ErrorFlag: raise Exception(self.controller.ErrorString) x_axis = np.array(waveform[0]) data = [np.array(waveform[1])] self.data_grabed_signal.emit([ OrderedDict(name='Lecroy Waverunner 6Zi', data=data, type='Data1D', x_axis=dict(data=x_axis, label='Time', units='s')) ]) def stop(self): """ not implemented? """ return "" def close(self): """ close the current instance. """ # disconnect the interface with the scope self.controller.Disconnect()