Esempio n. 1
0
def get_sense(handle, endpoint_in, endpoint_out):

    # Request Sense
    print("Request Sense:")
    sense = (ct.c_uint8 * 18)()
    cdb   = (ct.c_uint8 * 16)()  # SCSI Command Descriptor Block
    cdb[0] = 0x03  # Request Sense
    cdb[4] = REQUEST_SENSE_LENGTH

    expected_tag = ct.c_uint32()
    send_mass_storage_command(handle, endpoint_out, 0, cdb, usb.LIBUSB_ENDPOINT_IN, REQUEST_SENSE_LENGTH, ct.pointer(expected_tag))
    size = ct.c_int()
    rc = usb.bulk_transfer(handle, endpoint_in, ct.cast(ct.pointer(sense), ct.POINTER(ct.c_ubyte)), REQUEST_SENSE_LENGTH, ct.byref(size), 1000)
    if rc < 0:
        print("usb.bulk_transfer failed: {}".format(usb.error_name(rc)))
        return

    size = size.value
    print("   received {} bytes".format(size))

    if sense[0] != 0x70 and sense[0] != 0x71:
        perr("   ERROR No sense data\n")
    else:
        perr("   ERROR Sense: {:02X} {:02X} {:02X}\n",
             sense[2] & 0x0F, sense[12], sense[13])

    # Strictly speaking, the get_mass_storage_status() call should come
    # before these perr() lines.  If the status is nonzero then we must
    # assume there's no data in the buffer.  For xusb it doesn't matter.
    get_mass_storage_status(handle, endpoint_in, expected_tag)
Esempio n. 2
0
def ezusb_cpucs(device, addr, do_run):

    global verbose

    data = ct.c_uint8(0x00 if do_run else 0x01)

    if verbose:
        logerror("{}\n", "stop CPU" if data else "reset CPU")
    status = usb.control_transfer(device,
                                  usb.LIBUSB_ENDPOINT_OUT |
                                  usb.LIBUSB_REQUEST_TYPE_VENDOR |
                                  usb.LIBUSB_RECIPIENT_DEVICE,
                                  RW_INTERNAL,
                                  addr & 0xFFFF, addr >> 16,
                                  ct.byref(data), 1,
                                  1000);
    if (status != 1 and
        # We may get an I/O error from libusb as the device disappears
        (not do_run or status != usb.LIBUSB_ERROR_IO)):
        mesg = "can't modify CPUCS"
        if status < 0:
            logerror("{}: {}\n", mesg, usb.error_name(status))
        else:
            logerror("{}\n", mesg)
        return False
    else:
        return True
Esempio n. 3
0
def main(argv=sys.argv):

    global handle, done

    hp = [usb.hotplug_callback_handle() for i in range(2)]

    vendor_id = int(argv[1]) if len(argv) > 1 else 0x045a
    product_id = int(argv[2]) if len(argv) > 2 else 0x5005
    class_id = int(argv[3]) if len(argv) > 3 else usb.LIBUSB_HOTPLUG_MATCH_ANY

    rc = usb.init(None)
    if rc < 0:
        print("failed to initialise libusb: {}".format(usb.error_name(rc)))
        return 1

    try:
        if not usb.has_capability(usb.LIBUSB_CAP_HAS_HOTPLUG):
            print("Hotplug capabilites are not supported on this platform")
            return 1

        rc = usb.hotplug_register_callback(
            None, usb.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED, 0, vendor_id,
            product_id, class_id, hotplug_callback, None, ct.byref(hp[0]))
        if rc != usb.LIBUSB_SUCCESS:
            print("Error registering callback 0", file=sys.stderr)
            return 1

        rc = usb.hotplug_register_callback(
            None, usb.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0,
            vendor_id, product_id, class_id, hotplug_callback_detach, None,
            ct.byref(hp[1]))
        if rc != usb.LIBUSB_SUCCESS:
            print("Error registering callback 1", file=sys.stderr)
            return 1

        while done < 2:
            rc = usb.handle_events(None)
            if rc < 0:
                print("libusb.handle_events() failed: {}".format(
                    usb.error_name(rc)))
    finally:
        if handle:
            usb.close(handle)
        usb.exit(None)

    return 0
Esempio n. 4
0
def main():

    global devh
    global VID, PID
    global do_exit

    #sigact = struct_sigaction()
    #sigact.sa_handler = sig_hdlr
    #sigemptyset(ct.byref(sigact.sa_mask))
    #sigact.sa_flags = 0
    signal.signal(signal.SIGINT, sig_hdlr)

    rc = usb.init(None)
    if rc < 0:
        print("Error initializing libusb: {}".format(usb.error_name(rc)),
              file=sys.stderr)
        sys.exit(1)

    try:
        devh = usb.open_device_with_vid_pid(None, VID, PID)
        if not devh:
            print("Error finding USB device", file=sys.stderr)
            return rc

        rc = usb.claim_interface(devh, 2)
        if rc < 0:
            print("Error claiming interface: {}".format(usb.error_name(rc)),
                  file=sys.stderr)
            return rc

        benchmark_in(EP_ISO_IN)

        while not do_exit:
            rc = usb.handle_events(None)
            if rc != usb.LIBUSB_SUCCESS:
                break

        # Measurement has already been done by the signal handler.

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

    return rc
Esempio n. 5
0
def ezusb_read(device, label, opcode, addr, data, size):

    global verbose

    if verbose > 1:
        logerror("{}, addr {:#010x} len %4u ({:#06x})\n", label, addr, size,
                 size)
    status = usb.control_transfer(
        device, usb.LIBUSB_ENDPOINT_IN | usb.LIBUSB_REQUEST_TYPE_VENDOR
        | usb.LIBUSB_RECIPIENT_DEVICE, opcode, addr & 0xFFFF, addr >> 16,
        ct.cast(data, ct.POINTER(ct.c_ubyte)), ct.c_uint16(size), 1000)
    if status != ct.c_int(size).value:
        if status < 0:
            logerror("{}: {}\n", label, usb.error_name(status))
        else:
            logerror("{} ==> {}\n", label, status)

    return 0 if status >= 0 else -errno.EIO
Esempio n. 6
0
def ezusb_fx3_jump(device, addr):

    global verbose

    if verbose:
        logerror("transfer execution to Program Entry at {:#010x}\n", addr)
    status = usb.control_transfer(
        device, usb.LIBUSB_ENDPOINT_OUT | usb.LIBUSB_REQUEST_TYPE_VENDOR
        | usb.LIBUSB_RECIPIENT_DEVICE, RW_INTERNAL, addr & 0xFFFF, addr >> 16,
        NULL, 0, 1000)
    # We may get an I/O error from libusb as the device disappears
    if status != 0 and status != usb.LIBUSB_ERROR_IO:
        mesg = "failed to send jump command"
        if status < 0:
            logerror("{}: {}\n", mesg, usb.error_name(status))
        else:
            logerror("{}\n", mesg)
        return False
    else:
        return True
Esempio n. 7
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