def __init__(self, dev): self.dev = dev self.cfg = cfg = dev.get_active_configuration() self.intf = intf = find_descriptor( cfg, bInterfaceClass=CONFIG["class"], bInterfaceSubClass=CONFIG["subclass"], # bInterfaceProtocol=CCID_PROTOCOL_0, ) if intf is None: raise ValueError("Not a CCID device") claim_interface(dev, intf) for ep in intf: if (endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and endpoint_direction(ep.bEndpointAddress) == ENDPOINT_OUT): self.bulkout = ep.bEndpointAddress if (endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and endpoint_direction(ep.bEndpointAddress) == ENDPOINT_IN): self.bulkin = ep.bEndpointAddress self.seq = 0 self.timeout = 10000
def connect(self): """Attempt to and return connection""" # Disconnect device if it's already connected. if self._connected: self.disconnect() # Find the device by the vendor ID. usb_device = core.find(idVendor=VENDOR_ID) if not usb_device: # Device not found return self._connected # Copy the default configuration. usb_device.set_configuration() config = usb_device.get_active_configuration() interface = config[(0, 0)] # Get the write endpoint. endpoint_out = util.find_descriptor( interface, custom_match=lambda e: util.endpoint_direction( e.bEndpointAddress) == util.ENDPOINT_OUT) assert endpoint_out is not None, 'cannot find write endpoint' # Get the read endpoint. endpoint_in = util.find_descriptor( interface, custom_match=lambda e: util.endpoint_direction( e.bEndpointAddress) == util.ENDPOINT_IN) assert endpoint_in is not None, 'cannot find read endpoint' self._usb_device = usb_device self._endpoint_in = endpoint_in self._endpoint_out = endpoint_out self._connected = True return self._connected
def _open(self) -> None: print('USB OPEN START') try: # find the first USB device that matches the filter self._dev = find(idVendor=self._idVendor, idProduct=self._idProduct) if self._dev is None: raise DriverException("Could not open specified device") # Detach kernel driver try: if self._dev.is_kernel_driver_active(0): try: self._dev.detach_kernel_driver(0) except USBError as e: raise DriverException("Could not detach kernel driver") except NotImplementedError: pass # for non unix systems # set the active configuration. With no arguments, the first # configuration will be the active one self._dev.set_configuration() # get an endpoint instance cfg = self._dev.get_active_configuration() self._interfaceNumber = cfg[(0, 0)].bInterfaceNumber interface = find_descriptor(cfg, bInterfaceNumber=self._interfaceNumber, bAlternateSetting=get_interface( self._dev, self._interfaceNumber)) claim_interface(self._dev, self._interfaceNumber) self._epOut = find_descriptor( interface, custom_match=lambda e: endpoint_direction(e.bEndpointAddress ) == ENDPOINT_OUT) self._epIn = find_descriptor( interface, custom_match=lambda e: endpoint_direction(e.bEndpointAddress ) == ENDPOINT_IN) if self._epOut is None or self._epIn is None: raise DriverException("Could not initialize USB endpoint") self._queue = Queue() self._loop = self.USBLoop(self._epIn, self._packetSize, self._queue) self._loop.start() self._driver_open = True print('USB OPEN SUCCESS') except IOError as e: self._close() raise DriverException(str(e))
def setUp(self): self.dev = usb.core.find(idVendor=0xcafe, idProduct=0xcafe, custom_match=find_by_serial(DUT_SERIAL)) self.assertIsNotNone(self.dev, "Couldn't find ucmx gadget0 device") self.cfg = uu.find_descriptor(self.dev, bConfigurationValue=2) self.assertIsNotNone(self.cfg, "Config 2 should exist") self.dev.set_configuration(self.cfg) self.intf = self.cfg[(0, 0)] # heh, kinda gross... self.ep_out = [ep for ep in self.intf if uu.endpoint_direction(ep.bEndpointAddress) == uu.ENDPOINT_OUT][0] self.ep_in = [ep for ep in self.intf if uu.endpoint_direction(ep.bEndpointAddress) == uu.ENDPOINT_IN][0]
def setUp(self): self.dev = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID, custom_match=find_by_serial(DUT_SERIAL)) self.assertIsNotNone(self.dev, "Couldn't find locm3 gadget0 device") self.cfg = uu.find_descriptor(self.dev, bConfigurationValue=2) self.assertIsNotNone(self.cfg, "Config 2 should exist") self.dev.set_configuration(self.cfg) self.intf = self.cfg[(0, 0)] # heh, kinda gross... self.ep_out = [ep for ep in self.intf if uu.endpoint_direction(ep.bEndpointAddress) == uu.ENDPOINT_OUT][0] self.ep_in = [ep for ep in self.intf if uu.endpoint_direction(ep.bEndpointAddress) == uu.ENDPOINT_IN][0]
def __init__(self, dev): """ __init__(dev) -> None Initialize the DEV of CCID. device: usb.core.Device object. """ cfg = dev.get_active_configuration() intf = find_descriptor(cfg, bInterfaceClass=CCID_CLASS, bInterfaceSubClass=CCID_SUBCLASS, bInterfaceProtocol=CCID_PROTOCOL_0) if intf is None: raise ValueError("Not a CCID device") try: claim_interface(dev, intf) except Exception as e: print(e) for ep in intf: if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \ endpoint_direction(ep.bEndpointAddress) == ENDPOINT_OUT: self.__bulkout = ep.bEndpointAddress if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \ endpoint_direction(ep.bEndpointAddress) == ENDPOINT_IN: self.__bulkin = ep.bEndpointAddress assert len(intf.extra_descriptors) == 54 assert intf.extra_descriptors[1] == 33 if (intf.extra_descriptors[42] & 0x02): # Short APDU level exchange self.__use_APDU = True elif (intf.extra_descriptors[42] & 0x04): # Short and extended APDU level exchange self.__use_APDU = True elif (intf.extra_descriptors[42] & 0x01): # TPDU level exchange self.__use_APDU = False else: raise ValueError("Unknown exchange level") # Check other bits??? # intf.extra_descriptors[40] # intf.extra_descriptors[41] self.__dev = dev self.__timeout = 10000 self.__seq = 0
def __setup_device(self, dev): '''Get endpoints for a device. True on success.''' self.__inep = None self.__outep = None self.__intep = None self.__cfg = None self.__dev = None self.__intf = None # Attempt to find the USB in, out and interrupt endpoints for a PTP # interface. for cfg in dev: for intf in cfg: if intf.bInterfaceClass == PTP_USB_CLASS: for ep in intf: ep_type = endpoint_type(ep.bmAttributes) ep_dir = endpoint_direction(ep.bEndpointAddress) if ep_type == ENDPOINT_TYPE_BULK: if ep_dir == ENDPOINT_IN: self.__inep = ep elif ep_dir == ENDPOINT_OUT: self.__outep = ep elif ((ep_type == ENDPOINT_TYPE_INTR) and (ep_dir == ENDPOINT_IN)): self.__intep = ep if not (self.__inep and self.__outep and self.__intep): self.__inep = None self.__outep = None self.__intep = None else: self.__cfg = cfg self.__dev = dev self.__intf = intf return True return False
def retrieve_device_endpoints(cls, device, return_endpoint_address=False): ep_bulk_in = None ep_bulk_out = None ep_interrupt_in = None # Retrieve device endpoints (BULK and INTERRUPT) for config in device: for intf in config: for ep in intf.endpoints(): ep_type = endpoint_type(ep.bmAttributes) ep_direction = endpoint_direction(ep.bEndpointAddress) if ep_type == ENDPOINT_TYPE_BULK and ep_direction == ENDPOINT_IN: ep_bulk_in = ep elif ep_type == ENDPOINT_TYPE_BULK and ep_direction == ENDPOINT_OUT: ep_bulk_out = ep elif ep_type == ENDPOINT_TYPE_INTR and ep_direction == ENDPOINT_IN: ep_interrupt_in = ep # Ensure that all three endpoints are found if not ep_bulk_in: raise Exception("Missing bulk in endpoint.") elif not ep_bulk_out: raise Exception("Missing bulk out endpoint.") elif not ep_interrupt_in: raise Exception("Missing interrupt in endpoint.") if return_endpoint_address: return ep_bulk_in.address, ep_bulk_out.address, ep_interrupt_in.address else: return ep_bulk_in, ep_bulk_out, ep_interrupt_in
def __init__(self, dev): """ __init__(dev) -> None Initialize the DEV of CCID. device: usb.core.Device object. """ cfg = dev.get_active_configuration() intf = find_descriptor(cfg, bInterfaceClass=CCID_CLASS, bInterfaceSubClass=CCID_SUBCLASS, bInterfaceProtocol=CCID_PROTOCOL_0) if intf is None: raise ValueError("Not a CCID device") claim_interface(dev, intf) for ep in intf: if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \ endpoint_direction(ep.bEndpointAddress) == ENDPOINT_OUT: self.__bulkout = ep.bEndpointAddress if endpoint_type(ep.bmAttributes) == ENDPOINT_TYPE_BULK and \ endpoint_direction(ep.bEndpointAddress) == ENDPOINT_IN: self.__bulkin = ep.bEndpointAddress assert len(intf.extra_descriptors) == 54 assert intf.extra_descriptors[1] == 33 if (intf.extra_descriptors[42] & 0x02): # Short APDU level exchange self.__use_APDU = True elif (intf.extra_descriptors[42] & 0x04): # Short and extended APDU level exchange self.__use_APDU = True elif (intf.extra_descriptors[42] & 0x01): # TPDU level exchange self.__use_APDU = False else: raise ValueError("Unknown exchange level") # Check other bits??? # intf.extra_descriptors[40] # intf.extra_descriptors[41] self.__dev = dev self.__timeout = 10000 self.__seq = 0
def _open(self): # Most of this is straight from the PyUSB example documentation dev = findDeviceUSB( idVendor=self.idVendor, idProduct=self.idProduct, custom_match=lambda d: (d.bus == self.bus or self.bus is None) and (d.address == self.address or self.address is None)) if dev is None: raise DriverError("Could not open device (not found)") # make sure the kernel driver is not active try: if dev.is_kernel_driver_active(0): try: dev.detach_kernel_driver(0) except USBError as e: exit("could not detach kernel driver: {}".format(e)) except NotImplementedError: pass # for non unix systems dev.set_configuration() cfg = dev.get_active_configuration() interfaceNumber = cfg[(0, 0)].bInterfaceNumber intf = find_descriptor(cfg, bInterfaceNumber=interfaceNumber, bAlternateSetting=get_interface( dev, interfaceNumber)) claim_interface(dev, interfaceNumber) endpoint_out_matcher = \ lambda e: endpoint_direction(e.bEndpointAddress) == ENDPOINT_OUT epOut = find_descriptor(intf, custom_match=endpoint_out_matcher) assert epOut is not None endpoint_in_matcher = \ lambda e: endpoint_direction(e.bEndpointAddress) == ENDPOINT_IN ep_in = find_descriptor(intf, custom_match=endpoint_in_matcher) assert ep_in is not None self._epOut = epOut self._epIn = ep_in self._dev = dev self._intNum = interfaceNumber
def connect(self, dev=None, deviceid=None): """ Connects to the device. :params dev: If set, this device will be used instead of searched. :params deviceid: If set, the first device with this rotary id will be used. """ if dev is None: if deviceid: dev = self._search_by_deviceid(deviceid) else: # use the first device dev = usb.core.find(idVendor=0x144a, idProduct=0x7250) if dev is None: raise ValueError('Device not found') self.dev = dev dev.set_configuration() cfg = dev.get_active_configuration() intf = cfg[(0, 0)] for endpoint in intf: if endpoint_address(endpoint.bEndpointAddress) == 0x1: if endpoint_direction( endpoint.bEndpointAddress) == ENDPOINT_IN: self.interupt[0] = endpoint else: self.interupt[1] = endpoint elif endpoint_address(endpoint.bEndpointAddress) == 0x6 \ and endpoint_direction(endpoint.bEndpointAddress) == ENDPOINT_IN: self.bulk[0] = endpoint elif endpoint_address(endpoint.bEndpointAddress) == 0x2 \ and endpoint_direction(endpoint.bEndpointAddress) == ENDPOINT_OUT: self.bulk[1] = endpoint if None in self.interupt: raise RuntimeError("Could not find interupt endpoint") if None in self.bulk: raise RuntimeError("Could not find bulk endpoint") self.connected = True
def _str(self): if util.endpoint_direction(self.bEndpointAddress) == util.ENDPOINT_IN: direction = "IN" else: direction = "OUT" return ("ENDPOINT 0x%X: %s %s" % (self.bEndpointAddress, _lu.ep_attributes[(self.bmAttributes & 0x3)], direction))
def get_endpoint(direction): predicate = lambda ep: \ util.endpoint_type(ep.bmAttributes) == util.ENDPOINT_TYPE_BULK and \ util.endpoint_direction(ep.bEndpointAddress) == direction eps = list(filter(predicate, endpoints)) if len(eps) == 0: raise NeotoolsError( 'Cannot find endpoint with direction %s' % direction) return eps[0]
def _str(self): if util.endpoint_direction(self.bEndpointAddress) == util.ENDPOINT_IN: direction = "IN" else: direction = "OUT" return ( "ENDPOINT 0x%X: %s %s" % (self.bEndpointAddress, _lu.ep_attributes[(self.bmAttributes & 0x3)], direction))
def setUp(self): self.dev = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID, custom_match=find_by_serial(DUT_SERIAL)) self.assertIsNotNone(self.dev, "Couldn't find locm3 gadget0 device") self.cfg = uu.find_descriptor(self.dev, bConfigurationValue=2) self.assertIsNotNone(self.cfg, "Config 2 should exist") self.dev.set_configuration(self.cfg) self.req = uu.CTRL_OUT | uu.CTRL_TYPE_VENDOR | uu.CTRL_RECIPIENT_INTERFACE self.intf = self.cfg[(0, 0)] # heh, kinda gross... self.ep_out = [ ep for ep in self.intf if uu.endpoint_direction(ep.bEndpointAddress) == uu.ENDPOINT_OUT ][0] self.ep_in = [ ep for ep in self.intf if uu.endpoint_direction(ep.bEndpointAddress) == uu.ENDPOINT_IN ][0]
def findUSBEndpoints(idVendor, idProduct, direction): r"""Finds and initializes endpoints At first it searches for matching device, detaches kernel drivers for all interfaces and finally returns first input endpoint object. """ # get device dev = usb.core.find(idVendor = idVendor, idProduct = idProduct, find_all = False ) if dev is None: return None # iterate over all interfaces under device and detach kernel driver for i in objFind( dev, Interface, find_all = True ): if dev.is_kernel_driver_active(i.bInterfaceNumber): dev.detach_kernel_driver(i.bInterfaceNumber) # match endpoint that has input direction matcher = lambda e: endpoint_direction(e.bEndpointAddress) == direction return objFind( dev, Endpoint, matcher = matcher, find_all = False )
def open(self): # If we get here, the device should be accessible, and with a valid configuration # so, check for 'Picoprobeness' # Search the Vendor Specific interface in first configuration for i in self._dev[0]: if i.bInterfaceClass == PicoLink.CLASS: self._if = i break # Check for a missing device interface if self._if is None: raise exceptions.ProbeError() # Scan and assign Endpoints for e in self._if: if util.endpoint_direction( e.bEndpointAddress) == util.ENDPOINT_OUT: self._wr_ep = e else: self._rd_ep = e # Something is missing from this probe! if self._wr_ep is None or self._rd_ep is None: raise exceptions.ProbeError("Unrecognized Picoprobe interface")
def __str__(self): headstr = " " + self._str() + " " if util.endpoint_direction(self.bEndpointAddress) == util.ENDPOINT_IN: direction = "IN" else: direction = "OUT" return "%s%s\n" % (headstr, "=" * (60 - len(headstr))) + \ " %-17s:%#7x (7 bytes)\n" % ( "bLength", self.bLength) + \ " %-17s:%#7x %s\n" % ( "bDescriptorType", self.bDescriptorType, _try_lookup(_lu.descriptors, self.bDescriptorType)) + \ " %-17s:%#7x %s\n" % ( "bEndpointAddress", self.bEndpointAddress, direction) + \ " %-17s:%#7x %s\n" % ( "bmAttributes", self.bmAttributes, _lu.ep_attributes[(self.bmAttributes & 0x3)]) + \ " %-17s:%#7x (%d bytes)\n" % ( "wMaxPacketSize", self.wMaxPacketSize, self.wMaxPacketSize) + \ " %-17s:%#7x" % ("bInterval", self.bInterval)
def __setup_device(self, dev): '''Get endpoints for a device. True on success.''' self.__inep = None self.__outep = None self.__intep = None self.__cfg = None self.__dev = None self.__intf = None # Attempt to find the USB in, out and interrupt endpoints for a PTP # interface. for cfg in dev: for intf in cfg: if intf.bInterfaceClass == PTP_USB_CLASS: for ep in intf: ep_type = endpoint_type(ep.bmAttributes) ep_dir = endpoint_direction(ep.bEndpointAddress) if ep_type == ENDPOINT_TYPE_BULK: if ep_dir == ENDPOINT_IN: self.__inep = ep elif ep_dir == ENDPOINT_OUT: self.__outep = ep elif ((ep_type == ENDPOINT_TYPE_INTR) and (ep_dir == ENDPOINT_IN)): self.__intep = ep if not (self.__inep and self.__outep and self.__intep): self.__inep = None self.__outep = None self.__intep = None else: logger.debug('Found {}'.format(repr(self.__inep))) logger.debug('Found {}'.format(repr(self.__outep))) logger.debug('Found {}'.format(repr(self.__intep))) self.__cfg = cfg self.__dev = dev self.__intf = intf return True return False
def __init__(self, product: int, timeout: Optional[float] = 5) -> None: print(f"__init__({product}, {timeout})") if timeout is not None: timeout += time() while True: device = find(idVendor=0x27c6, idProduct=product) if device is not None: try: if get_status(device) == 0x0001: break except USBError as error: if (error.backend_error_code != -1 and error.backend_error_code != -4): raise error if timeout is not None and time() > timeout: if device is None: raise USBTimeoutError("Device not found", -5, 19) raise USBTimeoutError("Invalid device state", -12, 131) sleep(0.01) self.device: USBDevice = device print(f"Found Goodix device: \"{self.device.product}\" " f"from \"{self.device.manufacturer}\" " f"on bus {self.device.bus} " f"address {self.device.address}.") interface = find_descriptor(self.device.get_active_configuration(), bInterfaceClass=CLASS_DATA) if interface is None: raise USBError("Interface data not found", -5, 6) print(f"Found interface data: {interface.bInterfaceNumber}") endpoint_in = find_descriptor( interface, custom_match=lambda endpoint: endpoint_direction( endpoint.bEndpointAddress) == ENDPOINT_IN and endpoint_type( endpoint.bmAttributes) == ENDPOINT_TYPE_BULK) if endpoint_in is None: raise USBError("Endpoint in not found", -5, 6) self.endpoint_in: int = endpoint_in.bEndpointAddress print(f"Found endpoint in: {hex(self.endpoint_in)}") endpoint_out = find_descriptor( interface, custom_match=lambda endpoint: endpoint_direction( endpoint.bEndpointAddress) == ENDPOINT_OUT and endpoint_type( endpoint.bmAttributes) == ENDPOINT_TYPE_BULK) if endpoint_out is None: raise USBError("Endpoint out not found", -5, 6) self.endpoint_out: int = endpoint_out.bEndpointAddress print(f"Found endpoint out: {hex(self.endpoint_out)}") # Empty device reply buffer (Current patch while waiting for a fix) self.empty_buffer()