Ejemplo n.º 1
0
 def profileusb(self, other):
     del other
     dev = find(find_all=True)
     devices = []
     for cfg in dev:
         devclass = str(cfg.bDeviceClass)
         product = str(cfg.iProduct)
         vid = hex(cfg.idVendor)
         pid = hex(cfg.idProduct)
         for line in Configuration(find(idVendor=cfg.idVendor)):
             line = str(line)
             linestrip = line.strip()
             linesplit = linestrip.split('\n')
             linesplit = [x.split(':') for x in linesplit]
             lines = []
             for w in linesplit:
                 lines.append([y.strip(' ') for y in w])
             for e in lines:
                 if 'bInterfaceClass' in e[0]:
                     intclass = e[1]
                     devices.append([devclass, product, vid, pid, intclass])
     with open('devices.pkl', 'wb') as f:
         dump(devices, f)
     self.profile.SetLabel("Done!")
     self.profile.Disable()
     self.test.Enable()
Ejemplo n.º 2
0
    def open(self, vendor=None, product=None):
        if vendor is not None and product is not None:
            dev = ucore.find(idVendor=vendor, idProduct=product)
        else:
            def match(d):
                return (d.idVendor, d.idProduct) in supported_devices

            dev = ucore.find(custom_match=match)

        self.open_dev(dev)
Ejemplo n.º 3
0
 def testusb(self, other):
     del other
     with open('devices.pkl', 'rb') as f:
         benchmark = load(f)
     dev = find(find_all=True)
     devices = []
     for cfg in dev:
         devclass = str(cfg.bDeviceClass)
         product = str(cfg.iProduct)
         vid = hex(cfg.idVendor)
         pid = hex(cfg.idProduct)
         for line in Configuration(find(idVendor=cfg.idVendor)):
             line = str(line)
             linestrip = line.strip()
             linesplit = linestrip.split('\n')
             linesplit = [x.split(':') for x in linesplit]
             lines = []
             for w in linesplit:
                 lines.append([y.strip(' ') for y in w])
             for e in lines:
                 if 'bInterfaceClass' in e[0]:
                     intclass = e[1]
                     devices.append([devclass, product, vid, pid, intclass])
     first_tuple_list = [tuple(lst) for lst in benchmark]
     secnd_tuple_list = [tuple(lst) for lst in devices]
     first_set = set(first_tuple_list)
     secnd_set = set(secnd_tuple_list)
     output = ""
     height = 100
     first = 0
     for devclass, product, vid, pid, usbtype in first_set.symmetric_difference(
             secnd_set):
         if usbtype == "0xa CDC Data":
             devicedesc = "Virtual Data Port (Network)"
         elif usbtype == "0xe0 Wireless Controller":
             devicedesc = "Wireless Internet Or Bluetooth"
         elif usbtype == "0x8 Mass Storage":
             devicedesc = "Data Storage Device"
         elif usbtype == "0x9 Hub":
             devicedesc = "USB Hub"
         elif usbtype == "0x3 Human Interface Device":
             devicedesc = "Keyboard, Mouse, or Other Input Device"
         elif usbtype == "0x2 CDC Communication":
             devicedesc = "Vitual Communications Port (Network)"
         else:
             devicedesc = usbtype + " device "
         if first == 0:
             output += "This appears to be a: \n                     " + devicedesc + " \n"
         else:
             output += "                     " + devicedesc + " \n"
         height = height + 30
         first = 1
     self.SetSize((500, height))
     self.message.SetLabel(output)
Ejemplo n.º 4
0
def PlhUSBConnection(tracker_id):
    trck_init = None
    try:
        import usb.core as uc
        # Check the idProduct using the usbdeview software, the idProduct is unique for each
        # device and connection fails when is incorrect
        # trck_init = uc.find(idVendor=0x0F44, idProduct=0x0003) [used in a different device]
        trck_init = uc.find(idVendor=0x0F44, idProduct=0xEF12)
        cfg = trck_init.get_active_configuration()
        for i in cfg:
            for x in i:
                # TODO: try better code
                x = x
        trck_init.set_configuration()
        endpoint = trck_init[0][(0, 0)][0]
        if tracker_id == 2:
            # Polhemus FASTRAK needs configurations first
            # TODO: Check configurations to standardize initialization for all Polhemus devices
            trck_init.write(0x02, "u")
            trck_init.write(0x02, "F")
        # First run to confirm that everything is working
        trck_init.write(0x02, "P")
        data = trck_init.read(endpoint.bEndpointAddress,
                              endpoint.wMaxPacketSize)
        if not data:
            trck_init = None
            print('Could not connect to Polhemus USB without error.')

    except:
        print('Could not connect to Polhemus USB with error.')

    return trck_init
