Example #1
0
    def get_usb_devices(self):
        """Scan for USB devices"""

        devlist = []

        try:
            # Connect to device (attempt #1)
            dev = list(
                usb.core.find(find_all=True,
                              idVendor=0x2B3E,
                              backend=libusb0.get_backend()))
        except usb.core.NoBackendError:
            try:
                # An error in the previous one is often caused by Windows 64-bit not detecting the correct library, attempt to force this with paths
                # that often work so user isn't aware
                dev = list(
                    usb.core.find(find_all=True,
                                  idVendor=0x2B3E,
                                  backend=libusb0.get_backend(
                                      find_library=lambda x:
                                      r"c:\Windows\System32\libusb0.dll")))
            except usb.core.NoBackendError:
                raise IOError(
                    "Failed to find USB backend. Check libusb drivers installed, check for path issues on library, and check for 32 vs 64-bit issues."
                )
        # Found something
        if len(dev) > 0:
            devlist.extend(dev)

        return devlist
Example #2
0
    def get_possible_devices(self, idProduct):
        """
        Get a list of matching devices being based a list of PIDs. Returns list of usbdev that match (or empty if none)
        """

        devlist = []

        for id in idProduct:
            try:
                # Connect to device (attempt #1)
                dev = list(
                    usb.core.find(find_all=True,
                                  idVendor=0x2B3E,
                                  idProduct=id,
                                  backend=libusb0.get_backend()))
            except usb.core.NoBackendError:
                try:
                    # An error in the previous one is often caused by Windows 64-bit not detecting the correct library, attempt to force this with paths
                    # that often work so user isn't aware
                    dev = list(
                        usb.core.find(find_all=True,
                                      idVendor=0x2B3E,
                                      idProduct=id,
                                      backend=libusb0.get_backend(
                                          find_library=lambda x:
                                          r"c:\Windows\System32\libusb0.dll")))
                except usb.core.NoBackendError:
                    raise IOError(
                        "Failed to find USB backend. Check libusb drivers installed, check for path issues on library, and check for 32 vs 64-bit issues."
                    )
            # Found something
            if len(dev) > 0:
                devlist.extend(dev)

        return devlist
