Ejemplo n.º 1
0
def get_vendor_code_from_os_string_descriptor(handle):
    print("  Reading OS String Descriptor")
    # get its length from the descriptor header
    length = 4
    desc = (c_uint8 * length)()
    request_type = usb.LIBUSB_ENDPOINT_IN
    request = 0x06  # GET_DESCRIPTOR (0x06)
    value = (0x03 << 8) | 0xEE  # STRING_DESCRIPTOR (0x03), INDEX (0xEE)
    index = 0x0000
    r = usb.control_transfer(handle, request_type, request, value, index, desc,
                             length, 1000)
    if r == length:
        length = desc[0]
        desc = (c_uint8 * length)()

        # get the full descriptor
        r = usb.control_transfer(handle, request_type, request, value, index,
                                 desc, length, 1000)
        if r == length:
            dump_hex(desc, r)
            return desc[MS_OS_DESC_VENDOR_CODE_OFFSET]

    # Another way
    # Read the OS String Descriptor at string index 0xEE
    desc = (c_uint8 * MS_OS_DESC_STRING_LENGTH)()
    r = usb.get_string_descriptor(handle, MS_OS_DESC_STRING_INDEX, 0, desc,
                                  MS_OS_DESC_STRING_LENGTH)

    if r == MS_OS_DESC_STRING_LENGTH and memcmp(
            ms_os_desc_string, desc, sizeof(ms_os_desc_string)) == 0:
        dump_hex(desc, r)
        return desc[MS_OS_DESC_VENDOR_CODE_OFFSET]
Ejemplo n.º 2
0
def read_ms_os_10_descriptors(handle):
    print("\nReading MS OS 1.0 Descriptors\n")

    vendor_code = get_vendor_code_from_os_string_descriptor(handle)
    if not vendor_code:
        print("    OS String Descriptor is not found")
        return

    print("  Reading Extended Compat ID OS Feature Descriptor")
    request_type = usb.LIBUSB_ENDPOINT_IN | usb.LIBUSB_REQUEST_TYPE_VENDOR | usb.LIBUSB_RECIPIENT_DEVICE
    request = vendor_code
    value = 0x0000
    index = 0x0004
    length = 8
    desc = (c_uint8 * length)()
    # Read the descriptor header
    r = usb.control_transfer(handle, request_type, request, value, index, desc,
                             length, 1000)
    if r != length:
        print("    Extended Compat ID OS Feature Descriptor is not found")
        return

    length = cast(desc, POINTER(c_uint32))[0]  # c_uint32

    # Read the full feature descriptor
    desc = (c_uint8 * length)()
    r = usb.control_transfer(handle, request_type, request, value, index, desc,
                             length, 1000)
    if r != length:
        print("    Extended Compat ID OS Feature Descriptor is not found")
        return

    dump_hex(desc, r)
Ejemplo n.º 3
0
def read_ms_os_20_descriptors(handle, vendor_code):
    print("\nReading MS OS 2.0 descriptors\n")

    print("  Reading MS OS 2.0 descriptor set header")
    request_type = usb.LIBUSB_ENDPOINT_IN | usb.LIBUSB_REQUEST_TYPE_VENDOR | usb.LIBUSB_RECIPIENT_DEVICE
    request = vendor_code
    value = 0x0000
    index = 0x0007
    length = 10
    desc = (c_uint8 * length)()
    # Read the descriptor header
    r = usb.control_transfer(handle, request_type, request, value, index, desc,
                             length, 1000)
    if r != length:
        print("  Not found")
        return

    dump_hex(desc, r)

    length = cast(pointer(desc), POINTER(c_uint16))[4]

    # Read the full feature descriptor
    desc = (c_uint8 * length)()
    r = usb.control_transfer(handle, request_type, request, value, index, desc,
                             length, 1000)
    if r != length:
        print("  Not found")
        return

    dump_hex(desc, r)
