Esempio n. 1
0
def _load_usb_backend():
    # First try to find backend locally, if not found try the systems.
    try:
        tmp = os.environ['PATH']
        os.environ['PATH'] = ''
        backend = libusb1.get_backend(find_library=_find_library_local)
        if backend is not None:
            return backend
    finally:
        os.environ['PATH'] = tmp

    backend = libusb1.get_backend()
    if backend is not None:
        return backend
Esempio n. 2
0
def backend_init():
    # Initialize backend
    global BACKEND

    BACKEND = libusb1.get_backend()
    if not BACKEND:
        # Set the libusb path
        if platform.system() in 'Windows':
            if '32bit' in str(platform.architecture()):
                LIBUSB_PATH = resource_path('libusb\\MS32\\libusb-1.0.dll')
            else:
                LIBUSB_PATH = resource_path('libusb\\MS64\\libusb-1.0.dll')
            BACKEND = libusb1.get_backend(find_library=lambda x: LIBUSB_PATH)

    if not BACKEND:
        sys_exit('No USB library found.')
    def __init__(self):
        # attempt to find the PSoC plant electrophys device
        test = libusb1.get_backend()
        print test
        print 'test'
        self.device = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID, backend=libusb1.get_backend())

        if self.device is None:
            print ValueError("Device not found")
        else:
            logging.info("Device found")

        # set the active configuration, pyUSB handles the details
        self.device.set_configuration()
        logging.error("fix above")

        # set the different interfaces and endpoints of the device, see device API for documentation
        usb_config = self.device.get_active_configuration()

        # the communication is on the first interface (0) and the second alternate setting (1)
        communication_interface = usb_config[(0, 1)]

        self.ep_send_info = communication_interface[1]  # the OUT endpoint is EP2
        self.ep_get_info = communication_interface[0]  # the IN endpoint is EP1

        # the communication is on the first interface (0) and the third alternate setting (2)
        data_interface = usb_config[(0, 2)]
        self.ep_get_data = data_interface[0]  # the IN endpoint for ISO data transfer is the 0 EP of interface 0,2
        self.device.set_interface_altsetting(interface=0, alternate_setting=1)
    def open(self, device=None):
        """
        Opens the connection to the Sound Card. If no device is given, it will try to connect to the first Sound Card that is connected to the computer.

        :param device: (Optional) Already initialized libUSB's device to use.
        """
        if device is None:
            self._backend = libusb.get_backend()
            try:
                self._dev = usb.core.find(backend=self._backend,
                                          idVendor=0x04d8,
                                          idProduct=0xee6a)
            except OSError as e:
                self._dev = None
                pass
        else:
            self._dev = device

        if self._dev is None:
            print(
                "Unable to connect to the Sound Card through the USB port. You will be unable to send and receive sounds."
            )
        else:
            # set the active configuration. With no arguments, the first configuration will be the active one
            # note: some devices reset when setting an already selected configuration so we should check for it before
            self._cfg = self._dev.get_active_configuration()
            if self._cfg is None or self._cfg.bConfigurationValue != 1:
                self._dev.set_configuration(1)

        self._connected = True if self._dev else False
Esempio n. 5
0
    def open(self):
        if self._conn_open is True:
            return True

        print('Trying to open USB connection to the Harp sound card')
        backend = libusb.get_backend()
        # backend = libusb.get_backend(find_library=lambda x: "libusb-1.0.dll")
        self._dev = usb.core.find(backend=backend,
                                  idVendor=0x04d8,
                                  idProduct=0xee6a)
        if self._dev is None:
            print(
                f'\tError while trying to connect to the Harp sound card. Please make sure it is connected to the computer and try again.'
            )
            return False

        print(f'backend used: {self._dev.backend}')
        if self._dev is None:
            print(
                '\tSoundCard not found. Please connect it to the USB port before proceeding.'
            )
        else:
            # set the active configuration. With no arguments, the first configuration will be the active one
            # note: some devices reset when setting an already selected configuration so we should check for it before
            _cfg = self._dev.get_active_configuration()
            if _cfg is None or _cfg.bConfigurationValue != 1:
                self._dev.set_configuration(1)
            usb.util.claim_interface(self._dev, 0)

        self._conn_open = True
        return True
