Beispiel #1
0
def main():
    usage = 'Usage: python3 {} [-d] VID:PID'.format(sys.argv[0])
    argc = len(sys.argv)
    if 2 > argc or argc > 3:
        print(usage)
        sys.exit(1)
    if 3 == argc:
        if sys.argv[1] != '-d':
            print(usage)
            sys.exit(1)

        os.environ["LIBUSB_DEBUG"] = "4"  # usb.LIBUSB_LOG_LEVEL_DEBUG

    if sys.argv[-1].find(':') < 0:
        print('Invalid VID & PID')
        print(usage)
        sys.exit(1)

    ids = sys.argv[-1].split(':')
    vid = int(ids[0], 16)
    pid = int(ids[1], 16)

    version = usb.get_version()[0]
    print("Using libusb v{}.{}.{}.{}".format(version.major, version.minor,
                                             version.micro, version.nano))
    r = usb.init(None)
    if r < 0:
        sys.exit(r)

    try:
        usb.set_option(None, usb.LIBUSB_OPTION_LOG_LEVEL,
                       usb.LIBUSB_LOG_LEVEL_INFO)
        test_device(vid, pid)
    finally:
        usb.exit(None)
Beispiel #2
0
def test_default_context_change(tctx):

    # Tests that the default context (used for various things including
    # logging) works correctly when the first context created in a
    # process is destroyed.

    ctx = ct.POINTER(usb.context)()
    for i in range(100):

        # First create a new context
        r = usb.init(ct.byref(ctx))
        if r != usb.LIBUSB_SUCCESS:
            testlib.logf(tctx, "Failed to init libusb: {:d}", r)
            return test_result.TEST_STATUS_FAILURE

        # Enable debug output, to be sure to use the context
        usb.set_option(None, usb.LIBUSB_OPTION_LOG_LEVEL, usb.LIBUSB_LOG_LEVEL_DEBUG)
        usb.set_option(ctx,  usb.LIBUSB_OPTION_LOG_LEVEL, usb.LIBUSB_LOG_LEVEL_DEBUG)

        # Now create a reference to the default context
        r = usb.init(None)
        if r != usb.LIBUSB_SUCCESS:
            testlib.logf(tctx, "Failed to init libusb: {:d}", r)
            return test_result.TEST_STATUS_FAILURE

        # Destroy the first context
        usb.exit(ctx)
        # Destroy the default context
        usb.exit(None)

    return test_result.TEST_STATUS_SUCCESS