Ejemplo n.º 4
0
def display_xbox_status(handle):

    # The XBOX Controller is really a HID device that got its HID Report Descriptors
    # removed by Microsoft.
    # Input/Output reports described at http://euc.jp/periphs/xbox-controller.ja.html

    input_report = (20 * ct.c_uint8)()

    print("\nReading XBox Input Report...")
    r = usb.control_transfer(
        handle, usb.LIBUSB_ENDPOINT_IN | usb.LIBUSB_REQUEST_TYPE_CLASS
        | usb.LIBUSB_RECIPIENT_INTERFACE, HID_GET_REPORT,
        (HID_REPORT_TYPE_INPUT << 8) | 0x00, 0, input_report, 20, 1000)
    if r < 0:
        return err_exit(r)
    print("   D-pad: {:02X}".format(input_report[2] & 0x0F))
    print("   Start:{}, Back:{}, "
          "Left Stick Press:{}, Right Stick Press:{}".format(
              B(input_report[2] & 0x10), B(input_report[2] & 0x20),
              B(input_report[2] & 0x40), B(input_report[2] & 0x80)))
    # A, B, X, Y, Black, White are pressure sensitive
    print("   A:{}, B:{}, X:{}, Y:{}, White:{}, Black:{}".format(
        input_report[4], input_report[5], input_report[6], input_report[7],
        input_report[9], input_report[8]))
    print("   Left Trigger: {}, Right Trigger: {}".format(
        input_report[10], input_report[11]))
    print("   Left Analog (X,Y): ({},{})".format(
        int16_t((input_report[13] << 8) | input_report[12]),
        int16_t((input_report[15] << 8) | input_report[14])))
    print("   Right Analog (X,Y): ({},{})".format(
        int16_t((input_report[17] << 8) | input_report[16]),
        int16_t((input_report[19] << 8) | input_report[18])))
    return 0
Ejemplo n.º 5
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
Ejemplo n.º 6
0
    def _make_control_transfer(self,
                               request_type,
                               b_request,
                               w_value,
                               w_index,
                               data,
                               size,
                               timeout=2000):
        """
        Read/Write data from USB device.
        :param request_type: Request type value. Combines direction, type and recipient enum values.
                        Bit 7: Request direction (0=Host to device - Out, 1=Device to host - In).
                        Bits 5-6: Request type (0=standard, 1=class, 2=vendor, 3=reserved).
                        Bits 0-4: Recipient (0=device, 1=interface, 2=endpoint,3=other).
        :param b_request: Request field for the setup packet. The actual request, see USBRequestCodes Enum.
        :param w_value: Value field for the setup packet. A word-size value that varies according to the request.
                        For example, in the CLEAR_FEATURE request the value is used to select the feature, in the
                        GET_DESCRIPTOR request the value indicates the descriptor type and in the SET_ADDRESS
                        request the value contains the device address.
        :param w_index: Index field for the setup packet. A word-size value that varies according to the request.
                        The index is generally used to specify an endpoint or an interface.
        :param data: ctypes structure class.
        :param size: size of data.
        :return: True if successful otherwise False.
        https://www.jungo.com/st/support/documentation/windriver/802/wdusb_man_mhtml/node55.html#SECTION001213000000000000000
        """
        if self.interface is None:
            raise USBDeviceInterfaceNotClaimedError(self.dev_key)
        if not isinstance(b_request, USBRequestCode):
            raise ValueError(
                'b_request argument must be USBRequestCode enum value.')

        ret = usb.control_transfer(
            self.__libusb_dev_handle__,  # ct.c_char_p
            request_type,  # ct.c_uint8
            b_request,  # ct.c_uint8, must be a USBRequestCode Enum value.
            w_value,  # ct.c_uint16
            w_index,  # ct.c_uint16
            ct.cast(data, ct.POINTER(ct.c_ubyte)),  # ct.POINTER(ct.c_ubyte)
            ct.c_uint16(size),  # ct.c_uint16
            timeout)  # ct.c_uint32

        if ret >= 0:
            if request_type & USBRequestDirection.ENDPOINT_IN:
                _logger.debug('Read {} bytes from'.format(size) +
                              f' {self.dev_key}.')
            else:
                _logger.debug('Wrote {} bytes to'.format(size) +
                              f' {self.dev_key}.')
            return True

        usb_error(ret,
                  _('Failed to communicate with device') + f' {self.dev_key}.')
        return False
