def find(self, idProduct): deviceList = usbtmc.list_devices() while 0: device = deviceList.next() if idProduct == device.idProduct: return usbtmc.Instrument(device) if (debug): print "deviceList = ", deviceList deviceCount = len(deviceList) if (deviceCount == 0): print "There are no USBTMC devices attached or there is a driver problem" raise for device in deviceList: if idProduct == device.idProduct: return usbtmc.Instrument(device) continue try: if (debug): print "trying ", device handle = usbtmc.Instrument(device) reply = handle.ask("*IDN?") if (debug): print "Reply = ", reply if (pe.match(reply)): if (debug): print "Found match" return handle if (debug): print reply, " doesn't match ", regexp except OSError: if (debug): print "DEBUG: Unable to open ", device raise
def __init__(self, resource=None): if resource is not None: self.Instrument = usbtmc.Instrument(resource) else: for r in usbtmc.list_resources(): tmpIntrument = usbtmc.Instrument(str(r)) if tmpIntrument.ask("*IDN?").startswith("B&K Precision, 8600"): self.Instrument = tmpIntrument self.initialize() break
def connect(self, c, idProduct, idVendor, iSerialNumber): '''Attempts to connect to usbtmc with idProduct, idVendor, iSerialNumber.''' #idProduct=0x0957 #idVendor=0x17a4 #iSerialNumber='MY51361370' try: if iSerialNumber != '': self.instr = usbtmc.Instrument(idProduct, idVendor, iSerialNumber) else: self.instr = usbtmc.Instrument(idProduct, idVendor) return "Succesfully connected." except Exception as inst: return str(inst)
def main(): counter = usbtmc.Instrument(_AGILENT_USB_VID, _AGILENT_USB_53230A_PID) counter.timeout = 5. counter.open() try: counter.clear() print "Resetting counter" counter.write("*RST") counter.write("*RST") print "*IDN?", counter.ask("*IDN?") print "Configuring input #1" _ConfigureInput(counter, 1) print "Configuring input #2" _ConfigureInput(counter, 2) #print "Checking input configurations" #print "INP1:LEV?", counter.ask("INP1:LEV?") #print "INP2:LEV?", counter.ask("INP2:LEV?") print "Configuring time interval mode" counter.write("CONF:TINT (@%d),(@%d)" % _TI) count = 0 while True: reading = float(counter.ask("READ?")) print count, reading count = count + 1 except Exception, e: print e
def __init__(self, name='', vendorId=0x0957, productId=0x8B18):#, serialNumber): ''' This will create an instance of the DMM based on the following parameters. :param vendorId: The vendor's identifier. :param productId: The product identifier. :param name: The name used as a reference for the DMM. :param serialNumber: The unique number given by the manufacturer. ''' #0x0957, 0x8B18, try: # Vendor ID, product ID and Serial number are used to create the instance of the DMM. self.__vendor = vendorId self.__product = productId self.__name = name #self.__serialNumber = serialNumber # The mode, range, and plc are used to keep track of the state the DMM is in to prevent unncessary configuration. self.__mode = None self.__range = None self.__currentPlc = None self.__voltagePlc = None self.__model = '' ateConfig.log.logger.debug('Initializing %s (%i:%i)...' % (name, vendorId, productId))#, serialNumber)) self.instr = usbtmc.Instrument(self.__vendor, self.__product)#, self.__serialNumber) ateConfig.log.logger.debug('%s (%i:%i) initialized.' % (name, vendorId, productId))#, serialNumber)) except Exception as e: ateConfig.log.logger.error('Failed to initialize 66321B.') self.instr = None
def __init__(self, ch=1): self.instr = usbtmc.Instrument(0x0a69, 0x084a) self.instr.write("CHAN {}\n".format(ch)) #print self.instr.ask("CHAN?\n") self.instr.write("CHAN:ACT ON\n") self.instr.write(":MODE CCH\n") print "Found: {}".format(self.idn())
def set_Oszi(self, VendorID, ProductID, StartP=1250, EndP=1250): """ By Default 4 Channels are active self.__Channels=[1,2,3,4]. Use self.SetChannels(**Channels) to modify active Channel list. Vendor ID and ProductID, in dec. hex values mus start with 0x. Enc is signed Ascii by default. If you change that, you'll have to adjust self.__widthD yourself. Work in Progress: The measurement methods are now being implemented, aim is to archieve better time resolution """ self.__VID = VendorID self.__PID = ProductID self.__dev = usbtmc.Instrument(VendorID, ProductID) self.SetStartPoint(StartP) self.SetEndPoint(EndP) self.__Channels = [1, 2, 3, 4] self.__voltsDiv = {} self.voltsDiv() self.__widthD = {1: 127, 2: 32767} self.__width = 2 self.SetEncAscii() self.__unitD = {} self.ReadUnit() self.__Offset = {} self.Offset() self.__Inv = {} self.ReadInv() #self.SetImmedTypes("MEAN") self.__IMMESrcD = dict.fromkeys(range(1, 5)) self.__IMMETypD = dict.fromkeys(range(1, 5)) self.__IMMEUniD = dict.fromkeys(range(1, 5)) self.ReadImmedUnits() self.__IMMEValD = dict.fromkeys(range(1, 5))
def activate(self,quiet=False): # Open channel to device self.instr = usbtmc.Instrument(self.params['vid'],self.params['pid']) self.instr.timeout = 2 self.driverConnected = True # Reset device try: if self.subdriver=='thorlabs-tsp01': #self.write("*CLS\r") # clear status self.write("*RST\r") # reset else: self.instr.clear() except usbtmc.usbtmc.UsbtmcException as e: cprint( '\t%s' % e, 'red', attrs=['bold']) # Try and get ID of device as a check for successful connection try: self.params['IDN'] = self.ask("*IDN?") cprint( "\tdetected %s" % self.params['IDN'] ,'green') if self.subdriver=='33220a' or self.subdriver=='dg1000z': self.write("SYST:BEEP") # beep the interface except KeyboardInterrupt: raise except: self.params['IDN']='?' if not quiet: cprint( '[no response]\n', 'yellow', attrs=['bold']) # Make first query to get units, description, etc. self.query(reset=True) if not quiet: self.pprint() return
def __init__(self, *args, **kwargs): logging.basicConfig(filename='metrolab.log', level=logging.DEBUG) self.sensor = usbtmc.Instrument(0x1bfa, 0x0498) # (4096 samples * 3 axes * 4B/sample + 64B for time&temp&... self.max_transfer_size = 49216 # Show sensor name in Terminal ret = self.sensor.ask("*IDN?") print(ret) self.average_count = self.defaults['average'] self.unit = self.defaults['unit'] self.range = self.defaults['range'] # can be 0.1, 0.3, 1 or 3 self.n_digits = self.defaults['n_digits'] self.period = self.defaults['period'] self.block_size = self.defaults['block_size'] # Write settings to device #self.sensor.write(":format:data default") logging.debug('range upper %s', self.sensor.ask(":sense:range:upper?")) # from online repo for sensor self.stop = False self.last_reading = { fetch_kind: None for fetch_kind in self.fetch_kinds} self.data_stack = {fetch_kind: [] for fetch_kind in self.fetch_kinds} self.errors = [] self.setup(**kwargs) logging.info('... End init')
def __init__(self, device='USB0::2391::5981::INSTR'): try: self.instr = usbtmc.Instrument(device) except: print('Instrument was likley not found?') #probably should find a way to list available instruments raise
def __init__(self, *args, **kwargs): if usbtmc is None: raise ImportError("usbtmc is required for TMC instruments.") AbstractCommunicator.__init__(self) self._inst = usbtmc.Instrument(*args, **kwargs) self._terminator = "\n" # Use the system default line ending by default.
def connect(self, address=None): """ Méthode pour établir la connection avec l'oscillo. Si la connection est établie, la fonction renvoie l'identité de l'oscilloscope. ---------- address : str Chaîne de caractères contenant l'addresse VISA de l'instrument. ---------- st : bool 'True' ou 'False' selon la résolution de la connection. """ if self.connection == 'usb': print(usbtmc.list_devices()) self.inst = usbtmc.Instrument(address) try: print(self.inst.ask('*IDN?')) except: print('Connection failed.') self.inst = False else: print('Connection succeed.')
def drift(centroid_avg): tmc_dac = usbtmc.Instrument(0x05e6, 0x2230) tmc_dac.write("INSTrument:COMBine:OFF") tmc_dac.write("SYST:REM") tmc_id = tmc_dac.ask("*IDN?") try: tmc_dac.write("INSTrument:SELect CH1") tmc_dac.write("INSTrument:SELect CH2") tmc_dac.write("APPLY CH1,1.5V,0.1A") tmc_dac.write("APPLY CH2,0.0V,0.0A") tmc_dac.write("OUTPUT ON") tmc_dac.write("SYST:BEEP") # time.sleep(0.3) except: tmc_dac = None print("KEITHLEY DAC: NOT FOUND") time.sleep(0.5) KEITHLEY1_VALUE = 1.5 tmc_dac.write("INST:NSEL 1") tmc_dac.write("VOLT %.3f"%(KEITHLEY1_VALUE)) while True: centroid= centroid_avg.get() if centroid is not None: if centroid >60 : tmc_dac.write("INST:NSEL 1") tmc_dac.write("VOLT %.3f"%((KEITHLEY1_VALUE*1000 - 2)/1000.0)) if centroid < 40: tmc_dac.write("INST:NSEL 1") tmc_dac.write("VOLT %.3f"%((KEITHLEY1_VALUE*1000 + 2)/1000.0))
def PowerMeterConfig(): try: dev = finddev(idVendor=0x1313, idProduct=0x8072) dev.reset() print('Initializing PM100... ', end='') instr = usbtmc.Instrument(4883, 32882) global PowerMeter PowerMeter = ThorlabsPM100(inst=instr) try: print(instr.ask("*IDN?")) except usb.core.USBError: print('...Failed! Continuing to program without PM') global PMAbsent PMAbsent = True #Formatting CSV Files for Power Meter if it is present. csvWrite(PMDataFile, ("# PwrM Sample Time", "Power"), "a") csvWrite(PMInterpFile, ("# XMiss Sample Time", "PwrM Sample Time", "Power", "PwrM Interpolation"), "a") except Exception as Exc: print(Exc) print("Not connected to Power Meter.") PMAbsent = True
def __init__(self): self.instr = usbtmc.Instrument('USB::6833::3601::INSTR') print("=> Dcload: {}".format(self.instr.ask("*IDN?"))) #def __init__(self): for ser_dev in get_serial_dev(): print("Trying: {}".format(ser_dev)) try: for i in range(5): self.instr = serial.Serial(ser_dev, 19200, timeout=1) idn = self.ask("*IDN?") print(idn) if idn: continue except: self.instr.close() continue print(idn) if idn: if idn[0:len(IDN_DL3021)] == IDN_DP71x: print(">> Found PS: {}".format(idn)) self.write(":SYST:REM") time.sleep(0.5) return self.instr.close() print("DL3021 not found!")
def get_instrument(pos): """Returns a new instrument. Args: pos -- device position in devices list (provided by list_devices()) """ return usbtmc.Instrument(usbtmc.list_resources()[pos])
def __init__(self, *args, **kwargs): if usbtmc is None: raise ImportError("usbtmc is required for TMC instruments.") super(USBTMCCommunicator, self).__init__(self) self._filelike = usbtmc.Instrument(*args, **kwargs) self._terminator = "\n"
def __init__(self, DRY=True): self.DRY = DRY if (self.DRY == False): self.psu = usbtmc.Instrument(0x0957, 0x0f07) # Tie into the USB interface fpr the N6705B print(self.ask("*IDN?")) self.pre_wait()
def __init__(self, interface, device='', tcp_port=5025, hostname='', baudrate=9600, visa_string='', line_ending='\r'): self.device = device self.line_ending = line_ending self.interface = interface if self.interface == 'file': self.comm_dev = open(self.device, 'w') self.comm_dev.close() if self.interface == 'serial': self.comm_dev = serial.Serial(self.device, baudrate, timeout=2, xonxoff=True) if self.interface == 'lan': self.comm_dev = telnetlib.Telnet(hostname, tcp_port) if self.interface == 'usbtmc': if usbtmc is None: exit('usbtmc is not availalbe') self.comm_dev = usbtmc.Instrument(visa_string)
def get_oscilloscope(opts): if opts.platform == 'visa': # create device manager object try: rm = visa.ResourceManager() except: rm = visa.ResourceManager('@py') # create instrument object # rm.list_resources() # chamber jet instr = rm.open_resource('USB0::0x1AB1::0x04CE::DS1ZA164457681::INSTR') # control jet #instr = rm.open_resource('USB0::0x1AB1::0x04CE::DS1ZA170603287::INSTR', # timeout=2000, chunk_size=102400) print("device info: {}".format(instr.query("*IDN?"))) print("device timeout: {}".format(instr.timeout)) print("device chunk size: {}".format(instr.chunk_size)) else: instr = usbtmc.Instrument(0x1ab1, 0x04ce) instr.open() instr.rigol_quirk == True #while not (instr.timeout == opts.timeout and instr.rigol_quirk == False): while not (instr.timeout == opts.timeout): instr.timeout = opts.timeout # instr.rigol_quirk = False id = '' while not id: try: id = instr.ask("*IDN?") except Exception as e: # USBError print("{} in get_oscilloscope".format(e)) time.sleep(opts.timeout) print("device info: {}".format(id)) print("device timeout: {}".format(instr.timeout)) return instr
def open(self, instr_addr=None, tcp_timeout=None): '''Open/Reopen Connection The given `instr_address` defines the instrument-address. It can be either - An empty string or None (meaning no address) - IP-Address in digits and dots format (e.g. '192.168.0.170') - TCPIP NI-VISA format: 'TCPIP::<IP-Address>::<PortNo>::SOCKET' (for example: 'TCPIP:192.168.0.170::5025::SOCKET') - USB NI-VISA short-format: 'USB::<VendorId>::<ProductId>::INSTR (for example: 'USB::0x168b::0x2184::INSTR') - USB NI-VISA long-format: 'USB::<VendorId>::<ProductId>::<SerialNo>::INSTR (for example: 'USB::0x168b::0x2184::0000214991::INSTR') In order to findout the USB-Address, use `usbtmc.usbtmc.list_devices()`. If for example it returns: `[<DEVICE ID 168b:2184 on Bus 001 Address 002>]` then the USB-Address is: 'USB::0x168b::0x2184::INSTR'. In case of multiple devices, the serial-number can be added too. For example: 'USB::0x168b::0x2184::0000214991::INSTR' Note: If either `instr_addr` is None or `tcp_timeout` is None, then the the previous value of the relevant argument is used. :param instr_addr: the instrument's address. :param tcp_timeout: TCP-Socket time-out (in seconds) ''' self.close() self._dev_props = None if instr_addr is not None: self._set_instr_address(instr_addr) if tcp_timeout is not None: self._tcp_timeout = float(tcp_timeout) if self._ip_addr is not None: # Open TCP-IP Socket: self._tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) self._tcp_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self._tcp_sock.settimeout(self._tcp_timeout) self._tcp_sock.connect((self._ip_addr, self._tcp_port_nb)) self._intf_type = CommIntfType.LAN elif self._usb_addr is not None: self._usb_sock = usbtmc.Instrument(self._usb_addr) if self._usb_sock is None: warn_msg ='Failed to open USB-TMC Instrument at "{0}".'.format(self._usb_addr) warnings.warn(warn_msg) else: self._intf_type = CommIntfType.USB idn = self.send_query('*IDN?') opt = self.send_query('*OPT?') self._dev_props = get_device_properties(idn, opt) if self._dev_props is None and self._paranoia_level >= 2: warn_msg = 'unsupported model: {0}.'.format(idn) warnings.warn(warn_msg) self._model_name = self.get_dev_property('model_name', '')
def init_device(self): Device.init_device(self) # PROTECTED REGION ID(Keithley2100.init_device) ENABLED START # #instr=usbtmc.Instrument(idVendor,idProduct) self.instr=usbtmc.Instrument(0x05e6,0x2100) self.set_status("Connected to DVMM Keithley 2100") self.debug_stream("Connected to DVMM Keithley 2100") self.set_state(PyTango.DevState.ON)
def connect(self): # Connect to device self.agilent = usbtmc.Instrument(0x0957, 0x0D09) self.time_0 = time.time() # Start thread that reads out the data self.thr = threading.Thread(target=self.create_data_sample, args=()) self.thr.start()
def __init__(self): try: rm = visa.ResourceManager() rm.list_resources() # list available instruments self._instr = rm.open_resource('USB0::0x1AB1::0x0588::DG1D131402088::INSTR') except: self._instr = usbtmc.Instrument(0x1ab1, 0x0588) # RIGOL TECHNOLOGIES,DG1022 ,DG1D131402088 self._instr.timeout = 10
def list_devices(): """List all usbtmc compatible devices connected to PC.""" if not usbtmc.list_resources(): print("No device found.") else: for i in usbtmc.list_resources(): inst = usbtmc.Instrument(i) print(inst.ask("*IDN?"))
def __init__(self): self.instr = usbtmc.Instrument(0x1ab1, 0x04ce) self.MEAS = [ 'VPP', 'VMAX', 'VMIN', 'VAMP', 'VTOP', 'VBAS', 'VAV', 'VRMS', 'OVER', 'PRES', 'FREQ', 'RIS', 'FALL', 'PER', 'PWID', 'NWID', 'PDUT', 'NDUT', 'PDEL', 'NDEL' ] print("=> Scope: {}".format(self.instr.ask("*IDN?")))
def get_instr(): try: if hasattr(get_instr, 'instr'): return get_instr.instr instr = usbtmc.Instrument(0xF4EC, 0xEE3A) get_instr.instr = instr return instr except: pass
def __init__(self, DRY=True, timeout=120): self.DRY = DRY if (self.DRY == False): self.pna = usbtmc.Instrument(0x0957, 0x0118) self.pna.timeout = timeout # Tie into the USB interface fpr the PNA-X print(self.ask("*IDN?")) self.pre_wait() self.extra_sleep = -1
def __init__(self, debug=False): self.debug = debug try: import usbtmc as python_usbtmc self.inst = python_usbtmc.Instrument( 1689, 874) # Works only for Tektronix-TDS2024B except Exception as e: error = "ERROR: Can't create logical usbtmc" print(error) raise Exception(error)
def __init__(self): self.instrumentIdList = self.getInstrumentIdList() self.instr = usbtmc.Instrument(int(self.instrumentIdList[0], 16), int(self.instrumentIdList[1], 16)) self.thread = threading.Thread(target=self.threadRead) self.continuousMeasure = False self.thread.start() self.measure() self.setRange() self.setRate()