Ejemplo n.º 5
0
 def __init__(self, vi, pi, ledonly, relaisonly, reset):
     self.ledonly = ledonly
     self.relaisonly = relaisonly
     self.index = 0
     self.devices = []
     devicesraw = find(idVendor=vi, idProduct=pi, find_all=True)
     for dev in devicesraw:
         dev.id = len(self.devices)
         self.devices.append(dev)
     for dev in self.devices:
         if dev:
             ep = dev[0].interfaces()[0].endpoints()[0]
             intf = dev[0].interfaces()[0].bInterfaceNumber
             if dev.is_kernel_driver_active(intf):
                 try:
                     dev.detach_kernel_driver(intf)
                 except USBError as e:
                     sys.exit('Could not detatch kernel driver:' + str(e))
             try:
                 dev.set_configuration()
                 if reset:
                     dev.reset()
             except USBError as e:
                 sys.exit('Could not set configuration:' + str(e))
             dev.eaddr = ep.bEndpointAddress
             while True:
                 result = self.bulk_transfer_from_device(6)
                 if result[0] == 0:
                     sleep(0.1)
                 else:
                     break
             self.old_state = result
         else:
             print('No device connected')
Ejemplo n.º 6
0
    def __init__(self, idVendor=0x2121, idProduct=0x2130, configuration=(0,0)):
        self.status = ("Initializing", False)
        import usb.core as usbcore
        self.dev = usbcore.find(idVendor=idVendor, idProduct=idProduct)
        import usb.backend.libusb0
        backend = usb.backend.libusb0.get_backend(find_library=lambda x: r'./windows_dll/libusb0.dll')
        self.dev = usb.core.find(idVendor=idVendor, idProduct=idProduct, backend=backend)
        if self.dev:
            self.dev.set_configuration()
            self.cfg = self.dev.get_active_configuration()
            self.inf = self.cfg[configuration]
            self.endpoint_out = usb.util.find_descriptor(self.inf, custom_match = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)
            self.endpoint_in = usb.util.find_descriptor(self.inf, custom_match = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN)
            self.send(cnc_commands.cmd_init_1())
            self.send(cnc_commands.cmd_init_2())
            self.send(cnc_commands.cmd_init_3())
            self.send(cnc_commands.cmd_init_4())
            self.send(cnc_commands.cmd_init_5())
            self.send(cnc_commands.cmd_init_6())
            self.send(cnc_commands.cmd_init_7())
            self.send(cnc_commands.cmd_init_8())
            self.send(cnc_commands.cmd_init_9())
            self.send(cnc_commands.cmd_init_10())
            self.restore_config(r"./valves/VWR_Plate_Lid.json")

        else:
            raise Exception, "Can't find device with vendor %0d and product %0d!" % (idVendor, idProduct)
Ejemplo n.º 7
0
def detect_tablet():
    try:
        dev = core.find(idVendor=0x256c, idProduct=0x006e)
        return True if dev is not None else False
    except Exception as e:
        print("An error has occurred upon detecting device: {}".format(e))
    return False
Ejemplo n.º 8
0
 def __init__(self):
     LOG.debug('probing usb devices')
     self.device = find(idVendor=OUTLET_USB_VENDOR_ID,
                        idProduct=OUTLET_USB_PRODUCT_ID)
     LOG.info('found device: %r', self.device)
     if not self.device:
         raise USBError('cannot find USB device')
Ejemplo n.º 9
0
    def PlhPatriot(self):
        trck_init = None

        try:
            import sys

            import usb.core as uc
            # import usb.util as uu

            trck_init = uc.find(idVendor=0x0F44, idProduct=0xEF12)

            if not trck_init:
                print 'Could not find Polhemus PATRIOT USB. Trying Polhemus ' \
                      'serial connection...'

                trck_init = self.polhemus_serial(3)

            else:
                try:
                    cfg = trck_init.get_active_configuration()
                    for i in cfg:
                        for x in i:
                            # TODO: try better code
                            x = x
                    trck_init.set_configuration()

                except uc.USBError as err:
                    dlg.TrackerNotConnected(3)
                    print 'Could not set configuration %s' % err

        except ImportError:
            print 'Import Error for Polhemus PATRIOT USB.'
            trck_init = self.polhemus_serial(3)

        return trck_init