Ejemplo n.º 7
0
def get_hwstat(status):

    global devh

    r = usb.control_transfer(devh, CTRL_IN, USB_RQ, 0x07, 0, ct.byref(status), 1, 0)
    if r < 0:
        print("read hwstat error {}".format(r), file=sys.stderr)
        return r
    if r < 1:
        print("short read ({})".format(r), file=sys.stderr)
        return -1

    print("hwstat reads {:02x}".format(status))
    return 0
Ejemplo n.º 8
0
def set_hwstat(status):

    global devh

    print("set hwstat to {:02x}".format(status))

    r = usb.control_transfer(devh, CTRL_OUT, USB_RQ, 0x07, 0, ct.byref(status), 1, 0)
    if r < 0:
        print("set hwstat error {}".format(r), file=sys.stderr)
        return r
    if r < 1:
        print("short write ({})".format(r), file=sys.stderr, end="")
        return -1

    return 0
Ejemplo n.º 9
0
def set_mode(data):

    global devh

    print("set mode {:02x}".format(data))

    r = usb.control_transfer(devh, CTRL_OUT, USB_RQ, 0x4e, 0, ct.byref(data), 1, 0)
    if r < 0:
        print("set mode error {}".format(r), file=sys.stderr)
        return r
    if r < 1:
        print("short write ({})".format(r), file=sys.stderr, end="")
        return -1

    return 0
Ejemplo n.º 10
0
def set_xbox_actuators(handle, left, right):

    print("\nWriting XBox Controller Output Report...")

    output_report = (6 * ct.c_uint8)()
    output_report[1] = ct.sizeof(output_report)
    output_report[3] = left
    output_report[5] = right

    r = usb.control_transfer(
        handle, usb.LIBUSB_ENDPOINT_OUT | usb.LIBUSB_REQUEST_TYPE_CLASS
        | usb.LIBUSB_RECIPIENT_INTERFACE, HID_SET_REPORT,
        (HID_REPORT_TYPE_OUTPUT << 8) | 0x00, 0, output_report, 6, 1000)
    if r < 0:
        return err_exit(r)
    return 0
Ejemplo n.º 11
0
def print_f0_data():

    global devh

    data = (ct.c_ubyte * 0x10)()
    r = usb.control_transfer(devh, CTRL_IN, USB_RQ, 0xf0, 0, data, ct.sizeof(data), 0)
    if r < 0:
        print("F0 error {}".format(r), file=sys.stderr)
        return r
    if r < ct.sizeof(data):
        print("short read ({})".format(r), file=sys.stderr)
        return -1

    print("F0 data:", end="")
    for i in range(ct.sizeof(data)):
        print("{:02x} ".format(data[i]), end="")
    print()
    return 0
