def __init__(self, dfu_serial): context = usb1.USBContext() for device in context.getDeviceList(skip_on_error=True): if device.getVendorID() == 0x0483 and device.getProductID( ) == 0xdf11: try: this_dfu_serial = device.open().getASCIIStringDescriptor(3) except Exception: continue if this_dfu_serial == dfu_serial or dfu_serial is None: self._handle = device.open() self.legacy = "07*128Kg" in self._handle.getASCIIStringDescriptor( 4) return raise Exception("failed to open " + dfu_serial if dfu_serial is not None else "DFU device")
def wait_for_device(): while 1: try: context = usb1.USBContext() for device in context.getDeviceList(skip_on_error=True): if (device.getVendorID() == 0xbbaa and device.getProductID() == 0xddcc) or \ (device.getVendorID() == 0x0483 and device.getProductID() == 0xdf11): handle = device.open() handle.claimInterface(0) cloudlog.info("found board") handle.close() return except Exception as e: print "exception", e, print "waiting..." time.sleep(1)
def find(vid, pid): """Finds the first USB device with the given vendor id and product id. :param: vid The vendor id to match. :param: pid The product id to match. :return: A LibUSB1Device instance wrapping the matched device. :raises: A NoDeviceError error if no matching device is found. """ context = usb1.USBContext() handle = context.openByVendorIDAndProductID(vid, pid, skip_on_error=True) if handle is None: raise NoDeviceError("No device with vendor %s and product %s" % (vid, pid)) return LibUSB1Device(context, handle)
def __init__(self, serial=None): self.productID = 0x0082 # MCC USB-1208FS self.context = usb1.USBContext() self.udev = self.context.openByVendorIDAndProductID( 0x9db, self.productID) if not self.udev: raise IOError("MCC USB-1208FS not found") for i in range(4): if sys.platform.startswith('linux'): if self.udev.kernelDriverActive(i): self.udev.detachKernelDriver(i) self.udev.resetDevice() self.udev.claimInterface(i) # need to get wMaxPacketSize self.wMaxPacketSize = self.getMaxPacketSize()
def open_dev(usbcontext=None): if usbcontext is None: usbcontext = usb1.USBContext() print 'Scanning for devices...' for udev in usbcontext.getDeviceList(skip_on_error=True): vid = udev.getVendorID() pid = udev.getProductID() if (vid, pid) == (0x14b9, 0x0001): print print print 'Found device' print 'Bus %03i Device %03i: ID %04x:%04x' % ( udev.getBusNumber(), udev.getDeviceAddress(), vid, pid) return udev.open() raise Exception("Failed to find a device")
def open(vid=VID, pid=PID): with usb1.USBContext() as context: handle = context.openByVendorIDAndProductID(vid, pid, skip_on_error=True) if handle is None: raise RuntimeError('could not open PDC002 device') try: handle.setAutoDetachKernelDriver(True) except usb1.USBErrorNotSupported: pass with handle.claimInterface(0): yield PDC002Bootloader(handle)
def __init__(self, path, busnum, devnum, serialnum=None): self.serialnum = serialnum self.ctx = usb1.USBContext() self.handle = None for dev in self.ctx.getDeviceList(): if dev.getBusNumber() == busnum and dev.getDeviceAddress( ) == devnum: self.handle = dev.open() if self.handle is None: raise Exception( "Failed to find power board even though it was enumerated") self.battery = Battery(self.handle) self.output = Outputs(self.handle)
def list(): context = usb1.USBContext() ret = [] try: for device in context.getDeviceList(skip_on_error=True): if device.getVendorID() == 0xbbaa and device.getProductID( ) in [0xddcc, 0xddee]: try: ret.append(device.getSerialNumber()) except Exception: continue except Exception: pass # TODO: detect if this is real # ret += ["WIFI"] return ret
def __init__(self, path, busnum, devnum, serialnum=None): self.serialnum = serialnum self.ctx = usb1.USBContext() self.handle = None for dev in self.ctx.getDeviceList(): if dev.getBusNumber() == busnum and dev.getDeviceAddress( ) == devnum: self.handle = dev.open() if self.handle is None: raise Exception( "Failed to find servo board even though it was enumerated") self._positions = [0] * 12 self.init_board()
def program_device(hex_data, device_info): context = usb1.USBContext() device = get_device_handle(context) if device is None: print("No valid device found.") sys.exit(1) try: print("Connected to bootloader.") # Program in all data from the loaded HEX file, in a number of device # page sized chunks for addr in range(0, hex_data.maxaddr(), device_info['page_size']): # Compute the address range of the current page in the device current_page_range = list( range(addr, addr + device_info['page_size'])) # Extract the data from the hex file at the specified start page # address and convert it to a regular list of bytes page_data = [hex_data[i] for i in current_page_range] print(("Writing address 0x%04X-0x%04X" % (current_page_range[0], current_page_range[-1]))) # Devices with more than 64KB of flash should shift down the page # address so that it is 16-bit (page size is guaranteed to be # >= 256 bytes so no non-zero address bits are discarded) if device_info['flash_kb'] < 64: send_page_data(device, addr, page_data) else: send_page_data(device, addr >> 8, page_data) # Once programming is complete, start the application via a dummy page # program to the page address 0xFFFF print("Programming complete, starting application.") try: device.controlWrite(usb1.libusb1.LIBUSB_REQUEST_TYPE_VENDOR | usb1.libusb1.LIBUSB_RECIPIENT_DEVICE, CONFIG_ID, 0, COMMAND_STARTAPPLICATION, []) # reboot, ignore pipe error except usb1.USBErrorPipe: pass finally: device.close() context.close()
def connect(self, claim=True, wait=False): if self._handle != None: self.close() if self._serial == "WIFI": self._handle = WifiHandle() print("opening WIFI device") self.wifi = True else: context = usb1.USBContext() self._handle = None self.wifi = False while 1: try: for device in context.getDeviceList(skip_on_error=True): #print(device) if device.getVendorID( ) == 0xbbaa and device.getProductID() in [ 0xddcc, 0xddee ]: try: this_serial = device.getSerialNumber() print(this_serial) except Exception: continue if self._serial is None or this_serial == self._serial: self._serial = this_serial print("opening device", self._serial, hex(device.getProductID())) time.sleep(1) self.bootstub = device.getProductID() == 0xddee self.legacy = (device.getbcdDevice() != 0x2300) self._handle = device.open() self._handle.setAutoDetachKernelDriver( True) #dinglx if claim: self._handle.claimInterface(0) #self._handle.setInterfaceAltSetting(0, 0) #Issue in USB stack break except Exception as e: print("exception", e) traceback.print_exc() if wait == False or self._handle != None: break assert (self._handle != None) print("connected")
def _get_class_usb(self): result = [] context = usb1.USBContext() for device in context.getDeviceList(): result.append({ 'bus': device.getBusNumber(), 'address': device.getDeviceAddress(), 'manufacturer': device.getManufacturer(), 'product': device.getProduct(), 'vid': device.getVendorID(), 'pid': device.getProductID(), 'class': device.getDeviceClass() }) context.exit() return result
def __init__(self, logger, bus_id, dev_id): self.__logger = logger self.__context = usb1.USBContext() self.__context.setDebug(3) devices = self.__context.getDeviceList() for device in devices: if (is_rk_device(device) and device.getBusNumber() == bus_id and device.getDeviceAddress() == dev_id): product_id = device.getProductID() self.__read_endpoint = RK_DEVICE_ENDPOINTS[product_id][0] self.__write_endpoint = RK_DEVICE_ENDPOINTS[product_id][1] self.__dev_handle = device.open() if not self.__dev_handle: raise Exception('Failed to open device.')
def __init__(self, context=None): super().__init__() self.owns_context = False if context: self.context = context else: self.context = usb1.USBContext() self.owns_context = True self.handle = self.context.openByVendorIDAndProductID( VENDOR_ID, PRODUCT_ID, #skip_on_error=True, ) if self.handle is None: raise usb1.USBErrorNotFound( 'Device not found or wrong permissions') if usb1.hasCapability(usb1.CAP_SUPPORTS_DETACH_KERNEL_DRIVER): self.handle.setAutoDetachKernelDriver( True) # needed? probably in use by "hid" self.handle.claimInterface(0) self.sendPacket(makePacket(0xCC, 0x60, 0x00)) self.led_order0 = LED(2, 1, 0) #TODO self.led_order1 = LED(2, 1, 0) buff = self.handle.controlRead(0xA1, 0x01, 0x03CC, 0x0000, 64) if len(buff) == 64: self.report = IT8297_Report.from_buffer(buff) print("Product:", self.report.str_product.decode('utf-8')) self.led_order0.r = (self.report.byteorder0 >> 16) & 0xFF self.led_order0.g = (self.report.byteorder0 >> 8) & 0xFF self.led_order0.b = self.report.byteorder0 & 0xFF if self.report.chip_id == 0x82970100: # BX version self.led_order1.r = (self.report.byteorder1 >> 16) & 0xFF self.led_order1.g = (self.report.byteorder1 >> 8) & 0xFF self.led_order1.b = self.report.byteorder1 & 0xFF else: # AX version self.led_order0.r = (self.report.byteorder0 >> 16) & 0xFF self.led_order0.g = (self.report.byteorder0 >> 8) & 0xFF self.led_order0.b = self.report.byteorder0 & 0xFF self._startup()
def open_dev(usbcontext=None, verbose=False): if usbcontext is None: usbcontext = usb1.USBContext() verbose and print('Scanning for devices...') for udev in usbcontext.getDeviceList(skip_on_error=True): vid = udev.getVendorID() pid = udev.getProductID() if (vid, pid) in ((HAM_VID, DC5_PID), (HAM_VID, DC12_PID)): if verbose: print('') print('') print('Found device') print('Bus %03i Device %03i: ID %04x:%04x' % (udev.getBusNumber(), udev.getDeviceAddress(), vid, pid)) return udev.open() raise Exception("Failed to find a device")
def main(): found = False with usb1.USBContext() as context: for device in context.getDeviceIterator(skip_on_error=True): if (device.getVendorID(), device.getProductID()) == (0x0483,0x3748) or \ (device.getVendorID(), device.getProductID()) == (0x0483,0x374b): found = True print('%s (%04x:%04x)' % (device.getProduct(), device.getVendorID(), device.getProductID()) ) oos="" sn=device._getStringDescriptor(device.device_descriptor.iSerialNumber, 0x0409) for x in sn: pass oos +="\\x%02x"%ord(x) print("hla_serial \""+sn+"\"") # this was the easy before, but we print it anyways print("hla_serial \""+oos+"\"") # everything escaped and ready for OpenOCD's tcl scripts if found == False: print("not units found.")
def find_exact(bus, address): """Finds the USB device on the given bus at the given address. :param: bus The bus the device is on. :param: address The address of the device on the bus. :return: A LibUSB1Device instance wrapping the matched device. :raises: A NoDeviceError error if no matching device is found. """ context = usb1.USBContext() for d in context.getDeviceList(skip_on_error=True): if d.getBusNumber() == bus and d.getDeviceAddress() == address: handle = d.open() return LibUSB1Device(context, handle) raise NoDeviceError("No device with bus %d and address %d" % (bus, address))
def gcodecmd(self, cmd, timeout=10, retry_counter=5, retry_timeout=1): try: self._handle.bulkWrite(self.ENDPOINT_CMD_IN, '~{0}\r\n'.format(cmd).encode()) #read data until ok signals end data = '' cmd_done = False while not cmd_done: newdata = self._handle.bulkRead(self.ENDPOINT_CMD_OUT, self.BUFFER_SIZE, int(timeout*1000.0)).decode() if newdata.strip() == 'ok': cmd_done = True elif newdata.strip().endswith('ok'): cmd_done = True data = data + newdata #decode data return data.replace('\r', '') except usb1.USBError as usberror: #retry if retry_counter set if retry_counter > 0: #sleep and retry claiming interface success = False while not success and retry_counter > 0: #wait for timeout time.sleep(retry_timeout) #clean everything up self._handle.releaseInterface(0) self._handle.close() self._context.close() #open device self._context = usb1.USBContext() self._handle = self._context.openByVendorIDAndProductID(self.vendorid, self.deviceid) success = self._handle.claimInterface(0) retry_counter = retry_counter - 1 if success: #if connection successfull gain control. self.gcodecmd('M601 S0') return self.gcodecmd(cmd, timeout, retry_counter-1, retry_timeout) raise FlashForgeError('USB Error', usberror)
def can_init(): global handle, context cloudlog.info("attempting can init") context = usb1.USBContext() #context.setDebug(9) for device in context.getDeviceList(skip_on_error=True): if device.getVendorID() == 0xbbaa and device.getProductID() == 0xddcc: handle = device.open() handle.claimInterface(0) if handle is None: print "CAN NOT FOUND" exit(-1) print "got handle" cloudlog.info("can init done")
def __init__(self, serial=None, claim=True): if serial == "WIFI": self.handle = WifiHandle() print "opening WIFI device" else: context = usb1.USBContext() self.handle = None for device in context.getDeviceList(skip_on_error=True): if device.getVendorID() == 0xbbaa and device.getProductID() == 0xddcc: if serial is None or device.getSerialNumber() == serial: print "opening device", device.getSerialNumber() self.handle = device.open() if claim: self.handle.claimInterface(0) break assert self.handle != None
def __init__(self, serial=None): self.productID = 0x00fe # usb-2408-2AO self.context = usb1.USBContext() self.udev = self.context.openByVendorIDAndProductID( 0x9db, self.productID) if not self.udev: raise IOError("MCC USB-2408-2AO not found") usb_2400.__init__(self) # Build a lookup table of calibration coefficients to translate values to voltages: # corrected value = value * Cal_AO[DAC#].slope + Cal_AO[DAC#].intercept self.Cal_AO = [table(), table()] address = 0x0180 for i in range(0, 2): #two analog output channels self.Cal_AO[i].slope, = unpack('d', self.MemoryR(address, 8)) address += 8 self.Cal_AO[i].intercept, = unpack('d', self.MemoryR(address, 8)) address += 8
def __init__(self, verbose=0, fXtal=114.285, multiplier=4, i2c=0x55, vendor_id=0x16c0, product_id=0x05dc): self.verbose = verbose self.fXtal = fXtal self.multiplier = multiplier self.i2c = i2c self.context = usb1.USBContext() self.device = self.context.getByVendorIDAndProductID( vendor_id, product_id) if self.verbose: print("device", self.device) self.handle = self.device.open() self.version = self.getVersion()
def __init__(self, vendor_id=VID_CYPRESS, product_id=PID_FX2): self.timeout = 1000 try: self.usb_context = usb1.USBContext() self.usb_poller = None self.usb = self.usb_context.openByVendorIDAndProductID(vendor_id, product_id) except usb1.USBErrorAccess: raise FX2DeviceError("Cannot access device {:04x}:{:04x}" .format(vendor_id, product_id)) if self.usb is None: raise FX2DeviceError("Device {:04x}:{:04x} not found" .format(vendor_id, product_id)) try: self.usb.setAutoDetachKernelDriver(True) except usb1.USBErrorNotSupported: pass
def __init__(self, VID=NO_FIRMWARE_VENDOR_ID, PID=PRODUCT_ID_BE): self.device = None self.device_handle = None self.context = usb1.USBContext() self.is_device_firmware_present = False self.supports_single_channel = False self.is_iso = False self.packetsize = None self.num_channels = 2 self.ac_dc_status = 0x11 self.VID=VID self.PID=PID self.calibration = None self.calibration_ext = None self.offset1 = { 1:0, 2:0, 5:0, 10:0 } self.offset2 = { 1:0, 2:0, 5:0, 10:0 } self.gain1 = { 1:1.01, 2:1.01, 5:0.99, 10:1.0 } self.gain2 = { 1:1.01, 2:1.01, 5:0.99, 10:1.0 }
def find(cls, path): if not path.startswith("usb"): return log.debug("using libusb-{0}.{1}.{2}".format(*libusb.getVersion()[0:3])) usb_or_none = re.compile(r'^(usb|)$') usb_vid_pid = re.compile(r'^usb(:[0-9a-fA-F]{4})(:[0-9a-fA-F]{4})?$') usb_bus_dev = re.compile(r'^usb(:[0-9]{1,3})(:[0-9]{1,3})?$') match = None for regex in (usb_vid_pid, usb_bus_dev, usb_or_none): m = regex.match(path) if m is not None: log.debug("path matches {0!r}".format(regex.pattern)) if regex is usb_vid_pid: match = [int(s.strip(':'), 16) for s in m.groups() if s] match = dict(zip(['vid', 'pid'], match)) if regex is usb_bus_dev: match = [int(s.strip(':'), 10) for s in m.groups() if s] match = dict(zip(['bus', 'adr'], match)) if regex is usb_or_none: match = dict() break else: return None context = libusb.USBContext() try: devices = context.getDeviceList(skip_on_error=True) vid, pid = match.get('vid'), match.get('pid') bus, dev = match.get('bus'), match.get('adr') if vid is not None: devices = [d for d in devices if d.getVendorID() == vid] if pid is not None: devices = [d for d in devices if d.getProductID() == pid] if bus is not None: devices = [d for d in devices if d.getBusNumber() == bus] if dev is not None: devices = [d for d in devices if d.getDeviceAddress() == dev] return [(d.getVendorID(), d.getProductID(), d.getBusNumber(), d.getDeviceAddress()) for d in devices] finally: context.exit()
def main(): signal.signal(signal.SIGINT, signal_handler) from optparse import OptionParser parser = OptionParser() parser.add_option( '-c', '--config', default='~/.voctomix-stream-deck.conf', help='Path to config file', ) parser.add_option( '-d', '--device', help='USB device to use, in "bus.dev" format', ) parser.add_option( '-v', '--verbose', action='store_true', help='Print informative messages to stderr', ) (options, args) = parser.parse_args() if options.config is None: parser.print_help(sys.stderr) sys.exit(1) if options.device is None: usb_device = None else: usb_device = options.device.split('.') assert len(usb_device) == 2 usb_device = (int(usb_device[0]), int(usb_device[1])) verbose = options.verbose with usb1.USBContext() as context: handle = getDeviceHandle(context, VENDOR_ID, DEVICE_ID, usb_device) if handle is None: print >> sys.stderr, 'Elgato Stream Deck not found' sys.exit(1) handle.setConfiguration(0) handle.claimInterface(0) while True: data = handle.bulkRead(ENDPOINT, BUFFER_SIZE) print("".join("%02x" % i for i in data))
def open(self): self.context = usb1.USBContext().open() for i in range(10): try: self.handle = self.context.openByVendorIDAndProductID( 0x04e8, 0x685d) break except usb1.USBError: logging.warning('Open USB device failed, retrying...') time.sleep(1) self.handle.claimInterface(self.interface) self.write(b'ODIN') try: response = self.read(7) if response != b'LOKE': raise Exception('Strange response: {}'.format(response)) except usb1.USBErrorTimeout: logging.warning('Protocol initialization failed. Maybe device is ' 'already initialized?')
def check_device(usbcontext=None, verbose=True): if usbcontext is None: usbcontext = usb1.USBContext() for udev in usbcontext.getDeviceList(skip_on_error=True): vid = udev.getVendorID() pid = udev.getProductID() if (vid, pid) in gxs700_fw.pidvid2name_post.keys(): if verbose: print print print 'Found device' print 'Bus %03i Device %03i: ID %04x:%04x' % ( udev.getBusNumber(), udev.getDeviceAddress(), vid, pid) return udev return None
def list_usb(): '''list all available usb devices''' context = usb1.USBContext() devices = context.getDeviceList() for device in devices: vendor = device.getVendorID() product = device.getProductID() print('ID %04x:%04x' % (vendor, product), end=' ') bus = device.getBusNumber() print('->Bus %03i' % bus, end=' ') dev = device.getDeviceAddress() print('Device', dev, end=' ') try: print(device.getProduct(), end=' ') print('by', device.getManufacturer(), end=' ') except: pass print()
def bootloader_boot(): # eventually the hid loader will use this too with usb1.USBContext() as context: voltex = None for dev in context.getDeviceList(): if dev.getVendorID() == 0x16D0 and dev.getProductID() == 0x0A6D: # because there is the pseudo-composite-parent we ignore try: voltex = dev.open() print "Open success!" except: print "Open fail" if voltex is None: # Device not present, or user is not allowed to access device. print("Couldn't find device to reboot") return False with voltex.claimInterface(0): voltex.bulkWrite(1, [42] + [0] * (ENDPOINT_SIZE - 1)) return True