Ejemplo n.º 10
0
def PlhUSBConnection(tracker_id):
    trck_init = None
    try:
        import usb.core as uc
        # Check the idProduct using the usbdeview software, the idProduct is unique for each
        # device and connection fails when is incorrect
        # trck_init = uc.find(idVendor=0x0F44, idProduct=0x0003) [used in a different device]
        trck_init = uc.find(idVendor=0x0F44, idProduct=0xEF12)
        cfg = trck_init.get_active_configuration()
        for i in cfg:
            for x in i:
                # TODO: try better code
                x = x
        trck_init.set_configuration()
        endpoint = trck_init[0][(0, 0)][0]
        if tracker_id == 2:
            # Polhemus FASTRAK needs configurations first
            # TODO: Check configurations to standardize initialization for all Polhemus devices
            trck_init.write(0x02, "u")
            trck_init.write(0x02, "F")
        # First run to confirm that everything is working
        trck_init.write(0x02, "P")
        data = trck_init.read(endpoint.bEndpointAddress,
                              endpoint.wMaxPacketSize)
        if not data:
            trck_init = None
            print('Could not connect to Polhemus USB without error.')

    except:
        print('Could not connect to Polhemus USB with error.')

    return trck_init
Ejemplo n.º 11
0
 def find_usb_device(self, serial_number):
     # return a usb_device
     try:
         all_devices = core.find(find_all=True, idVendor=0x2457)
         found_device = False
         for self.__usb_device in all_devices:
             try:
                 self.__usb_device.set_configuration()
             except core.USBError:
                 raise core.USBError(
                     "Could not configure the usb device in OceanOpticsDevice.find_usb_device()"
                 )
             # since this is USB the device name and ocean optics protocol are implied from the productID
             self.__ocean_optics_protocol = \
                 device_identity.get_ocean_optics_device_protocol(self.__usb_device.idProduct)
             self.__device_name = device_identity.get_ocean_optics_device_name(
                 self.__usb_device.idProduct)
             self.set_product_id_and_usb_endpoints(
                 self.__usb_device.idProduct)
             self.__serial_number = self.__introspection_methods.serial_number_get(
             )
             if serial_number == self.__serial_number:
                 found_device = True
                 break
     except core.NoBackendError:
         raise RuntimeError(
             "Error: libusb is probably not installed on the host machine.\n{0}",
             sys.exc_info()[0])
     return found_device
Ejemplo n.º 12
0
    def PlhPatriot(self):
        trck_init = None

        try:
            import sys

            import usb.core as uc
            # import usb.util as uu

            trck_init = uc.find(idVendor=0x0F44, idProduct=0xEF12)

            if not trck_init:
                print 'Could not find Polhemus PATRIOT USB. Trying Polhemus ' \
                      'serial connection...'

                trck_init = self.polhemus_serial(3)

            else:
                try:
                    cfg = trck_init.get_active_configuration()
                    for i in cfg:
                        for x in i:
                            # TODO: try better code
                            x = x
                    trck_init.set_configuration()

                except uc.USBError as err:
                    dlg.TrackerNotConnected(3)
                    print 'Could not set configuration %s' % err

        except ImportError:
            print 'Import Error for Polhemus PATRIOT USB.'
            trck_init = self.polhemus_serial(3)

        return trck_init
Ejemplo n.º 13
0
def PlhUSBConnection(tracker_id):
    trck_init = None
    try:
        import usb.core as uc
        trck_init = uc.find(idVendor=0x0F44, idProduct=0x0003)
        cfg = trck_init.get_active_configuration()
        for i in cfg:
            for x in i:
                # TODO: try better code
                x = x
        trck_init.set_configuration()
        endpoint = trck_init[0][(0, 0)][0]
        if tracker_id == 2:
            # Polhemus FASTRAK needs configurations first
            # TODO: Check configurations to standardize initialization for all Polhemus devices
            trck_init.write(0x02, "u")
            trck_init.write(0x02, "F")
        # First run to confirm that everything is working
        trck_init.write(0x02, "P")
        data = trck_init.read(endpoint.bEndpointAddress,
                              endpoint.wMaxPacketSize)
        if not data:
            trck_init = None

    except:
        print 'Could not connect to Polhemus USB.'

    return trck_init
        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