Ejemplo n.º 12
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
Ejemplo n.º 13
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
Ejemplo n.º 14
0
def read_ms_winsub_feature_descriptors(handle, bRequest, iface_number):

    # Read the MS WinUSB Feature Descriptors, that are used on Windows 8 for automated driver installation

    MAX_OS_FD_LENGTH = 256

    #int r;

    os_desc = (ct.c_uint8 * MAX_OS_FD_LENGTH)()

    class struct_os_fd(ct.Structure):
        _fields_ = [
        ("desc",        ct.c_char_p),
        ("recipient",   ct.c_uint8),
        ("index",       ct.c_uint16),
        ("header_size", ct.c_uint16),
    ]
    os_fd = [
        struct_os_fd(b"Extended Compat ID",  usb.LIBUSB_RECIPIENT_DEVICE,    0x0004, 0x10),
        struct_os_fd(b"Extended Properties", usb.LIBUSB_RECIPIENT_INTERFACE, 0x0005, 0x0A),
    ]

    if iface_number < 0:
        return

    # WinUSB has a limitation that forces wIndex to the interface number when issuing
    # an Interface Request. To work around that, we can force a Device Request for
    # the Extended Properties, assuming the device answers both equally.
    if force_device_request:
        os_fd[1].recipient = usb.LIBUSB_RECIPIENT_DEVICE

    for i in range(2):

        print("\nReading {} OS Feature Descriptor (wIndex = 0x%04d):".format(
              os_fd[i].desc, os_fd[i].index))

        # Read the header part
        r = usb.control_transfer(handle,
                                 ct.c_uint8(usb.LIBUSB_ENDPOINT_IN |
                                            usb.LIBUSB_REQUEST_TYPE_VENDOR |
                                            os_fd[i].recipient),
                                 bRequest,
                                 ct.c_uint16((iface_number << 8) | 0x00), os_fd[i].index,
                                 os_desc, os_fd[i].header_size,
                                 1000)
        if r < os_fd[i].header_size:
            perr("   Failed: {}", usb.strerror(usb.error(r)) if r < 0 else "header size is too small")
            return
        le_type_punning_IS_fine = ct.cast(os_desc, ct.c_void_p)
        length = ct.cast(le_type_punning_IS_fine, ct.POINTER(ct.c_uint32))[0].value  # ct.c_uint32
        length = min(length, MAX_OS_FD_LENGTH)

        # Read the full feature descriptor
        r = usb.control_transfer(handle,
                                 ct.c_uint8(usb.LIBUSB_ENDPOINT_IN |
                                            usb.LIBUSB_REQUEST_TYPE_VENDOR |
                                            os_fd[i].recipient),
                                 bRequest,
                                 ct.c_uint16((iface_number << 8) | 0x00), os_fd[i].index,
                                 os_desc, ct.c_uint16(length),
                                 1000)
        if r < 0:
            perr("   Failed: {}", usb.strerror(usb.error(r)))
            return
        else:
            display_buffer_hex(os_desc, r)