Esempio n. 6
0
    def get_possible_devices(self, idProduct=None, dictonly=True):
        """
        Get a list of matching devices being based a list of PIDs. Returns list of usbdev that match (or empty if none)
        """
        if idProduct is None:
            idProduct = [None]

        my_kwargs = {'find_all': True, 'idVendor': 0x2B3E}
        if os.name == "nt":
            #on windows, need to manually load libusb because of 64bit python loading the wrong one
            libusb_backend = libusb1.get_backend()
            if not libusb_backend:
                libusb_backend = libusb0.get_backend(
                    find_library=lambda x: r"c:\Windows\System32\libusb0.dll")
                logging.info("Using libusb0 backend")
            my_kwargs['backend'] = libusb_backend
        devlist = []
        try:
            for id in idProduct:
                if id:
                    dev = list(usb.core.find(idProduct=id, **my_kwargs))
                else:
                    dev = list(usb.core.find(**my_kwargs))
                if len(dev) > 0:
                    if len(dev) == 1:
                        devlist.extend(dev)
                    else:
                        # Deals with the multiple chipwhisperers attached but user only
                        # has permission to access a subset. The langid error is usually
                        # raised when there are improper permissions, so it is used to
                        # skip the those devices. However, the user is warned when this
                        # happens because the langid error is occasionally raised when
                        # there are backend errors.
                        for d in dev:
                            try:
                                d.serial_number
                                devlist.append(d)
                            except ValueError as e:
                                if "langid" in str(e):
                                    logging.info(
                                        'A device raised the "no langid" error, it is being skipped'
                                    )
                                else:
                                    raise
            if dictonly:
                devlist = [{
                    'sn': d.serial_number,
                    'product': d.product,
                    'pid': d.idProduct,
                    'vid': d.idVendor
                } for d in devlist]

            return devlist
        except ValueError as e:
            if "langid" not in str(e):
                raise
            raise OSError(
                "Unable to communicate with found ChipWhisperer. Check that another process isn't connected to it and that you have permission to communicate with it."
            )
Esempio n. 7
0
 def get_storage_device(self):
     devices = list(
         usb.core.find(find_all=True, backend=libusb1.get_backend()))
     storage_device = []
     device_list = self.__get_device_mount_point__(
         self.__get_mass_storage_devices__(devices))
     for device in device_list:
         storage_device.append(StorageDevice(device))
     return storage_device
Esempio n. 8
0
    def __init__(self, use_libusb0 = True):

        self.dev = usb.core.find(idVendor = 0X0456, idProduct = 0XB40D,
                                 backend = libusb0.get_backend() if use_libusb0 else libusb1.get_backend())

        if self.dev is not None:
            self.dev.set_configuration()

        super().__init__(self.dev)
Esempio n. 9
0
    def findBEE(self):
        r"""
        findBEE method
        
        searches for connected printers and tries to connect to the first one.
        """

        self.connected = False

        # find our device
        self.dev = usb.core.find(idVendor=0xFFFF, idProduct=0x014E, backend=libusb1.get_backend())
        # self.dev = usb.core.find(idVendor=0xffff, idProduct=0x014e,backend=libusb0.get_backend())
        # self.dev = usb.core.find(idVendor=0xffff, idProduct=0x014e,backend=openusb.get_backend())

        # was it found? no, try the other device
        if self.dev is None:
            self.dev = usb.core.find(idVendor=0x29C9, idProduct=0x001)
        elif self.dev is None:
            raise ValueError("Device not found")

        if self.dev is None:
            print("Can't Find Printer")
            return

        # set the active configuration. With no arguments, the first
        # configuration will be the active one
        try:
            self.dev.set_configuration()
            self.dev.reset()
            self.cfg = self.dev.get_active_configuration()
            self.intf = self.cfg[(0, 0)]
            print("reconnect")
        except usb.core.USBError as e:
            sys.exit("Could not set configuration: %s" % str(e))

        # self.endpoint = self.dev[0][(0,0)][0]

        self.ep_out = usb.util.find_descriptor(
            self.intf,
            # match the first OUT endpoint
            custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT,
        )

        self.ep_in = usb.util.find_descriptor(
            self.intf,
            # match the first in endpoint
            custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN,
        )

        # Verify that the end points exist
        assert self.ep_out is not None
        assert self.ep_in is not None

        self.connected = True

        return
Esempio n. 10
0
def load_libusb():
    """Apply a patch to pyusb and load the libusb1 backend"""
    # Patch ctypes find_library to look in the correct location
    # import ctypes.util
    # ctypes.util.find_library = find_library

    # Patch the LibUSB init to disable device discovery
    from usb.backend import libusb1

    libusb1._LibUSB.__init__ = libusb_init
    return libusb1.get_backend(find_library)