Ejemplo n.º 15
0
def __plugDevice(flag, dom, usbmap):              
        for dev in core.find(find_all=True):
            for cfg in dev:
                intf = util.find_descriptor(cfg, find_all=True)
                intf0 = util.find_descriptor(cfg, bInterfaceClass=0)
                intf3 = util.find_descriptor(cfg, bInterfaceClass=3)
                intf9 = util.find_descriptor(cfg, bInterfaceClass=9)
                if intf != None and intf0 == None and intf3 == None and intf9 == None:
                    idVendor = str(hex(dev.idVendor))
                    if len(idVendor) < 6:
                        idVendor = '0x' + '0' * (6 - len(idVendor)) + idVendor[2:]
                     
                    idProduct = str(hex(dev.idProduct))
                    if len(idProduct) < 6:
                        idProduct = '0x' + '0' * (6 - len(idProduct)) + idProduct[2:]

                    xml = __generateUSBXML(idVendor, idProduct)
                    if dom != None and dom.isActive() == True:
                        if flag:
                            dom.attachDevice(xml)
                            syspath=__getSysPath(idVendor, idProduct)
                            if syspath != None:
                                usbmap[syspath]=idProduct+idVendor
                        else:
                            dom.detachDevice(xml)
                            syspath=__getSysPath(idVendor, idProduct)
                            if syspath != None:
                                usbmap.pop(syspath)
                    else:
                        pass 
Ejemplo n.º 16
0
    def __init__(self):
        super().__init__("IS-NITRO-Emulator")
        self.device = find(idVendor=0x0F6e, idProduct=0x0404)

        if self.device is None:
            raise DeviceNotFound(self)

        if self.debug:
            self.print_configurations()

        self.device.set_configuration()
        # self.device.reset()  # Prevent weird timeouts when used twice

        config = self.device.get_active_configuration()
        interface = config[(0, 0)]

        # Claim interface
        if self.device.is_kernel_driver_active(interface.iInterface):
            self.device.detach_kernel_driver(interface.iInterface)
            claim_interface(self.device, interface.iInterface)

        self.endpoint_out = find_descriptor(interface,
                                            bEndpointAddress=0x01)  # Bulk Out
        self.endpoint_in = find_descriptor(interface,
                                           bEndpointAddress=0x82)  # Bulk in
        # self.endpoint_debug = find_descriptor(interface, bEndpointAddress=0x83)  # Bulk in 2?

        assert self.endpoint_out is not None
        assert self.endpoint_in is not None

        self.isid = resource_stream(__name__, "../resources/isid.bin").read()
        self.debugger_code = resource_stream(
            __name__, "../resources/debugger_code.bin").read()
Ejemplo n.º 17
0
    def open_devpath(self, busnum: int, address: int):
        def match(d):
            return d.bus == busnum and d.address == address

        dev = ucore.find(custom_match=match)

        self.open_dev(dev)
Ejemplo n.º 18
0
def find_all_usb_devices():
    device_list = list()
    try:
        all_devices = core.find(find_all=True, idVendor=0x2457)
        for a_usb_device in all_devices:
            try:
                a_usb_device.set_configuration()
            except core.USBError:
                raise core.USBError(
                    "Could not configure the usb device in OceanOpticsDevice.find_usb_device()"
                )

            oo_protocol = device_identity.get_ocean_optics_device_protocol(
                a_usb_device.idProduct)
            oo_device_name = device_identity.get_ocean_optics_device_name(
                a_usb_device.idProduct)
            oo_device = OceanOpticsDevice(
                interface_type=InterfaceType.USB,
                product_id=a_usb_device.idProduct,
                ocean_optics_protocol=oo_protocol,
                ocean_optics_device_name=oo_device_name)
            device_list.append(a_usb_device)
    except core.NoBackendError:
        raise RuntimeError(
            "Error: libusb is probably not installed on the host machine.\n{0}",
            sys.exc_info()[0])
    return device_list
 def listPrinters(self):
     printers = core.find(find_all=True)  # , bDeviceClass=7)
     for printer in printers:
         print printer.bDeviceClass
         try:
             print util.get_string(printer, 256, 3)
         except:
             print 'dispositivo oculto'
Ejemplo n.º 20
0
 def __init__(self):
     self.dev = u.find(idVendor=0x2123, idProduct=0x1010)
     if self.dev is None:
         raise IOError('Dream Cheeky missile launcher not found.')
     if self.dev.is_kernel_driver_active(0):
         self.dev.detach_kernel_driver(0)
     self.dev.set_configuration()
     print 'missile launcher initialized'