Ejemplo n.º 15
0
def test_hid(handle, endpoint_in):

    global binary_dump
    global binary_name

    #int r;

    hid_report_descriptor = (ct.c_uint8 * 256)()
    report_buffer = ct.POINTER(ct.c_uint8)

    print("\nReading HID Report Descriptors:")
    descriptor_size = usb.control_transfer(handle,
                                           usb.LIBUSB_ENDPOINT_IN |
                                           usb.LIBUSB_REQUEST_TYPE_STANDARD |
                                           usb.LIBUSB_RECIPIENT_INTERFACE,
                                           usb.LIBUSB_REQUEST_GET_DESCRIPTOR,
                                           usb.LIBUSB_DT_REPORT << 8, 0,
                                           hid_report_descriptor,
                                           ct.sizeof(hid_report_descriptor),
                                           1000)
    if descriptor_size < 0:
        print("   Failed")
        return -1
    display_buffer_hex(hid_report_descriptor, descriptor_size)
    if binary_dump:
        try:
            fd = open(binary_name, "w")
        except: pass
        else:
            with fd:
                if fd.fwrite(hid_report_descriptor, descriptor_size) != descriptor_size:
                    print("   Error writing descriptor to file")

    size = get_hid_record_size(hid_report_descriptor, descriptor_size, HID_REPORT_TYPE_FEATURE)
    if size <= 0:
        print("\nSkipping Feature Report readout (None detected)")
    else:
        report_buffer = ct.cast(calloc(size, 1), ct.POINTER(ct.c_uint8))
        if not report_buffer:
            return -1

        print("\nReading Feature Report (length {})...".format(size))
        r = usb.control_transfer(handle,
                                 usb.LIBUSB_ENDPOINT_IN |
                                 usb.LIBUSB_REQUEST_TYPE_CLASS |
                                 usb.LIBUSB_RECIPIENT_INTERFACE,
                                 HID_GET_REPORT,
                                 (HID_REPORT_TYPE_FEATURE << 8) | 0, 0,
                                 report_buffer, ct.c_uint16(size),
                                 5000)
        if r >= 0:
            display_buffer_hex(report_buffer, size)
        else:
            if r == usb.LIBUSB_ERROR_NOT_FOUND:
                print("   No Feature Report available for this device")
            elif r == usb.LIBUSB_ERROR_PIPE:
                print("   Detected stall - resetting pipe...")
                usb.clear_halt(handle, 0)
            else:
                print("   Error: {}".format(usb.strerror(usb.error(r))))

        free(report_buffer)

    size = get_hid_record_size(hid_report_descriptor, descriptor_size, HID_REPORT_TYPE_INPUT)
    if size <= 0:
        print("\nSkipping Input Report readout (None detected)")
    else:
        report_buffer = ct.cast(calloc(size, 1), ct.POINTER(ct.c_uint8))
        if not report_buffer:
            return -1

        print("\nReading Input Report (length {})...".format(size))
        r = usb.control_transfer(handle,
                                 usb.LIBUSB_ENDPOINT_IN |
                                 usb.LIBUSB_REQUEST_TYPE_CLASS |
                                 usb.LIBUSB_RECIPIENT_INTERFACE,
                                 HID_GET_REPORT,
                                 (HID_REPORT_TYPE_INPUT << 8) | 0x00, 0,
                                 report_buffer, ct.c_uint16(size),
                                 5000)
        if r >= 0:
            display_buffer_hex(report_buffer, size)
        else:
            if r == usb.LIBUSB_ERROR_TIMEOUT:
                print("   Timeout! Please make sure you act on the device within the 5 seconds allocated...")
            elif r == usb.LIBUSB_ERROR_PIPE:
                print("   Detected stall - resetting pipe...")
                usb.clear_halt(handle, 0)
            else:
                print("   Error: {}".format(usb.strerror(usb.error(r))))

        # Attempt a bulk read from endpoint 0 (this should just return a raw input report)
        print("\nTesting interrupt read using endpoint {:02X}...".format(endpoint_in))
        r = usb.interrupt_transfer(handle, endpoint_in, report_buffer, size, ct.byref(size), 5000)
        if r >= 0:
            display_buffer_hex(report_buffer, size)
        else:
            print("   {}".format(usb.strerror(usb.error(r))))

        free(report_buffer)

    return 0