Esempio n. 11
0
 def find(bus, address):
     gs_usb = usb.core.find(
         idVendor=GS_USB_ID_VENDOR,
         idProduct=GS_USB_ID_PRODUCT,
         bus=bus,
         address=address,
         backend=libusb1.get_backend(),
     )
     if gs_usb:
         return GsUsb(gs_usb)
     return None
Esempio n. 12
0
def find_devices(vendor=None,
                 product=None,
                 serial_number=None,
                 custom_match=None,
                 **kwargs):
    """Find connected USB devices matching certain keywords.

    Wildcards can be used for vendor, product and serial_number.

    :param vendor: name or id of the vendor (manufacturer)
    :param product: name or id of the product
    :param serial_number: serial number.
    :param custom_match: callable returning True or False that takes a device as only input.
    :param kwargs: other properties to match. See usb.core.find
    :return:
    """
    kwargs = kwargs or {}
    attrs = {}
    if isinstance(vendor, str):
        attrs["manufacturer"] = vendor
    elif vendor is not None:
        kwargs["idVendor"] = vendor

    if isinstance(product, str):
        attrs["product"] = product
    elif product is not None:
        kwargs["idProduct"] = product

    if serial_number:
        attrs["serial_number"] = str(serial_number)

    if attrs:

        def cm(dev):
            if custom_match is not None and not custom_match(dev):
                return False
            for attr, pattern in attrs.items():
                try:
                    value = getattr(dev, attr)
                except (NotImplementedError, ValueError):
                    return False
                if not fnmatch(value.lower(), pattern.lower()):
                    return False
            return True

    else:
        cm = custom_match

    ## ADDED THIS to make sure using libusb in this test example
    be = libusb1.get_backend()

    return usb.core.find(backend=be, find_all=True, custom_match=cm, **kwargs)
Esempio n. 13
0
 def scan():
     r"""
     Retrieve the list of gs_usb devices handle
     :return: list of gs_usb devices handle
     """
     return [
         GsUsb(dev) for dev in usb.core.find(
             find_all=True,
             idVendor=GS_USB_ID_VENDOR,
             idProduct=GS_USB_ID_PRODUCT,
             backend=libusb1.get_backend(),
         )
     ]
Esempio n. 14
0
def device_from_fd(fd):
    import usb.backend.libusb1 as libusb1

    backend = libusb1.get_backend()
    if not backend:
        raise NoBackendError('No backend available')

    dev = backend.get_device_from_fd(fd)

    # create device
    device = Device(dev, backend)
    device._ctx.handle = dev

    return device
Esempio n. 15
0
def device_from_fd(fd):
    # setup library
    backend = libusb1.get_backend()
    lib = backend.lib
    ctx = backend.ctx

    # extend c wrapper with android functionality
    lib.libusb_wrap_sys_device.argtypes = [
        libusb1.c_void_p,
        libusb1.c_int,
        libusb1.POINTER(libusb1._libusb_device_handle),
    ]

    lib.libusb_get_device.argtypes = [libusb1.c_void_p]
    lib.libusb_get_device.restype = libusb1._libusb_device_handle

    LOGGER.debug("usb fd: %s", fd)

    # get handle from file descriptor
    handle = libusb1._libusb_device_handle()
    libusb1._check(lib.libusb_wrap_sys_device(ctx, fd, libusb1.byref(handle)))
    LOGGER.debug("usb handle: %s", handle)

    # get device (id?) from handle
    devid = lib.libusb_get_device(handle)
    LOGGER.debug("usb devid: %s", devid)

    # device: devid + handle wrapper
    class DummyDevice:
        def __init__(self, devid, handle):
            self.devid = devid
            self.handle = handle

    dev = DummyDevice(devid, handle)

    # create pyusb device
    device = usb.core.Device(dev, backend)
    device._ctx.handle = dev

    # device.set_configuration()

    return device
    def __init__(self, device=None):
        """
        If a libUSB's device is given, it will try to open it. If none is given it will try to connect to the first Sound Card that is connected to the computer.

        :param device: (Optional) libUSB device to use. If nothing is passed, it will try to connect automatically.
        """
        self._backend = libusb.get_backend()
        try:
            self._devices = list(
                usb.core.find(backend=self._backend,
                              idVendor=0x04d8,
                              idProduct=0xee6a,
                              find_all=True))
        except OSError as e:
            pass

        self._dev = self._devices[0] if self._devices else None
        self._cfg = None
        self._port = None
        self._connected = False

        self.open(self._dev if device is None else device)