Ejemplo n.º 21
0
 def enumerate_picoprobes(cls, uid=None) -> List["PicoLink"]:
     """! @brief Find and return all Picoprobes """
     # Use a custom matcher to make sure the probe is a Picoprobe and accessible.
     return [
         PicoLink(probe)
         for probe in core.find(find_all=True,
                                custom_match=FindPicoprobe(uid))
     ]
Ejemplo n.º 22
0
 def _get_device_available(self, find=False):
     """Find the K85 and return True if it is connected"""
     device = usb.find(idVendor=bVendor, idProduct=bProduct)
     if device is None:
         return False if find is False else None
     if isinstance(device, list):
         device = device[0]
     return True if find is False else device
Ejemplo n.º 23
0
 def usb_loop(self):
     usb_devices = {}
     devs = core.find(find_all=True)
     for dev in devs:
         path =  "usb_%04x:%04x_%03d_%03d_" % (dev.idVendor, dev.idProduct, dev.bus, dev.address)
         iot_device = IoTDevice(dev, 'usb')
         usb_devices[path] = iot_device
     return usb_devices
Ejemplo n.º 24
0
    def test_find(self):
        b = _MyBackend()
        self.assertEqual(find(backend=b, idVendor=1), None)
        self.assertNotEqual(find(backend=b, idProduct=1), None)
        self.assertEqual(len(tuple(find(find_all=True, backend=b))),
                         len(b.devices))
        self.assertEqual(
            len(tuple(find(find_all=True, backend=b, idProduct=1))), 1)
        self.assertEqual(
            len(tuple(find(find_all=True, backend=b, idVendor=1))), 0)

        self.assertEqual(
            len(
                tuple(
                    find(find_all=True,
                         backend=b,
                         custom_match=lambda d: d.idProduct == 1))), 1)

        self.assertEqual(
            len(
                tuple(
                    find(
                        find_all=True,
                        backend=b,
                        custom_match=lambda d: d.idVendor == devinfo.ID_VENDOR,
                        idProduct=1))), 1)
Ejemplo n.º 25
0
    def test_find(self):
        b = _MyBackend()
        self.assertEqual(find(backend=b, idVendor=1), None)
        self.assertNotEqual(find(backend=b, idProduct=1), None)
        self.assertEqual(len(find(find_all=True, backend=b)), len(b.devices))
        self.assertEqual(len(find(find_all=True, backend=b, idProduct=1)), 1)
        self.assertEqual(len(find(find_all=True, backend=b, idVendor=1)), 0)

        self.assertEqual(
                len(
                    find(
                        find_all=True,
                        backend=b,
                        custom_match = lambda d: d.idProduct==1
                    ),
                ),
                1
            )

        self.assertEqual(
                len(
                    find(
                        find_all=True,
                        backend=b,
                        custom_match = lambda d: d.idVendor==devinfo.ID_VENDOR,
                        idProduct=1
                    ),
                ),
                1
            )
Ejemplo n.º 26
0
    def __init__(self):
        # Connection to OWI Robotic Arm is established
        self.OWIArmUsbDevice = usbdev.find(idVendor=vendor, idProduct=product)
        if not self.OWIArmUsbDevice:
            raise ValueError("Could not connect to OWI Robotic Arm.")
        self.OWIArmUsbDevice.set_configuration()

        # Initialize motors and light bulb to be in idle/resting state
        self.stopMotion()
Ejemplo n.º 27
0
    def checkcams(self):
        self.devnums={"RGBtop":-1,"RGBside":-1,"Depth":-1}
        self.videonodes={"RGBtop":-1,"RGBside":-1,"Depth":-1}
        self.sidepresent=False
        self.toppresent=False
        self.depthpresent=False
        rgbdev=list(usbcore.find(find_all=True,idVendor=_RGBid[0],idProduct=_RGBid[1]))
        depthdev=list(usbcore.find(find_all=True,idVendor=_DEPTHid[0],idProduct=_DEPTHid[1]))
        for d in rgbdev:
            if d.port_number is _RGBTOPPORT:
                self.devnums["RGBtop"]=d.address
            elif d.port_number is _RGBSIDEPORT:
                self.devnums["RGBside"]=d.address
        for d in depthdev:
            if d.port_number is _DEPTHPORT:
                self.devnums["Depth"]=d.address
        c = pyudev.Context()
        for device in c.list_devices(subsystem='video4linux'):
            try:
                info=str(device).find("usb1")
                port=int(str(device)[info+7])
                node = int(str(device.device_node)[10:])
                if (node!=0 and (node%2==0) and (port ==_RGBTOPPORT) and (self.devnums["RGBtop"] !=-1)):
                    self.videonodes["RGBtop"]=node
                    self.toppresent=True
                elif (node!=0 and (node%2==0) and (port ==_RGBSIDEPORT) and (self.devnums["RGBside"] !=-1)):
                    self.videonodes["RGBside"] = node
                    self.sidepresent=True
            except:
                pass
        if(self.devnums["Depth"] is not -1):
            self.depthpresent=True
        else:
            self.depth_initialized=False

        if(self.devnums["RGBtop"]) is not -1:
            self.toppresent = True
        else:
            self.topinicialized = False

        if (self.devnums["RGBside"]) is not -1:
            self.sidepresent = True
        else:
            self.sideinicialized = False