Ejemplo n.º 16
0
def test_mass_storage(handle, endpoint_in, endpoint_out):

    # Mass Storage device to test bulk transfers (non destructive test)

    global binary_dump
    global binary_name

    #int r;
    #ct.c_uint32 i

    print("Reading Max LUN:")
    lun = ct.c_uint8()
    r = usb.control_transfer(handle,
                             usb.LIBUSB_ENDPOINT_IN |
                             usb.LIBUSB_REQUEST_TYPE_CLASS |
                             usb.LIBUSB_RECIPIENT_INTERFACE,
                             BOMS_GET_MAX_LUN,
                             0, 0,
                             ct.byref(lun), 1,
                             1000)
    lun = lun.value
    # Some devices send a STALL instead of the actual value.
    # In such cases we should set lun to 0.
    if r == 0:
        lun = 0
    elif r < 0:
        perr("   Failed: {}".format(usb.strerror(usb.error(r))))
    print("   Max LUN = {}".format(lun))

    # Send Inquiry
    print("Sending Inquiry:")
    buffer = (ct.c_uint8 * 64)()
    cdb    = (ct.c_uint8 * 16)()  # SCSI Command Descriptor Block
    cdb[0] = 0x12  # Inquiry
    cdb[4] = INQUIRY_LENGTH

    expected_tag = ct.c_uint32()
    send_mass_storage_command(handle, endpoint_out, lun, cdb, usb.LIBUSB_ENDPOINT_IN, INQUIRY_LENGTH, ct.pointer(expected_tag))
    size = ct.c_int()
    r = usb.bulk_transfer(handle, endpoint_in, ct.cast(ct.pointer(buffer), ct.POINTER(ct.c_ubyte)), INQUIRY_LENGTH, ct.byref(size), 1000)
    if r < 0:
        return err_exit(r)
    size = size.value
    print("   received {} bytes".format(size))
    # The following strings are not zero terminated
    vid = (ct.c_char * 9)()
    pid = (ct.c_char * 9)()
    rev = (ct.c_char * 5)()
    for i in range(8):
        vid[i]     = buffer[8  + i]
        pid[i]     = buffer[16 + i]
        rev[i / 2] = buffer[32 + i / 2]  # instead of another loop
    vid[8] = 0
    pid[8] = 0
    rev[4] = 0
    print("   VID:PID:REV \"%8s\":\"%8s\":\"%4s\"".format(vid, pid, rev))
    if get_mass_storage_status(handle, endpoint_in, expected_tag) == -2:
        get_sense(handle, endpoint_in, endpoint_out)

    # Read capacity
    print("Reading Capacity:")
    buffer = (ct.c_uint8 * 64)()
    cdb    = (ct.c_uint8 * 16)()  # SCSI Command Descriptor Block
    cdb[0] = 0x25  # Read Capacity

    expected_tag = ct.c_uint32()
    send_mass_storage_command(handle, endpoint_out, lun, cdb, usb.LIBUSB_ENDPOINT_IN, READ_CAPACITY_LENGTH, ct.pointer(expected_tag))
    size = ct.c_int()
    r = usb.bulk_transfer(handle, endpoint_in, ct.cast(ct.pointer(buffer), ct.POINTER(ct.c_ubyte)), READ_CAPACITY_LENGTH, ct.byref(size), 1000)
    if r < 0:
        return err_exit(r)
    size = size.value
    print("   received {} bytes".format(size))
    max_lba     = be_to_int32(buffer[0:])
    block_size  = be_to_int32(buffer[4:])
    device_size = (max_lba + 1.0) * block_size / (1024 * 1024 * 1024)
    print("   Max LBA: {:08X}, Block Size: {:08X} (%.2f GB)".format(
          max_lba, block_size, device_size))
    if get_mass_storage_status(handle, endpoint_in, expected_tag) == -2:
        get_sense(handle, endpoint_in, endpoint_out)

    # coverity[tainted_data]
    try:
        data = ct.cast(calloc(1, block_size), ct.POINTER(ct.c_ubyte)) # unsigned char*
    except:
        perr("   unable to allocate data buffer\n")
        return -1

    # Send Read
    print("Attempting to read %u bytes:".format(block_size))
    cdb    = (ct.c_uint8 * 16)()  # SCSI Command Descriptor Block
    cdb[0] = 0x28  # Read(10)
    cdb[8] = 0x01  # 1 block

    expected_tag = ct.c_uint32()
    send_mass_storage_command(handle, endpoint_out, lun, cdb, usb.LIBUSB_ENDPOINT_IN, block_size, ct.pointer(expected_tag))
    size = ct.c_int()
    usb.bulk_transfer(handle, endpoint_in, data, block_size, ct.byref(size), 5000)
    size = size.value
    print("   READ: received {} bytes".format(size))
    if get_mass_storage_status(handle, endpoint_in, expected_tag) == -2:
        get_sense(handle, endpoint_in, endpoint_out)
    else:
        display_buffer_hex(data, size)
        if binary_dump:
            try:
                fd = open(binary_name, "w")
            except: pass
            else:
                with fd:
                    if fd.fwrite(data, ct.c_size_t(size).value) != ct.c_uint(size).value:
                        perr("   unable to write binary data\n")

    free(data)

    return 0
