使用 libusb_bulk_transfer 从 USB HID 设备读取,并获取 libusb_error_io

问题描述

我正在做一个小项目,通过 USB 从三丰数字指示器读取值。通过采用 libUSB,我可以打开具有正确 PID 和 VID 的设备,并获得以下信息:

Reading device descriptor:
            length: 18
      device class: 0
               S/N: 3
           VID:PID: 0FE7:4001
         bcdDevice: 1100
   iMan:iProd:iSer: 1:2:3
          nb confs: 1

Reading BOS descriptor: no descriptor

Reading first configuration descriptor:
             nb interfaces: 1
              interface[0]: id = 0
interface[0].altsetting[0]: num endpoints = 1
   Class.SubClass.Protocol: 03.00.00
       endpoint[0].address: 81
           max packet size: 0008
          polling interval: 0A

Reading string descriptors:
   String (0x01): "Mitutoyo"
   String (0x02): "USB-ITN"
   String (0x03): "60026369"

然后,我尝试了以下代码

int transferred = 0; // actual size for write
int received = 0; // actual size for read
const int TRANSFER_SIZE = 9;  // transfer size
unsigned char buffer[TRANSFER_SIZE]; // USB buffer

char _cmd[TRANSFER_SIZE]; // command to be sent to device
strncpy_s(_cmd,"\0",sizeof("\0"));
strncat_s(_cmd,"R\r",sizeof("R\r"));
printf("_cmd %s \n",_cmd);

const int command_len = strlen(_cmd); // Get the length of the command string we are sending
if (command_len > TRANSFER_SIZE)
{
    printf("Error: command is larger than our limit of %i\n",TRANSFER_SIZE);
    return -1;
}

memset(buffer,TRANSFER_SIZE); // Zero out buffer to pad with null values 
memcpy(&buffer,_cmd,strlen(_cmd)); // put command into buffer

// write to device
int e = libusb_bulk_transfer(handle,buffer,TRANSFER_SIZE,&transferred,1500);
if (e >= 0)
{
    printf("\nWrite successful!");
    printf("\nSent %d bytes with string: %s\n",transferred,buffer);
}
else
    printf("\nError in write! e = %d and transferred = %d\n",e,transferred);

// read from device
e = libusb_bulk_transfer(handle,BULK_EP_IN,&received,1000);
if (e >= 0)
{
    printf("\nReceived: ");
    printf("%c",buffer[i]); //Will read a string from LPC2148
}
else
    printf("\nError in read! e = %d and received = %d\n",received);

但是,我得到了

Error in write! e = -1 and transferred = 0
Error in read! e = -1 and received = 0

对应于libusb_error_io。我没有找到有关错误类型的任何详细信息。所以我想知道错误是否表明 I/O 地址错误,或者我发送到设备的协议错误,或者缺少 libUSB 的某些系统依赖项?

顺便说一句,我随机尝试了设备的协议,因为我没有找到任何这种类型的文档。命令 "R\r" 来自 Mitutoyo 的不同类型的设备。如果有人碰巧知道 Mitutoyo 数字指示器系列 ID-S 的协议,如果能提供更多信息,我将不胜感激。

一个问题,是否有必要在缓冲区的开头放一个"\0"?如果低速设备的标准传输大小是 8,那么我应该发送到设备的缓冲区是 8+1。对吗?

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)