Esempio n. 17
0
import usb.backend.libusb1 as libusb1
import usb.util

backend = libusb1.get_backend()
if backend is None:
    raise ValueError('No backend available')

for bus in usb.busses():
    print(bus)
    for device in bus.devices:
        if device != None:
            usbDevice = usb.core.find(idVendor=device.idVendor,
                                      idProduct=device.idProduct)
            print(usbDevice)
Esempio n. 18
0
    def findBEE(self):
        r"""
         findBE-E method
        
        searches for connected printers and tries to connect to the first one.
        """
        
        self.connected = False
  
        # find all devices that match BEEVC USB descriptors
        devices = []           

        d=usb.core.find(find_all=True, idVendor=0xffff, idProduct=0x014e, backend=libusb1.get_backend())
        if d!=None: 
            for a in d: devices.append(a)

        d=usb.core.find(find_all=True, idVendor=0x29c9, idProduct=0x0001, backend=libusb1.get_backend())
        if d!=None: 
            for a in d: devices.append(a)
        
        d=usb.core.find(find_all=True, idVendor=0x29c9, idProduct=0x0002, backend=libusb1.get_backend())
        if d!=None: 
            for a in d: devices.append(a)

        d=usb.core.find(find_all=True, idVendor=0x29c9, idProduct=0x0003, backend=libusb1.get_backend())
        if d!=None: 
            for a in d: devices.append(a)

        d=usb.core.find(find_all=True, idVendor=0x29c9, idProduct=0x0004, backend=libusb1.get_backend())
        if d!=None: 
            for a in d: devices.append(a)
        
        #print("DEVICES:", devices)

        # try to connect to each of the devices found 
        connected=False
        for dev in devices:
            connected = False
            self.dev = dev

            # set the active configuration. With no arguments, the first
            # configuration will be the active one
            try:
                self.dev.set_configuration()
                self.dev.reset()
                time.sleep(0.5)
                #self.dev.set_configuration()
                self.cfg = self.dev.get_active_configuration()
                self.intf = self.cfg[(0,0)]
                print("reconnect")
                connected=True              #if it reached this point witout throwing an exception, we are connected to an available device
                break                       #out of for loop   
            except usb.core.USBError as e: 
                #print("Could not set configuration: %s" % str(e))
                connected=False # if it throws an expception we are not connected
                #time.sleep(1)  #if iterating a big list it is a good idea to let it sleep for a while


        #self.endpoint = self.dev[0][(0,0)][0]
        if connected==False:
            sys.exit("ERROR: Unable to connect to a valid device.")
        else:   #we are connected
            print("Connected to", self.dev.manufacturer, self.dev.product, "(SN:"+self.dev.serial_number+")")
            self.ep_out = usb.util.find_descriptor(
                self.intf,
                # match the first OUT endpoint
                custom_match = \
                lambda e: \
                usb.util.endpoint_direction(e.bEndpointAddress) == \
                usb.util.ENDPOINT_OUT)

            self.ep_in = usb.util.find_descriptor(
                self.intf,
                # match the first in endpoint
                custom_match = \
                lambda e: \
                usb.util.endpoint_direction(e.bEndpointAddress) == \
                usb.util.ENDPOINT_IN)

      # Verify that the end points exist
        assert self.ep_out is not None
        assert self.ep_in is not None
      
        self.connected = True
      
        return
Esempio n. 19
0
__author__ = 'torresmateo'
#!/usr/bin/python
import sys
import usb.core


# find USB devices
dev = usb.core.find(find_all=True)
# loop through devices, printing vendor and product ids in decimal and hex
for cfg in dev:
    print cfg.product
    sys.stdout.write('Decimal VendorID=' + str(cfg.idVendor) + ' & ProductID=' + str(cfg.idProduct) + '\n')
    sys.stdout.write('Hexadecimal VendorID=' + hex(cfg.idVendor) + ' & ProductID=' + hex(cfg.idProduct) + '\n\n')

from usb.backend import libusb1

a = libusb1.get_backend()
print a
Esempio n. 20
0
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)

        self.backend = libusb1.get_backend()

        self.device_connected.connect(self.device_info_receive)
Esempio n. 21
0
 def __init__(self, idVendor=0x0451, idProduct=0xc900):
     
     self.dev=usb.core.find(idVendor=idVendor ,idProduct=idProduct, backend=libusb1.get_backend())
     print(self.dev)
     self.dev.set_configuration()
     self.ans=[]