Example #3
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)
        """

        devlist = []

        if idProduct is None:
            idProduct = [None]

        libusb_backend = libusb0.get_backend()
        for _ in range(2):  #1 try for each backend
            try:
                for id in idProduct:
                    if id:
                        dev = list(
                            usb.core.find(find_all=True,
                                          idVendor=0x2B3E,
                                          idProduct=id,
                                          backend=libusb_backend))
                    else:
                        dev = list(
                            usb.core.find(find_all=True,
                                          idVendor=0x2B3E,
                                          backend=libusb_backend))
                    if len(dev) > 0:
                        devlist.extend(dev)
                if dictonly:
                    devlist = [{
                        'sn': d.serial_number,
                        'product': d.product,
                        'pid': d.idProduct,
                        'vid': d.idVendor
                    } for d in devlist]

                return devlist
            except (usb.core.NoBackendError, ValueError):
                # An error in the previous find is often caused by Windows 64-bit not detecting the correct library, attempt to force this with paths
                # that often work so user isn't aware
                #from usb.backend import libusb0
                libusb_backend = libusb0.get_backend(
                    find_library=lambda x: r"c:\Windows\System32\libusb0.dll")
                devlist = []
                continue

        raise IOError(
            "Failed to find USB backend. Check libusb drivers installed, check for path issues on library, and check for 32 vs 64-bit issues."
        )
Example #4
0
def _find_devices():
    """
    Returns a list of CrazyRadio devices currently connected to the computer
    """
    ret = []

    logger.info('Looking for devices....')

    if os.name == 'nt':
        import usb.backend.libusb0 as libusb0

        backend = libusb0.get_backend()
    else:
        backend = libusb_package.get_libusb1_backend()

    devices = usb.core.find(idVendor=USB_VID,
                            idProduct=USB_PID,
                            find_all=1,
                            backend=backend)
    if devices:
        for d in devices:
            if d.manufacturer == 'Bitcraze AB':
                ret.append(d)

    return ret
Example #5
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."
            )
Example #6
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)
Example #7
0
def init(idVendor=0xcafe, idProduct=0x0001):
    # set environment
    environ['PYUSB_DEBUG'] = 'debug'
    # find our device
    be = libusb0.get_backend()
    _dev = usb.core.find(idVendor=idVendor, idProduct=idProduct, backend=be)
    # was it found?
    if _dev is None:
        raise ValueError('Device not found')
    return _dev
Example #8
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=libusb0.get_backend(),
     )
     if gs_usb:
         return GsUsb(gs_usb)
     return None
Example #9
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=libusb0.get_backend(),
         )
     ]
Example #10
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={}
        if os.name == "nt":
            #on windows, need to manually load libusb because of 64bit python loading the wrong one
            libusb_backend = libusb0.get_backend(find_library=lambda x: r"c:\Windows\System32\libusb0.dll")
            my_kwargs = {'backend': libusb_backend}
        devlist = []
        try:
            for id in idProduct:
                if id:
                    dev = list(usb.core.find(find_all=True, idVendor=0x2B3E, idProduct=id, **my_kwargs))
                else:
                    dev = list(usb.core.find(find_all=True, idVendor=0x2B3E, **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("'This device has no langid' ValueError caught. This is usually caused by us trying to read the serial number of the chipwhisperer, but it failing. The device is here and we can see it, but we can't access it. This has a number of root causes, including:\n" +
                        "-Not having permission to access the ChipWhisperer (this still crops up if you have permission for one ChipWhisperer, but another ChipWhisperer is connected that you don't have access to)\n" +
                        "-Not having the correct libusb backend loaded (common on Windows with 64bit Python). We try to handle this by loading the correct backend on Windows"
                        )
Example #11
0
    def connect(self):
        '''Establishes a read/write connection to the 1st Pipsta found on the USB
        bus.
        '''

        # Find the Pipsta's specific Vendor ID and Product ID (also known as vid
        # and pid)
        dev = usb.core.find(idVendor=PIPSTA_USB_VENDOR_ID,
                            idProduct=PIPSTA_USB_PRODUCT_ID,
                            backend=libusb0.get_backend())
        if dev is None:                 # if no such device is connected...
            raise IOError('Printer not found')  # ...report error

        try:
            if platform.system() == 'Linux':
                dev.reset()

            # Initialisation. Passing no arguments sets the configuration to the
            # currently active configuration.
            dev.set_configuration()
        except usb.core.USBError as ex:
            raise IOError('Failed to configure the printer', ex)
        except AttributeError as ex:
            raise IOError('Failed to configure the printer')

        cfg = dev.get_active_configuration()  # Get a handle to the active interface

        interface_number = cfg[(0, 0)].bInterfaceNumber
        usb.util.claim_interface(dev, interface_number)
        alternate_setting = usb.control.get_interface(dev, interface_number)
        intf = usb.util.find_descriptor(
            cfg, bInterfaceNumber=interface_number,
            bAlternateSetting=alternate_setting)

        self.ep_out = usb.util.find_descriptor(
            intf,
            custom_match=lambda e:
            usb.util.endpoint_direction(e.bEndpointAddress) ==
            usb.util.ENDPOINT_OUT
        )

        self.ep_in = usb.util.find_descriptor(
            intf,
            custom_match=lambda e:
            usb.util.endpoint_direction(e.bEndpointAddress) ==
            usb.util.ENDPOINT_IN
        )
Example #12
0
    def __init__(self, name, config, config_filepath):
        # TODO: Support multiple monos on the same machine
        super().__init__(name, config, config_filepath)
        try:
            from usb.backend import libusb0  # type: ignore

            backend = libusb0.get_backend()
        except:
            # Fall back on default behavior if _anything_ goes wrong with specifing libusb0
            backend = None
        self._dev = usb.core.find(idVendor=JOBIN_YVON_ID_VENDOR,
                                  idProduct=IHR320_ID_PRODUCT,
                                  backend=backend)

        self._busy = True

        # Lie to the device that it speaks US English
        # Without this, the strings read from USB don't work
        self._dev._langids = (LANG_ID_US_ENGLISH, )
        self.description = ""  #self._dev.product
        self.serial = ""  #self._dev.serial_number
        self._gratings = config["gratings"]
        self._units = "nm"

        try:
            turret_i = loadtxt(
                "C:/Users/gabri/anaconda3/Lib/site-packages/yaqd_horiba/turret.txt",
                unpack=True)
        except:
            print(
                "Manually check what is the ihr320's current grating;\n insert 0 for the 600 grooves/mm grating,\n 1 for the 150 grooves/mm grating or\n 2 for the 120 grooves/mm grating"
            )
            turret_i = input("Grating index: ")
            my_file = open(
                "C:/Users/gabri/anaconda3/Lib/site-packages/yaqd_horiba/turret.txt",
                "w")
            my_file.write(f'{turret_i}')
            my_file.close()

        self._state["turret"] = list(self._gratings.keys())[int(turret_i)]

        self.home()

        self.set_position(100)
        self.set_front_entrance_slit(1)
        self.set_front_exit_slit(1)
Example #13
0
def _find_devices(serial=None):
    """
    Returns a list of CrazyRadio devices currently connected to the computer
    """
    ret = []

    if os.name == 'nt':
        import usb.backend.libusb0 as libusb0

        backend = libusb0.get_backend()
    else:
        backend = libusb_package.get_libusb1_backend()

    devices = usb.core.find(idVendor=0x1915,
                            idProduct=0x7777,
                            find_all=1,
                            backend=backend)
    if devices:
        for d in devices:
            if serial is not None and serial == d.serial_number:
                return d
            ret.append(d)

    return ret
Example #14
0
SET_RADIO_POWER = 0x04
SET_RADIO_ARD = 0x05
SET_RADIO_ARC = 0x06
ACK_ENABLE = 0x10
SET_CONT_CARRIER = 0x20
SCANN_CHANNELS = 0x21
LAUNCH_BOOTLOADER = 0xFF

try:
    import usb.core

    pyusb_backend = None
    if os.name == 'nt':
        import usb.backend.libusb0 as libusb0

        pyusb_backend = libusb0.get_backend()
    pyusb1 = True
except Exception:
    pyusb1 = False


def _find_devices(serial=None):
    """
    Returns a list of CrazyRadio devices currently connected to the computer
    """
    ret = []

    if pyusb1:
        for d in usb.core.find(idVendor=0x1915,
                               idProduct=0x7777,
                               find_all=1,
Example #15
0
import sys
import time
import array
import binascii

logger = logging.getLogger(__name__)

USB_VID = 0x0483
USB_PID = 0x5740

try:
    import usb.core
    pyusb_backend = None
    if os.name == "nt":
        import usb.backend.libusb0 as libusb0
        pyusb_backend = libusb0.get_backend()
    pyusb1 = True
except:
    pyusb1 = False


def _find_devices():
    """
    Returns a list of CrazyRadio devices currently connected to the computer
    """
    ret = []

    logger.info("Looking for devices....")

    if pyusb1:
        for d in usb.core.find(idVendor=USB_VID, idProduct=USB_PID, find_all=1, backend=pyusb_backend):
Example #16
0
    def con(self, idProduct=[0xACE2]):
        """
        Connect to device using default VID/PID
        """

        for id in idProduct:
            try:
                # Connect to device (attempt #1)
                dev = usb.core.find(idVendor=0x2B3E, idProduct=id, backend=libusb0.get_backend())
            except usb.core.NoBackendError:
                try:
                    # An error in the previous one is often caused by Windows 64-bit not detecting the correct library, attempt to force this with paths
                    # that often work so user isn't aware
                    dev = usb.core.find(idVendor=0x2B3E, idProduct=id, backend=libusb0.get_backend(find_library=lambda x: r"c:\Windows\System32\libusb0.dll"))
                except usb.core.NoBackendError:
                    raise IOError("Failed to find USB backend. Check libusb drivers installed, check for path issues on library, and check for 32 vs 64-bit issues.")

            foundId = id

            #Found something
            if dev:
                break

        if not dev:
            raise Warning("Failed to find USB Device")

        try:
            dev.set_configuration()
        except ValueError:
            raise IOError("NAEUSB: Could not configure USB device")

        # Get serial number
        try:
            # New calling syntax
            self.snum = usb.util.get_string(dev, index=3)

        except TypeError:
            # Old calling syntax
            self.snum = usb.util.get_string(dev, length=256, index=3)


        if foundId in NEWAE_PIDS:
            name = NEWAE_PIDS[foundId]['name']
            fw_latest = NEWAE_PIDS[foundId]['fwver']
        else:
            name = "Unknown (PID = %04x)"%foundId

        logging.info('Found %s, Serial Number = %s' % (name, self.snum))

        self._usbdev = dev
        self.rep = 0x81
        self.wep = 0x02
        self._timeout = 200

        fwver = self.readFwVersion()
        logging.info('SAM3U Firmware version = %d.%d b%d' % (fwver[0], fwver[1], fwver[2]))

        latest = fwver[0] > fw_latest[0] or (fwver[0] == fw_latest[0] and fwver[1] >= fw_latest[1])
        if not latest:
            logging.warning('Your firmware is outdated - latest is %d.%d' % (fw_latest[0], fw_latest[1]) +
                            '. Suggested to update firmware, as you may experience errors')

        return foundId