我可以成功地将数据发送到USB设备,但每次设备的响应都会失败。我确信端点是正确的,因为使用windows中的hid api与相同设备成功通信。
这是我的代码:
struct libusb_context* hContxt;
libusb_init(&hContxt);
libusb_set_debug(hContxt, LIBUSB_LOG_LEVEL_DEBUG);
libusb_device_handle* hUsbHandle = libusb_open_device_with_vid_pid(hContxt, 0x0483, 0x3021);;
if (NULL == hUsbHandle)
{
printf("open failed!\n");
return 0;
}
libusb_claim_interface(hUsbHandle, 0);
int _nMaxPackSize = libusb_get_max_packet_size(libusb_get_device(hUsbHandle), 0x01);
unsigned char _szCmd[1024] = "12355666";
int _nSendSuccessLen = 0;
int _nRet = libusb_interrupt_transfer(hUsbHandle, 0x01,\
const_cast<unsigned char*>(&_szCmd[0]), _nMaxPackSize, &_nSendSuccessLen, 200);
unsigned char recv[1024];
int recvExpectLen = 0;
int recvAcutalLen = 0;
_nMaxPackSize = libusb_get_max_packet_size(libusb_get_device(hUsbHandle), 0x81);
while(1)
{
memset(recv, 0x00, sizeof recv);
_nRet = libusb_interrupt_transfer(hUsbHandle, 0x81,\
const_cast<unsigned char*>(recv), _nMaxPackSize, &recvAcutalLen, 1000);//block in libusb_handle_events_timeout_completed.
if (_nRet == LIBUSB_SUCCESS)
{
printf("recv Len: %d\n", recvAcutalLen);
}
Sleep(1000);
}
我是否需要设置libusb的其他API?
libusb的调试信息如下:
[ 0.811201] [00000820] libusb: debug [hid_submit_bulk_transfer] matched endpoint
81 with interface 0
[ 0.811201] [00000820] libusb: debug [hid_submit_bulk_transfer] reading 65 bytes
(report ID: 0x00)
[ 0.826801] [00000820] libusb: debug [libusb_get_next_timeout] next timeout in 0
.982700s
[ 0.826801] [00000820] libusb: debug [libusb_handle_events_timeout_completed] do
ing our own event handling
[ 0.842401] [00000820] libusb: debug [handle_events] poll fds modified, reallocating
[ 0.842401] [00000820] libusb: debug [handle_events] poll() 2 fds with timeout i
n 983ms
[ 1.840803] [00000820] libusb: debug [handle_events] poll() returned 0
[ 1.840803] [00000820] libusb: debug [libusb_cancel_transfer] transfer 00474628
[ 1.872003] [00000820] libusb: debug [hid_abort_transfers] will use interface 0<br/>
[ 1.887603] [00000820] libusb: warning [hid_abort_transfers] cancel failed: [6]
句柄无效。<br/>
[ 1.918803] [00000820] libusb: debug [libusb_cancel_transfer] cancel transfer failed error -5
[ 1.918803] [00000820] libusb: warning [handle_timeout] async cancel failed -5 errno=0
[ 1.918803] [00000820] libusb: debug [libusb_get_next_timeout] no URB with timeo
ut or all handled by OS; no timeout!
[ 1.918803] [00000820] libusb: debug [libusb_handle_events_timeout_completed] do
ing our own event handling
[ 1.934403] [00000820] libusb: debug [handle_events] poll() 2 fds with timeout i
n 60000ms