Beispiel #3
0
def main(argv=sys.argv):

    global verbose

    FIRMWARE = 0
    LOADER = 1
    known_devices = FX_KNOWN_DEVICES

    paths = [None, None]  # [const char*]
    device_id = None  # const char*
    device_path = os.environ.get("DEVICE", None)
    target_type = None  # const char*
    fx_names = FX_TYPE_NAMES
    img_names = IMG_TYPE_NAMES
    fx_type = FX_TYPE_UNDEFINED  # int
    img_types = [0] * len(paths)  # [int]
    #opt;          # int
    #status;       # int
    #ext;          # const char*
    #i, j;         # unsigned int
    vid = 0  # unsigned
    pid = 0  # unsigned
    busnum = 0  # unsigned
    devaddr = 0  # unsigned
    #_busnum;      # unsigned
    #_devaddr;     # unsigned
    dev = ct.POINTER(usb.device)()
    devs = ct.POINTER(ct.POINTER(usb.device))()
    device = ct.POINTER(usb.device_handle)()
    desc = usb.device_descriptor()

    try:
        opts, args = getopt.getopt(argv[1:], "qvV?hd:p:i:I:s:S:t:")
    except getopt.GetoptError:
        return print_usage(-1)

    for opt, optarg in opts:
        if opt == "-d":
            device_id = optarg
            if sscanf(device_id, "%x:%x", ct.byref(vid), ct.byref(pid)) != 2:
                print(
                    "please specify VID & PID as \"vid:pid\" in hexadecimal format",
                    file=sys.stderr)
                return -1
        elif opt == "-p":
            device_path = optarg
            if sscanf(device_path, "%u,%u", ct.byref(busnum),
                      ct.byref(devaddr)) != 2:
                print(
                    "please specify bus number & device number as \"bus,dev\" in decimal format",
                    file=sys.stderr)
                return -1
        elif opt in ("-i", "-I"):
            paths[FIRMWARE] = optarg
        elif opt in ("-s", "-S"):
            paths[LOADER] = optarg
        elif opt == "-V":
            print(FXLOAD_VERSION)
            return 0
        elif opt == "-t":
            target_type = optarg
        elif opt == "-v":
            verbose += 1
        elif opt == "-q":
            verbose -= 1
        elif opt in ("-?", "-h"):
            return print_usage(-1)
        else:
            return print_usage(-1)

    if paths[FIRMWARE] is None:
        logerror("no firmware specified!\n")
        return print_usage(-1)

    if device_id is not None and device_path is not None:
        logerror("only one of -d or -p can be specified\n")
        return print_usage(-1)

    # determine the target type
    if target_type is not None:
        for i in range(FX_TYPE_MAX):
            if fx_names[i] == target_type:
                fx_type = i
                break
        else:
            logerror("illegal microcontroller type: {}\n", target_type)
            return print_usage(-1)

    # open the device using libusb
    status = usb.init(None)
    if status < 0:
        logerror("usb.init() failed: {}\n", usb.error_name(status))
        return -1

    try:
        usb.set_option(None, usb.LIBUSB_OPTION_LOG_LEVEL, verbose)

        # try to pick up missing parameters from known devices
        if target_type is None or device_id is None or device_path is not None:

            if usb.get_device_list(None, ct.byref(devs)) < 0:
                logerror("libusb.get_device_list() failed: {}\n",
                         usb.error_name(status))
                return -1

            i = 0
            while True:
                dev = devs[i]
                if not dev:
                    usb.free_device_list(devs, 1)
                    logerror(
                        "could not find a known device - please specify type and/or vid:pid and/or bus,dev\n"
                    )
                    return print_usage(-1)

                _busnum = usb.get_bus_number(dev)
                _devaddr = usb.get_device_address(dev)
                if target_type is not None and device_path is not None:
                    # if both a type and bus,addr were specified, we just need to find our match
                    if (usb.get_bus_number(dev) == busnum
                            and usb.get_device_address(dev) == devaddr):
                        break
                else:
                    status = usb.get_device_descriptor(dev, ct.byref(desc))
                    if status >= 0:

                        if verbose >= 3:
                            logerror("examining {:04x}:{:04x} ({},{})\n",
                                     desc.idVendor, desc.idProduct, _busnum,
                                     _devaddr)

                        if_break = False
                        for known_device in known_devices:
                            if (desc.idVendor == known_device.vid
                                    and desc.idProduct == known_device.pid):
                                if (  # nothing was specified
                                    (target_type is None and device_id is None
                                     and device_path is None) or
                                        # vid:pid was specified and we have a match
                                    (target_type is None
                                     and device_id is not None
                                     and vid == desc.idVendor
                                     and pid == desc.idProduct) or
                                        # bus,addr was specified and we have a match
                                    (target_type is None
                                     and device_path is not None
                                     and busnum == _busnum
                                     and devaddr == _devaddr) or
                                        # type was specified and we have a match
                                    (target_type is not None
                                     and device_id is None
                                     and device_path is None
                                     and fx_type == known_device.type)):
                                    fx_type = known_device.type
                                    vid = desc.idVendor
                                    pid = desc.idProduct
                                    busnum = _busnum
                                    devaddr = _devaddr
                                    if_break = True
                                    break
                        if if_break:
                            if verbose:
                                logerror(
                                    "found device '{}' [{:04x}:{:04x}] ({},{})\n",
                                    known_device.designation, vid, pid, busnum,
                                    devaddr)
                            break
                i += 1

            status = usb.open(dev, ct.byref(device))
            usb.free_device_list(devs, 1)
            if status < 0:
                logerror("usb.open() failed: {}\n", usb.error_name(status))
                return -1

        elif device_id is not None:

            device = usb.open_device_with_vid_pid(None, ct.c_uint16(vid),
                                                  ct.c_uint16(pid))
            if not device:
                logerror("usb.open() failed\n")
                return -1

        # We need to claim the first interface
        usb.set_auto_detach_kernel_driver(device, 1)
        status = usb.claim_interface(device, 0)
        if status != usb.LIBUSB_SUCCESS:
            usb.close(device)
            logerror("libusb.claim_interface failed: {}\n",
                     usb.error_name(status))
            return -1

        if verbose:
            logerror("microcontroller type: {}\n", fx_names[fx_type])

        for i, path in enumerate(paths):
            if path is not None:
                ext = path[-4:]
                if ext.lower() == ".hex" or ext == ".ihx":
                    img_types[i] = IMG_TYPE_HEX
                elif ext.lower() == ".iic":
                    img_types[i] = IMG_TYPE_IIC
                elif ext.lower() == ".bix":
                    img_types[i] = IMG_TYPE_BIX
                elif ext.lower() == ".img":
                    img_types[i] = IMG_TYPE_IMG
                else:
                    logerror("{} is not a recognized image type\n", path)
                    return -1
            if verbose and path is not None:
                logerror("{}: type {}\n", path, img_names[img_types[i]])

        if paths[LOADER] is None:
            # single stage, put into internal memory
            if verbose > 1:
                logerror("single stage: load on-chip memory\n")
            status = ezusb_load_ram(device, paths[FIRMWARE], fx_type,
                                    img_types[FIRMWARE], 0)
        else:
            # two-stage, put loader into internal memory
            if verbose > 1:
                logerror("1st stage: load 2nd stage loader\n")
            status = ezusb_load_ram(device, paths[LOADER], fx_type,
                                    img_types[LOADER], 0)
            if status == 0:
                # two-stage, put firmware into internal memory
                if verbose > 1:
                    logerror("2nd state: load on-chip memory\n")
                status = ezusb_load_ram(device, paths[FIRMWARE], fx_type,
                                        img_types[FIRMWARE], 1)

        usb.release_interface(device, 0)
        usb.close(device)
    finally:
        usb.exit(None)

    return status