Ejemplo n.º 17
0
def display_ps3_status(handle):

    # The PS3 Controller is really a HID device that got its HID Report Descriptors
    # removed by Sony

    input_report      = (ct.c_uint8 * 49)()
    master_bt_address = (ct.c_uint8 *  8)()
    device_bt_address = (ct.c_uint8 * 18)()

    # Get the controller's bluetooth address of its master device
    r = usb.control_transfer(handle,
                             usb.LIBUSB_ENDPOINT_IN |
                             usb.LIBUSB_REQUEST_TYPE_CLASS |
                             usb.LIBUSB_RECIPIENT_INTERFACE,
                             HID_GET_REPORT,
                             0x03f5, 0,
                             master_bt_address,
                             ct.sizeof(master_bt_address),
                             100)
    if r < 0:
        return err_exit(r)
    print("\nMaster's bluetooth address: "
          "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}".format(
          master_bt_address[2], master_bt_address[3], master_bt_address[4],
          master_bt_address[5], master_bt_address[6], master_bt_address[7]))

    # Get the controller's bluetooth address
    r = usb.control_transfer(handle,
                             usb.LIBUSB_ENDPOINT_IN |
                             usb.LIBUSB_REQUEST_TYPE_CLASS |
                             usb.LIBUSB_RECIPIENT_INTERFACE,
                             HID_GET_REPORT,
                             0x03f2, 0,
                             device_bt_address,
                             ct.sizeof(device_bt_address),
                             100)
    if r < 0:
        return err_exit(r)
    print("\nMaster's bluetooth address: "
          "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}".format(
          device_bt_address[4], device_bt_address[5], device_bt_address[6],
          device_bt_address[7], device_bt_address[8], device_bt_address[9]))

    # Get the status of the controller's buttons via its HID report
    print("\nReading PS3 Input Report...")
    r = usb.control_transfer(handle,
                             usb.LIBUSB_ENDPOINT_IN |
                             usb.LIBUSB_REQUEST_TYPE_CLASS |
                             usb.LIBUSB_RECIPIENT_INTERFACE,
                             HID_GET_REPORT,
                             (HID_REPORT_TYPE_INPUT << 8) | 0x01, 0,
                             input_report,
                             ct.sizeof(input_report),
                             1000)
    if r < 0:
        return err_exit(r)
    pressed = input_report[2]  # Direction pad plus start, select, and joystick buttons
    if   pressed == 0x01: print("\tSELECT pressed")
    elif pressed == 0x02: print("\tLEFT 3 pressed")
    elif pressed == 0x04: print("\tRIGHT 3 pressed")
    elif pressed == 0x08: print("\tSTART presed")
    elif pressed == 0x10: print("\tUP pressed")
    elif pressed == 0x20: print("\tRIGHT pressed")
    elif pressed == 0x40: print("\tDOWN pressed")
    elif pressed == 0x80: print("\tLEFT pressed")
    pressed = input_report[3]  # Shapes plus top right and left buttons
    if   pressed == 0x01: print("\tLEFT 2 pressed")
    elif pressed == 0x02: print("\tRIGHT 2 pressed")
    elif pressed == 0x04: print("\tLEFT 1 pressed")
    elif pressed == 0x08: print("\tRIGHT 1 presed")
    elif pressed == 0x10: print("\tTRIANGLE pressed")
    elif pressed == 0x20: print("\tCIRCLE pressed")
    elif pressed == 0x40: print("\tCROSS pressed")
    elif pressed == 0x80: print("\tSQUARE pressed")
    print("\tPS button: {}".format(input_report[4]))
    print("\tLeft Analog (X,Y): ({},{})".format(input_report[6],  input_report[7]))
    print("\tRight Analog (X,Y): ({},{})".format(input_report[8], input_report[9]))
    print("\tL2 Value: {}\tR2 Value: {}".format(input_report[18], input_report[19]))
    print("\tL1 Value: {}\tR1 Value: {}".format(input_report[20], input_report[21]))
    print("\tRoll (x axis): {} Yaw (y axis): {} Pitch (z axis) {}".format(
            #(((input_report[42] + 128) % 256) - 128),
            int8_t(input_report[42]),
            int8_t(input_report[44]),
            int8_t(input_report[46])))
    print("\tAcceleration: {}".format(int8_t(input_report[48])))
    print()

    return 0