libusb示例

dozeoo dozeoo     2022-09-14     652

关键词:

技术分享
#include <stdio.h>
#include <libusb-1.0/libusb.h>
#include <stdint.h>
#include <string.h>

void processMessage(const uint8_t*);


/*----------------------------------------------------------------------*/
int main(int argc, char*argv[])
{
  int res                      = 0;  /* return codes from libusb functions */
  libusb_device_handle* handle = 0;  /* handle for USB device */
  int kernelDriverDetached     = 0;  /* Set to 1 if kernel driver detached */
  int numBytes                 = 0;  /* Actual bytes transferred. */
  uint8_t buffer[64];                /* 64 byte transfer buffer */

  /* Initialise libusb. */
  res = libusb_init(0);
  if (res != 0)
  {
    fprintf(stderr, "Error initialising libusb.
");
    return 1;
  }

  /* Get the first device with the matching Vendor ID and Product ID. If
   * intending to allow multiple demo boards to be connected at once, you
   * will need to use libusb_get_device_list() instead. Refer to the libusb
   * documentation for details. */
  handle = libusb_open_device_with_vid_pid(0, 0x04d8, 0x0070);
  if (!handle)
  {
    fprintf(stderr, "Unable to open device.
");
    return 1;
  }

  /* Check whether a kernel driver is attached to interface #0. If so, we‘ll 
   * need to detach it.
   */
  if (libusb_kernel_driver_active(handle, 0))
  {
    res = libusb_detach_kernel_driver(handle, 0);
    if (res == 0)
    {
      kernelDriverDetached = 1;
    }
    else
    {
      fprintf(stderr, "Error detaching kernel driver.
");
      return 1;
    }
  }

  /* Claim interface #0. */
  res = libusb_claim_interface(handle, 0);
  if (res != 0)
  {
    fprintf(stderr, "Error claiming interface.
");
    return 1;
  }


  /* We can now send and receive messages. For example, set normal mode. */
  memset(buffer, 0, 64);
  buffer[58] = 0;      /* CANCTRL = Normal mode. */
  buffer[60] = 0x02;   /* SPI command = Write.   */
  buffer[61] = 0x0f;   /* Register = CANCTRL     */
  buffer[62] = 0;      /* Data = 0 (normal mode) */
  
  /* Send the message to endpoint 1 with a 100ms timeout. */
  res = libusb_interrupt_transfer(handle, 1, buffer, 64, &numBytes, 100);
  if (res == 0)
  {
    printf("%d bytes transmitted successfully.
", numBytes);
  }
  else
  {
    fprintf(stderr, "Error sending message to device.
");
  }


  /* Listen for a message. Note that for a normal application you‘ll need 
   * to use asynchronous mode because we can‘t predict when messages will be
   * available. This involves setting up a callback function to handle incoming
   * messages - refer to libusb documentation. */

  /* Wait up to 5 seconds for a message to arrive on endpoint 0x81. */
  res = libusb_interrupt_transfer(handle, 0x81, buffer, 64, &numBytes, 5000);
  if (0 == res)
  {
    if (numBytes == 64)
    {
      processMessage(buffer);
    }
    else
    {
      printf("Received %d bytes, expected 64.
", numBytes);
    }
  }
  else
  {
    fprintf(stderr, "Error receiving message.
");
  }

  /* Release interface #0. */
  res = libusb_release_interface(handle, 0);
  if (0 != res)
  {
    fprintf(stderr, "Error releasing interface.
");
  }

  /* If we detached a kernel driver from interface #0 earlier, we‘ll now 
   * need to attach it again.  */
  if (kernelDriverDetached)
  {
    libusb_attach_kernel_driver(handle, 0);
  }

  /* Shutdown libusb. */
  libusb_exit(0);

  return 0;
}


/*----------------------------------------------------------------------*/
void processMessage(const uint8_t* buffer)
{
  unsigned index = 0;

  /* Most significant bit set indicates a CAN message is present. */
  while(buffer[index] & 0x80)
  {
    unsigned extendedID = buffer[index] & 0x20;
    unsigned rtr        = buffer[index] & 0x10;
    unsigned dataLength = buffer[index] & 0x0f;
    unsigned canID      = 0;

    ++index;

    if (extendedID)  /* 29 bit identifier */
    {
      canID = buffer[index] << 21;
      ++index;
      canID |= (((buffer[index] & 0xe0 >> 5) | 
            (buffer[index] & 0x03)) << 16);
      ++index;
      canID |= (buffer[index] << 8);
      ++index;
      canID |= (buffer[index]);
      ++index;
    }
    else /* standard 11 bit identifier */
    {
      canID      = buffer[index] << 3;
      ++index;
      canID |= ((buffer[index] >> 1) & 7);
      ++index;
    }

    printf("CAN ID: 0x%x [%s] ", canID,
        extendedID ? "extended" : "standard");

    if (rtr)
    {
      printf("RTR
");
    }
    else
    {
      unsigned i = 0;
      for (i = 0; i < dataLength; ++i)
      {
        printf("0x%02x ", buffer[index]);
        ++index;
      }
      printf("
");
    }
  }

  printf("CAN Status:      0x%02x
", buffer[57]);
  printf("Transmit Errors: %u
", buffer[55]);
  printf("Receive Errors:  %u
", buffer[56]);

  /* If the command was read, we have received the result. */
  if (buffer[60] == 0x03)
  {
    printf("Read from register 0x%02x returned 0x%02x
",
        buffer[61], buffer[62]);
  }
}
View Code
技术分享
#include <stdio.h>    
#include <stdlib.h>    
#include <sys/types.h>    
#include <string.h>    
#include </usr/local/include/libusb-1.0/libusb.h>    


#define BULK_EP_OUT     0x82    
#define BULK_EP_IN      0x08    

int interface_ref = 0;    
int alt_interface,interface_number;    

int print_configuration(struct libusb_device_handle *hDevice,struct libusb_config_descriptor *config)    
{    
    char *data;    
    int index;    

    data = (char *)malloc(512);    
    memset(data,0,512);    

    index = config->iConfiguration;    

    libusb_get_string_descriptor_ascii(hDevice,index,data,512);    

    printf("
Interface Descriptors: ");    
    printf("
	Number of Interfaces : %d",config->bNumInterfaces);    
    printf("
	Length : %d",config->bLength);    
    printf("
	Desc_Type : %d",config->bDescriptorType);    
    printf("
	Config_index : %d",config->iConfiguration);    
    printf("
	Total length : %lu",config->wTotalLength);    
    printf("
	Configuration Value  : %d",config->bConfigurationValue);    
    printf("
	Configuration Attributes : %d",config->bmAttributes);    
    printf("
	MaxPower(mA) : %d
",config->MaxPower);    

    free(data);    
    data = NULL;    
    return 0;    
}    

struct libusb_endpoint_descriptor* active_config(struct libusb_device *dev,struct libusb_device_handle *handle)    
{    
    struct libusb_device_handle *hDevice_req;    
    struct libusb_config_descriptor *config;    
    struct libusb_endpoint_descriptor *endpoint;    
    int altsetting_index,interface_index=0,ret_active;    
    int i,ret_print;    

    hDevice_req = handle;    

    ret_active = libusb_get_active_config_descriptor(dev,&config);    
    ret_print = print_configuration(hDevice_req,config);    

    for(interface_index=0;interface_index<config->bNumInterfaces;interface_index++)    
    {    
        const struct libusb_interface *iface = &config->interface[interface_index];    
        for(altsetting_index=0;altsetting_index<iface->num_altsetting;altsetting_index++)    
        {    
            const struct libusb_interface_descriptor *altsetting = &iface->altsetting[altsetting_index];    

            int endpoint_index;    
            for(endpoint_index=0;endpoint_index<altsetting->bNumEndpoints;endpoint_index++)    
            {    
                const struct libusb_endpoint_desriptor *ep = &altsetting->endpoint[endpoint_index];    
                endpoint = ep;      
                alt_interface = altsetting->bAlternateSetting;    
                interface_number = altsetting->bInterfaceNumber;    
            }    

            printf("
EndPoint Descriptors: ");    
            printf("
	Size of EndPoint Descriptor : %d",endpoint->bLength);    
            printf("
	Type of Descriptor : %d",endpoint->bDescriptorType);    
            printf("
	Endpoint Address : 0x0%x",endpoint->bEndpointAddress);    
            printf("
	Maximum Packet Size: %x",endpoint->wMaxPacketSize);    
            printf("
	Attributes applied to Endpoint: %d",endpoint->bmAttributes);    
            printf("
	Interval for Polling for data Tranfer : %d
",endpoint->bInterval);    
        }    
    }    
    libusb_free_config_descriptor(NULL);    
    return endpoint;    
}    

int main(void)    
{    
    int r = 1;    
    struct libusb_device **devs;    
    struct libusb_device_handle *handle = NULL, *hDevice_expected = NULL;    
    struct libusb_device *dev,*dev_expected;    

    struct libusb_device_descriptor desc;    
    struct libusb_endpoint_descriptor *epdesc;    
    struct libusb_interface_descriptor *intdesc;    

    ssize_t cnt;    
    int e = 0,config2;    
    int i = 0,index;    
    char str1[64], str2[64];    
    char found = 0;    

// Init libusb     
    r = libusb_init(NULL);    
    if(r < 0)    
    {    
        printf("
failed to initialise libusb
");    
        return 1;    
    }    
    else    
        printf("
Init Successful!
");    

// Get a list os USB devices    
    cnt = libusb_get_device_list(NULL, &devs);    
    if (cnt < 0)    
    {    
        printf("
There are no USB devices on bus
");    
        return -1;    
    }    
    printf("
Device Count : %d
-------------------------------
",cnt);    

    while ((dev = devs[i++]) != NULL)    
    {    
        r = libusb_get_device_descriptor(dev, &desc);    
        if (r < 0)    
            {    
            printf("failed to get device descriptor
");    
            libusb_free_device_list(devs,1);    
            libusb_close(handle);    
            break;    
        }    

        e = libusb_open(dev,&handle);    
        if (e < 0)    
        {    
            printf("error opening device
");    
            libusb_free_device_list(devs,1);    
            libusb_close(handle);    
            break;    
        }    

        printf("
Device Descriptors: ");    
        printf("
	Vendor ID : %x",desc.idVendor);    
        printf("
	Product ID : %x",desc.idProduct);    
        printf("
	Serial Number : %x",desc.iSerialNumber);    
        printf("
	Size of Device Descriptor : %d",desc.bLength);    
        printf("
	Type of Descriptor : %d",desc.bDescriptorType);    
        printf("
	USB Specification Release Number : %d",desc.bcdUSB);    
        printf("
	Device Release Number : %d",desc.bcdDevice);    
        printf("
	Device Class : %d",desc.bDeviceClass);    
        printf("
	Device Sub-Class : %d",desc.bDeviceSubClass);    
        printf("
	Device Protocol : %d",desc.bDeviceProtocol);    
        printf("
	Max. Packet Size : %d",desc.bMaxPacketSize0);    
        printf("
	No. of Configuraions : %d
",desc.bNumConfigurations);    

        e = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, (unsigned char*) str1, sizeof(str1));    
        if (e < 0)    
        {    
        libusb_free_device_list(devs,1);    
            libusb_close(handle);    
            break;    
        }    
        printf("
Manufactured : %s",str1);    

        e = libusb_get_string_descriptor_ascii(handle, desc.iProduct, (unsigned char*) str2, sizeof(str2));    
        if(e < 0)    
        {    
        libusb_free_device_list(devs,1);    
            libusb_close(handle);    
            break;    
        }    
        printf("
Product : %s",str2);    
        printf("
----------------------------------------");    

        if(desc.idVendor == 0xffff && desc.idProduct == 0x4)    
        {    
        found = 1;    
        break;    
        }    
    }//end of while    
    if(found == 0)    
    {    
        printf("
Device NOT found
");    
        libusb_free_device_list(devs,1);    
        libusb_close(handle);    
        return 1;    
    }    
    else    
    {    
        printf("
Device found");    
        dev_expected = dev;    
        hDevice_expected = handle;    
    }    

    e = libusb_get_configuration(handle,&config2);    
    if(e!=0)    
    {    
        printf("
***Error in libusb_get_configuration
");    
        libusb_free_device_list(devs,1);    
        libusb_close(handle);    
        return -1;    
    }    
    printf("
Configured value : %d",config2);    

    if(config2 != 1)    
    {    
        libusb_set_configuration(handle, 1);    
        if(e!=0)    
        {    
            printf("Error in libusb_set_configuration
");    
            libusb_free_device_list(devs,1);    
            libusb_close(handle);    
            return -1;    
        }    
        else    
            printf("
Device is in configured state!");    
    }    

    libusb_free_device_list(devs, 1);    

    if(libusb_kernel_driver_active(handle, 0) == 1)    
    {    
        printf("
Kernel Driver Active");    
        if(libusb_detach_kernel_driver(handle, 0) == 0)    
            printf("
Kernel Driver Detached!");    
        else    
        {    
            printf("
Couldn‘t detach kernel driver!
");    
            libusb_free_device_list(devs,1);    
            libusb_close(handle);    
            return -1;    
        }    
    }    

    e = libusb_claim_interface(handle, 0);    
    if(e < 0)    
    {    
        printf("
Cannot Claim Interface");    
        libusb_free_device_list(devs,1);    
        libusb_close(handle);    
        return -1;    
    }    
    else    
        printf("
Claimed Interface
");    

    active_config(dev_expected,hDevice_expected);    

    //   Communicate     

    char *my_string, *my_string1;    
    int transferred = 0;    
    int received = 0;    
    int length = 0;    

    my_string = (char *)malloc(nbytes + 1);    
    my_string1 = (char *)malloc(nbytes + 1);    

    memset(my_string,,64);    
    memset(my_string1,,64);    

    strcpy(my_string,"prasad divesd");    
    length = strlen(my_string);    

    printf("
To be sent : %s",my_string);    

    e = libusb_bulk_transfer(handle,BULK_EP_IN,my_string,length,&transferred,0);    
    if(e == 0 && transferred == length)    
    {    
        printf("
Write successful!");    
        printf("
Sent %d bytes with string: %s
", transferred, my_string);    
    }    
    else    
        printf("
Error in write! e = %d and transferred = %d
",e,transferred);    

    sleep(3);    
    i = 0;    

    for(i = 0; i < length; i++)    
    {    
        e = libusb_bulk_transfer(handle,BULK_EP_OUT,my_string1,64,&received,0);  //64 : Max Packet Lenght    
        if(e == 0)    
        {    
            printf("
Received: ");    
            printf("%c",my_string1[i]);    //will read a string from lcp2148
            sleep(1);    
        }    
        else    
        {    
            printf("
Error in read! e = %d and received = %d
",e,received);    
            return -1;    
        }    
    }    


    e = libusb_release_interface(handle, 0);    

    libusb_close(handle);    
    libusb_exit(NULL);    

    printf("
");    
    return 0;    
}    
View Code

 

linux / libusb 获取usb设备路径

】linux/libusb获取usb设备路径【英文标题】:linux/libusbgetusbdevicepath【发布时间】:2012-12-2603:09:27【问题描述】:我使用libusb来枚举一些USB设备。现在我想获得“设备路径”。我认为它不叫usbdevice-path,因为我在google上没有成功。如... 查看详情

如何在 Mac OS X 上设置 libusb?

】如何在MacOSX上设置libusb?【英文标题】:HowtosetuplibusbonMacOSX?【发布时间】:2011-04-2016:45:41【问题描述】:我想尝试在Mac上使用libusb制作用户空间设备驱动程序,但我不知道从哪里开始。在SDK安装程序(我从http://www.ellert.se/twain... 查看详情

libusb系列-001-libusb简介(代码片段)

libusb系列-001-libusb简介文章目录libusb系列-001-libusb简介摘要基本信息简介支持平台官网如何使用下载神奇的1.0.9版本关键字:Debian、Linux、Qt、libusb、源码内容背景:最近项目终于切到Linux下开发了,所以最近的记录都是... 查看详情

libusb系列-002-windows下libusb源码编译(代码片段)

libusb系列-002-Windows下libusb源码编译文章目录libusb系列-002-Windows下libusb源码编译摘要Windows下编译libusb库下载源码进入msvc目录选择对应的项目工程编译查看编译好的库文件关键字:vs、编译、Qt、libusb、windows内容背景:最近... 查看详情

libusb系列-003-linux下libusb源码编译(代码片段)

libusb系列-003-Linux下libusb源码编译文章目录libusb系列-003-Linux下libusb源码编译摘要源码下载及解压下载源码解压下载的源码压缩包打开终端准备编译环境安装makedh-autoreconf安装libudev-dev编译错误的教程增加执行bootstrap.sh指令再编译mak... 查看详情

libusb系列-004-qt下使用libusb库(代码片段)

libusb系列-004-Qt下使用libusb库文章目录libusb系列-004-Qt下使用libusb库摘要复制库到指定目录在Pro中包含库文件包含头文件多说一句关键字:Debian、Linux、Qt、libusb、源码内容背景:最近项目终于切到Linux下开发了,所以最... 查看详情

libusb系列-006-qt下使用libusb1.0.9源码(代码片段)

libusb系列-006-Qt下使用libusb1.0.9源码文章目录libusb系列-006-Qt下使用libusb1.0.9源码摘要添加宏添加源文件编译文件测试libusb工程源码关键字:Debian、Linux、Qt、libusb、源码内容背景:最近项目终于切到Linux下开发了,所以最... 查看详情

如何使用 libusb 和 libusb_get_device_descriptor()?

】如何使用libusb和libusb_get_device_descriptor()?【英文标题】:Howtouselibusbandlibusb_get_device_descriptor()?【发布时间】:2013-01-2105:43:51【问题描述】:我正在学习第一次在Ubuntu12.10上使用libusbv1.0.0。这是我用来尝试了解如何使用此API的一... 查看详情

缓慢构建 librealsense libusb

】缓慢构建librealsenselibusb【英文标题】:slowbuildlibrealsenselibusb【发布时间】:2020-09-2312:59:45【问题描述】:当我启动我的程序时,构建需要很长时间,比如3.5分钟。我明白了:1>------Buildstarted:Project:libusb(ExternalProjectTargets\\libusb... 查看详情

安卓L | libusb_init 返回 LIBUSB_ERROR_OTHER (-99)

】安卓L|libusb_init返回LIBUSB_ERROR_OTHER(-99)【英文标题】:AndroidL|libusb_initreturnsLIBUSB_ERROR_OTHER(-99)【发布时间】:2014-10-2900:22:54【问题描述】:我尝试按照thisapproach中的建议在未植根的Nexus5上使用libusb(通过将USB文件描述符从java传输... 查看详情

libusb_open 在 Windows 7 上返回“LIBUSB_ERROR_NOT_SUPPORTED”

】libusb_open在Windows7上返回“LIBUSB_ERROR_NOT_SUPPORTED”【英文标题】:libusb_openreturns\'LIBUSB_ERROR_NOT_SUPPORTED\'onWindows7【发布时间】:2013-06-2508:51:51【问题描述】:我一直在Linux上使用LibUSB开发USB驱动程序,但现在我想为Windows编译一个... 查看详情

linux下交叉编译libusb的方法及编译一个使用了libusb库的test程序的方法(代码片段)

linux交叉编译libusb的方法下载libusb下载网址:libusb-BrowseFilesatSourceForge.net交叉编译libusb将下载好的libusb压缩包解压后进入该文件执行下列指令./configure--build=i686-linux--host=arm-linux--prefix=/home/xfc/usb/installCC 查看详情

libusb系列-007-qt下使用libusb1.0.26源码(代码片段)

libusb系列-007-Qt下使用libusb1.0.26源码文章目录libusb系列-007-Qt下使用libusb1.0.26源码摘要安装编译环境确认需要的文件开始编译错误1:找不到文件错误2:expected错误3:SCM_CREDENTALS错误4:类型冲突错误5assert断言错误错... 查看详情

libusb使用

xxx 查看详情

linux下libusb库的安装与使用

一、下载libusb下载网址:http://www.libusb.org/这里我选择的是下载:libusb-1.0.24二、安装libusb解压后libusb-1.0.24,得到的是源代码。$tar-jxvflibusb-1.0.24.tar.bz2$cdlibusb-1.0.24$./configure--prefix=/usr/local/li 查看详情

linux编译libusb(代码片段)

下载GitHub-libusb/libusb:Across-platformlibrarytoaccessUSBdevices安装依赖sudoaptinstall-ymakedh-autoreconf编译./autogen.sh./configuremakesudomakeinstall测试cdexamples./listdevs 查看详情

libusb3.0

...buffer太大时,读不到数据问题? 2)linux下,usb3.0 libusb_claim_interfacefail,error=-5对于一些linux标准支持的设备(如HID设备),可能需要使用libusb_detach_kernel_driver,或libusb_set_auto_detach_kernel_driver,将kernel提供的驱动卸载掉,否... 查看详情

linux下libusb库的安装与使用

一、下载libusb下载网址:http://www.libusb.org/这里我选择的是下载:libusb-1.0.24二、安装libusb解压后libusb-1.0.24,得到的是源代码。$tar-jxvflibusb-1.0.24.tar.bz2$cdlibusb-1.0.24$./configure--prefix=/usr/local/libusb-1.0.24$make$makeinstall三、... 查看详情