Beispiel #4
0
def main(argv=sys.argv):

    global VID, PID
    global test_mode
    global binary_dump
    global binary_name

    show_help  = False  # bool
    debug_mode = False  # bool
    error_lang = None   # char*

    # Default to generic, expecting VID:PID
    VID = 0
    PID = 0

    test_mode = USE_GENERIC

    endian_test = ct.c_uint16(0xBE00)
    if ct.cast(ct.pointer(endian_test), ct.POINTER(ct.c_uint8))[0] == 0xBE:
        print("Despite their natural superiority for end users, big endian\n"
              "CPUs are not supported with this program, sorry.")
        return 0

   #if len(argv) >= 2:
    for j in range(1, len(argv)):
        arglen = len(argv[j])
        if argv[j][0] in ('-', '/') and arglen >= 2:
            opt = argv[j][1]
            if opt == 'd':
                debug_mode = True
            elif opt == 'i':
                extra_info = True
            elif opt == 'w':
                force_device_request = True
            elif opt == 'b':
                j += 1
                if j >= len(argv) or argv[j][0] in ('-', '/'):
                    print("   Option -b requires a file name")
                    return 1
                binary_name = argv[j]
                binary_dump = True
            elif opt == 'l':
                j += 1
                if j >= len(argv) or argv[j][0] in ('-', '/'):
                    print("   Option -l requires an ISO 639-1 language parameter")
                    return 1
                error_lang = argv[j]
            elif opt == 'j':
                # OLIMEX ARM-USB-TINY JTAG, 2 channel composite device - 2 interfaces
                if not VID and not PID:
                    VID = 0x15BA
                    PID = 0x0004
            elif opt == 'k':
                # Generic 2 GB USB Key (SCSI Transparent/Bulk Only) - 1 interface
                if not VID and not PID:
                    VID = 0x0204
                    PID = 0x6025
            # The following tests will force VID:PID if already provided
            elif opt == 'p':
                # Sony PS3 Controller - 1 interface
                VID = 0x054C
                PID = 0x0268
                test_mode = USE_PS3
            elif opt == 's':
                # Microsoft Sidewinder Precision Pro Joystick - 1 HID interface
                VID = 0x045E
                PID = 0x0008
                test_mode = USE_HID
            elif opt == 'x':
                # Microsoft XBox Controller Type S - 1 interface
                VID = 0x045E
                PID = 0x0289
                test_mode = USE_XBOX
            else:
                show_help = True
        else:
            for i in range(arglen):
                if argv[j][i] == ':':
                    tmp_vid = 0  # unsigned int
                    tmp_pid = 0  # unsigned int
                    if sscanf(argv[j], "%x:%x" , ct.pointer(tmp_vid), ct.pointer(tmp_pid)) != 2:
                        print("   Please specify VID & PID as \"vid:pid\" in hexadecimal format")
                        return 1
                    VID = ct.c_uint16(tmp_vid)
                    PID = ct.c_uint16(tmp_pid)
                    break
            else:
                show_help = True

    if show_help or len(argv) == 1 or len(argv) > 7:
        print("usage: {} [-h] [-d] [-i] [-k] [-b file] [-l lang] [-j] [-x] [-s] [-p] [-w] [vid:pid]".format(argv[0]))
        print("   -h      : display usage")
        print("   -d      : enable debug output")
        print("   -i      : print topology and speed info")
        print("   -j      : test composite FTDI based JTAG device")
        print("   -k      : test Mass Storage device")
        print("   -b file : dump Mass Storage data to file 'file'")
        print("   -p      : test Sony PS3 SixAxis controller")
        print("   -s      : test Microsoft Sidewinder Precision Pro (HID)")
        print("   -x      : test Microsoft XBox Controller Type S")
        print("   -l lang : language to report errors in (ISO 639-1)")
        print("   -w      : force the use of device requests when querying WCID descriptors")
        print("If only the vid:pid is provided, xusb attempts to run the most appropriate test")
        return 0

    # xusb is commonly used as a debug tool, so it's convenient to have debug output
    # during usb.init(), but since we can't call on usb.set_option() before usb.init(),
    # we use the env variable method
    old_dbg_str = os.environ.get("LIBUSB_DEBUG", None)
    if debug_mode:
        try:
            os.environ["LIBUSB_DEBUG"] = "4"  # usb.LIBUSB_LOG_LEVEL_DEBUG
        except:
            print("Unable to set debug level")

    version = usb.get_version()[0]
    print("Using libusb v{}.{}.{}.{}\n".format(
          version.major, version.minor, version.micro, version.nano))
    r = usb.init(None)
    if r < 0:
        return r

    try:
        # If not set externally, and no debug option was given, use info log level
        if old_dbg_str is None and not debug_mode:
            usb.set_option(None, usb.LIBUSB_OPTION_LOG_LEVEL, usb.LIBUSB_LOG_LEVEL_INFO)
        if error_lang is not None:
            r = usb.setlocale(error_lang)
            if r < 0:
                print("Invalid or unsupported locale '{}': {}".format(
                      error_lang, usb.strerror(usb.error(r))))

        test_device(VID, PID)
    finally:
        usb.exit(None)

    if debug_mode:
        #char string[256];
        string = "LIBUSB_DEBUG={}".format("" if old_dbg_str is None else old_dbg_str)

    return 0