Ejemplo n.º 28
0
 def findExplorerDev():
     # Get XBee Device File - for SparkFun XBee Explorer
     # This could be done less cruftily
     desc = core.find(idVendor=0x0403, idProduct=0x6015)
     if desc is None:
         return None
     snum = desc.serial_number
     prod = 'FTDI_FT231X_USB_UART'
     dev = '/dev/serial/by-id/usb-{}_{}-if00-port0'.format(prod, snum)
     return dev
Ejemplo n.º 29
0
    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))
Ejemplo n.º 30
0
    def is_ai_cam_connected(self) -> List[str]:
        """Check if camera connected

        :return: list of connected camera devices
        :rtype: String list
        """
        ai_cam_id_vendor = 0x0c45
        ai_cam_id_product = 0x6366

        dev = core.find(idVendor=ai_cam_id_vendor, idProduct=ai_cam_id_product)
        return dev
Ejemplo n.º 31
0
	def __init__(self):
		#print "Init'ing RobotArm"
		self.first = 1
		#print self.first
		self.device = usbdev.find(idVendor=VENDOR, idProduct=PRODUCT)
		if(not self.device):
			raise ValueError("Could not connect to Robotic Arm USB device. Is the arm connected properly? Perhaps you're not running as root?")
		
		self.device.set_configuration()

		self.reset()
Ejemplo n.º 32
0
def get_devices(products=(MSISPM_OLD, SISPM, MSISPM_FLASH, MSISPM_FLASH_NEW)):
    """
    Returns a generator of Gembird USB outlet devices.
    `products` defaults to a tuple of known working Gembird device identifiers.
    Override products with caution, the usb commands might destroy a wrong device.

    NOTE: You need appropriate user permissions to access the devices.
    """
    for device in find(idVendor=VENDOR, find_all=True):
        if device.idProduct in products:
            yield OutletDevice(device)
Ejemplo n.º 33
0
 def find_all(cls):
     """return all devices with this idVendor and idProduct"""
     devices = []
     try:
         for device in _usb.find(idVendor=cls.ID_VENDOR,
                                 idProduct=cls.ID_PRODUCT,
                                 find_all=True):
             devices.append(cls(device))
     except _usb.NoBackendError as err:
         raise StlinkComException("USB Error: %s" % err)
     return devices
Ejemplo n.º 34
0
def openPort(Vid, Pid, ifc):
    global dev
    # Find glove
    dev = core.find(idVendor=Vid, idProduct=Pid)
    # Return if glove isn't found
    if dev is None:
        return None
    # Claim interface
    if dev.is_kernel_driver_active(ifc) is True:
        dev.detach_kernel_driver(ifc)
    util.claim_interface(dev, ifc)
    return 0
Ejemplo n.º 35
0
    def _initDevice():
        """Finds a Microchip PICDEM, which is what the lightmeter identifies as,
        sadly. Not robust, but I can see no better way."""
        lightmeterParams = {
            'idVendor': 0x04d8,
            'idProduct': 0xfcb7,
            'configuration': 1,
            'interface': (0, 0),
            'reqLen': 64
        }

        # find our device
        dev = usb.find(idVendor=lightmeterParams['idVendor'],
                       idProduct=lightmeterParams['idProduct'])

        # was it found?
        if dev is None:
            raise RuntimeError('Device not found')

        # set the active configuration. With no arguments, the first
        # configuration will be the active one
        try:
            dev.set_configuration(lightmeterParams['configuration'])
        except usb.USBError as e:
            # if there are permission problems, this is where they manifest;
            # attach the bus and address so that outer code can print an
            # informative message.
            e.bus = dev.bus
            e.address = dev.address
            raise e

        # get an endpoint instance
        cfg = dev.get_active_configuration()
        intf = cfg[lightmeterParams['interface']]

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

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

        if endpointOut is None or endpointIn is None:
            raise RuntimeError('Unable to open endpoints')

        return endpointIn, endpointOut
