libusb_bulk_transfer()只能运行一次

时间:2015-08-26 17:29:48

标签: c++ libusb

我对Libusb完全不熟悉。我在Ubuntu中编写了一个c ++程序,我可以连接到设备,我使用libusb_bulk_transfer(...)将一些数据传输到设备。它第一次工作,但第二次返回-1代码。但是,当我拒绝该设备,然后当我将设备重新安装到我的计算机时,它再次起作用。
这是我的代码:

#include <iostream>
#include <stdio.h>
#include <libusb.h>

using namespace std;

#define BULK_OUTPUT LIBUSB_ENDPOINT_OUT | 0x01
#define BULK_INPUT LIBUSB_ENDPOINT_IN | 0x01

union usb_relator {
    unsigned char usb_data[4];
    int32_t number;
};

int main()
{
    libusb_device_handle *handle = NULL;

    if (libusb_init(NULL) < 0)
    {
        cout << "Failure" << endl;
        return 0;
    }
    cout << "libusb inited successfully!!" << endl;

    libusb_device **devices;
    libusb_get_device_list(NULL, &devices);

    if (libusb_open(devices[0], &handle) < 0)
    {
        cout << "The device can not be open!!" << endl;
        return 0;
    }
    cout << "device opened successfully!!" << endl;

    libusb_device_descriptor descriptor;
    libusb_get_device_descriptor(devices[0], &descriptor);
    cout << "Vendor id: " << (int)descriptor.idVendor << endl;
    cout << "Product Id: " << (int)descriptor.idProduct << endl;

    libusb_detach_kernel_driver(handle, 0);
    if (libusb_claim_interface(handle, 0) < 0)
    {
        cout << "Can not claim interface!!" << endl;
        return 0;
    }
    cout << "Handle has been claimed!!" << endl;

    if (libusb_set_interface_alt_setting(handle, 0, 0) < 0)
    {
        cout << "Could not set alternate setting of the handle!!" << endl;
        return 0;
    }
    cout << "alt_setting set successfully!!" << endl;

    usb_relator number;

    cout << "Please insert your number: ";  
    cin >> number.number;

    int transfer_size;

    int returnCode = libusb_bulk_transfer(handle, BULK_OUTPUT, number.usb_data, sizeof(usb_relator), &transfer_size, 5000);
    if (returnCode == 0)
    {
        cout << "Data sent!!" << endl;
    }
    else
    {
        cout << "Data could not be send!! Code: " << returnCode << endl;
    }

    returnCode = libusb_bulk_transfer(handle, BULK_INPUT, number.usb_data, sizeof(usb_relator), &transfer_size, 5000);
    if (returnCode == 0)
    {
        cout << "Data recieved!!" << endl;
        cout << number.usb_data << endl;
    }
    else
    {
        cout << "Data could not recieve!! Code: " << returnCode << endl;
    }



    libusb_release_interface(handle, 0);
    libusb_close(handle);
    libusb_free_device_list(devices, 1);
    libusb_exit(NULL);
}

<小时/> 我正在使用Ubuntu 14.04,而我正在使用VMWare。谢谢你的帮助。 我认为它与我在代码中调用的libusb_detach_kernal_driver(...)方法有关。(在我声明界面的行之前)。

0 个答案:

没有答案