Beispiel #5
0
from ultimarc import translate_gettext as _
from ._base import _USB_PRODUCT_CLASSES, USB_PRODUCT_DESCRIPTIONS, USBDevices, DeviceClassID
from ._device import usb_error
from ..exceptions import USBDeviceClaimInterfaceError, USBDeviceNotFoundError, \
    USBDeviceInterfaceNotClaimedError

_logger = logging.getLogger('default')

# Initialize libusb library.
_ret = usb.init(None)
if _ret < 0:
    _str = f'{_("LibUSB.init() failed with error")} {usb.error_name(_ret).decode("utf-8")} ({_ret}).'
    raise IOError(_str)
# Enable additional logging from LibUSB.
usb.set_option(None, usb.LIBUSB_OPTION_LOG_LEVEL,
               1 if '--debug' in sys.argv else 0)


def _exit():
    """ Clean up libusb on exit """
    usb.exit(None)
    _logger.debug(_('LibUSB.exit() function called successfully.'))


# Register the _exit() function to be called when program quits.
atexit.register(_exit)

__all__ = [
    _USB_PRODUCT_CLASSES, USB_PRODUCT_DESCRIPTIONS, USBDevices, usb_error,
    USBDeviceClaimInterfaceError, USBDeviceInterfaceNotClaimedError,
    USBDeviceNotFoundError, DeviceClassID