Ejemplo n.º 36
0
 def enumerate_picoprobes(cls, uid=None) -> List["PicoLink"]:
     """! @brief Find and return all Picoprobes """
     try:
         # Use a custom matcher to make sure the probe is a Picoprobe and accessible.
         return [
             PicoLink(probe)
             for probe in core.find(find_all=True,
                                    custom_match=FindPicoprobe(uid))
         ]
     except core.NoBackendError:
         show_no_libusb_warning()
         return []
Ejemplo n.º 37
0
def selectDevice():
    devices = [d for d in usb.find(find_all=True)
               if d.bDeviceClass in {0, 2, 0xff}]

    if not devices:
        print("No devices detected")
        return None

    selection = -1
    selected = False

    print("PyUSB VCP Terminal: use ctrl+c or ctrl+d to exit")
    while not selected:
        for i, d in enumerate(devices):
            try:
                manufacturer = d.manufacturer + " "
            except:
                manufacturer = "Unknown"
            try:
                prod = d.product + " "
            except:
                prod = ""
            try:
                serial = d.serial_number + " "
            except:
                serial = ""

            print(
                "%d: %04x:%04x on Bus %03d %03d %s%s%s" %
                (i,
                 d.idVendor,
                 d.idProduct,
                 d.bus,
                 d.address,
                 manufacturer,
                 prod,
                 serial))

        selection = input("Enter device: ")

        try:
            selection = int(selection)
            if selection < 0 or selection >= len(devices):
                raise Exception()
            selected = True
        except:
            print(
                "Please enter number between 0 and {}".format(
                    len(devices) - 1))

    d = devices[selection]

    return d
Ejemplo n.º 38
0
def get_device_handle():
    dev = core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
    if dev is None:
        raise SystemError("Device not found!")

    interface = 0  # HID

    # Free red button from kernel driver
    # This does not work on OSX
    if dev.is_kernel_driver_active(interface) is True:
        dev.detach_kernel_driver(interface)
        util.claim_interface(dev, interface)
        kernel_was_attached = True

    return dev
Ejemplo n.º 39
0
	def update(self):
		"""
		updates pendrive list if, for example
		a new pendrive is entered
		"""	
		self.__pen_list = []
		devices = core.find(find_all=True, bDeviceClass=0)	
		for device in devices:
			cfg = device.get_active_configuration()
			interface_class = cfg[(0,0)].bInterfaceClass
        		if interface_class == 8:
				name = self.__getName(device)
				ID = self.__getDeviceID(device)
				usbDevice = USBDevice(device,name,ID)
				self.__pen_list.append(usbDevice)
Ejemplo n.º 40
0
def isPassthroughUsbDevice(interfaceClass, idP, idV):              
        for dev in core.find(find_all=True):
            for cfg in dev:
                intf = util.find_descriptor(cfg, bInterfaceClass=interfaceClass)
                if intf is not None:
                    idVendor = str(hex(dev.idVendor))
                    if len(idVendor) < 6:
                        idVendor = '0x' + '0' * (6 - len(idVendor)) + idVendor[2:]
                     
                    idProduct = str(hex(dev.idProduct))
                    if len(idProduct) < 6:
                        idProduct = '0x' + '0' * (6 - len(idProduct)) + idProduct[2:]

                    if idVendor !=None and idProduct != None and idVendor == idV and idProduct == idP:
                        return True

        return False
Ejemplo n.º 41
0
def selectDevice( ):
  devices = list( usb.find( find_all=True ) )

  if len( devices ) == 0:
    print( "No devices detected" )
    return None

  selection = -1
  selected = False

  print( "PyUSB VCP Terminal: use ctrl+c or ctrl+d to exit" )
  while not selected:
    for i,d in enumerate( devices ):
      try:
        manufacturer = d.manufacturer
      except:
        manufacturer = "Unknown"
      print( "%d: %04x:%04x on Bus %03d Address %03d %s" % (i, d.idVendor,
        d.idProduct, d.bus, d.address, manufacturer) )

    selection = input( "Enter device: " )

    try:
      selection = int( selection )
      if selection < 0 or selection >= len(devices):
        raise Exception()
      selected = True
    except:
      print( "Please enter number between 0 and {}".format(len(devices) - 1) )

  #try:
  d = devices[selection]
  #except Exception as e:
  #  log.error("Cannot open com port for {}".format(str(d)))
  #  print(str(e))
  #  exit()

  return d
Ejemplo n.º 42
0
def lsdetect(color='ffffff', log_level='info', verbosity='simple'):
    """
    Alienware detection tool for the masses.

    Use this to find out your led addresses.
    """
    set_log_level(log_level)
    set_log_formatter(verbosity)

    try:
        machine = get_machine()
        logger.info('Detected %s', machine['name'])
        device = machine['device']
        product_id = machine['uid']
    except EnvironmentError:
        logger.info('Cannot find machine')
        product_id = None
        while product_id is None:
            try:
                product_id = int(read_input('Product ID (ex: 0x0525): '), 16)
            except ValueError:
                pass
            except KeyboardInterrupt:
                logger.info('kthxbye')
                return SUCCESS
        device = find(idVendor=VENDOR_ID, idProduct=product_id)
        if device is None:
            return log_error_code(ERROR_DEVICE_NOT_FOUND)

    try:
        # This is the first step, we need to take control of the detected
        # device. We try really hard to connect, should be safe in most
        # situations for most machines.
        connect(device)
    except USBError:
        logger.error('Cannot take over device')
        return log_error_code(ERROR_DEVICE_CANNOT_TAKE_OVER)

    try:
        wait_ok(device)
    except USBError:
        return log_error_code(ERROR_DEVICE_TIMEOUT)

    idx = 0
    print ('Shutting down all leds, remember to use your touchpad '
           'so you can acknowledge when its lights turns on.')
    try:
        cmd_reset(device, RESET_ALL_LIGHTS_OFF)
        wait_ok(device)
        cmd_reset(device, RESET_ALL_LIGHTS_ON)
    except USBError:
        return log_error_code(ERROR_DEVICE_TIMEOUT)

    machine_name = read_input("Machine name: ")
    mode_version = 'MODE_VERSION_1'
    try:
        color = parse_color(color)
        idx = 0
        detected = []
        for address in LEDS_TO_SCAN:
            logger.info('Trying led 0x%.4x', address)
            try:
                wait_ok(device)
                cmd_set_color(device, idx, address, color)
                cmd_end_loop(device)
                cmd_transmit_execute(device)
            except USBError:
                return log_error_code(ERROR_DEVICE_TIMEOUT)
            changed = y_or_n('Did some led turned on? (y/[n]): ')
            if changed:
                name = read_input('Describe it (ex: Middle Left Keyboard)?: ')
                idx += 1
                detected.append((address, name))
        if not y_or_n('Does your machine use leds when sleeping on battery? '
                      '[Newer Alienware devices don\'t. '
                      'Answer "n" if you are not sure] (y/[n]): '):
            mode_version = 'MODE_VERSION_2'
    except KeyboardInterrupt:
        print ('')
    finally:
        print ('')
        print ('# Autogenerated machine definition:')
        print ('defmachine(0x%.4x, "%s", ( ' % (product_id, machine_name))
        for zone in detected:
            address, name = zone
            print ('    defzone(0x%.4x, "%s"),' % (address, name))
        print ('), %s)' % mode_version)
    return SUCCESS
Ejemplo n.º 43
0
 def createMicro(cls):
     snum = core.find(idVendor=0x1ffb, idProduct=0x0089).serial_number
     prod = 'Pololu_Corporation_Pololu_Micro_Maestro_6-Servo_Controller'
     # if00 is command port, if02 control port
     dev = '/dev/serial/by-id/usb-{}_{}-if00'.format(prod, snum)
     return cls(dev)
Ejemplo n.º 44
0
 def __init__(self):
     self.dirname = ''
     self.location = 0
     self.devices = [Device(d) for d in core.find(find_all=True)]
Ejemplo n.º 45
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from usb.core import find
import usb.control


def is_mass_storage(dev):
    import usb.util
    for cfg in dev:
        if usb.util.find_descriptor(cfg, bInterfaceClass=8) is not None:
            return True


for mass in find(find_all=True, custom_match=is_mass_storage):
    print(mass)
Ejemplo n.º 46
0
def busses():
    r"""Returns a tuple with the usb busses."""
    return (Bus(g) for k, g in groupby(
            sorted(core.find(find_all=True), key=lambda d: d.bus),
            lambda d: d.bus))