libusb的使用教程

libusb的使用教程

Linux 平台上的usb驱动开发,主要有内核驱动的开发和基于libusb的无驱设计。

对于内核驱动的大部分设备,诸如带usb接口的hid设备,linux本身已经自带了相关的驱动,我们只要操作设备文件便可以完成对设备大部分的操作,而另外一些设备,诸如自己设计的硬件产品,这些驱动就需要我们驱动工程师开发出相关的驱动了。内核驱动有它的优点,然而内核驱动在某些情况下会遇到如下的一些问题:

1 当使用我们产品的客户有2.4内核的平台,同时也有2.6内核的平台,我们要设计的驱动是要兼容两个平台的,就连makefile 我们都要写两个。

2 当我们要把linux移植到嵌入平台上,你会发现原先linux自带的驱动移过去还挺大的,我的内核当然是越小越好拉,这样有必要么。这还不是最郁闷的地方,如果嵌入平台是客户的,客户要购买你的产品,你突然发现客户设备里的系统和你的环境不一样,它没有你要的驱动了,你的程序运行不了,你会先想:“没关系,我写个内核驱动加载一下不就行了“。却发现客户连insmod加载模块的工具都没移植,那时你就看看老天,说声我怎么那么倒霉啊,客户可不想你动他花了n时间移植的内核哦

3 花了些功夫写了个新产品的驱动,挺有成就感啊,代码质量也是相当的有水准啊。正当你沉醉在你的代码中时,客服不断的邮件来了,“客户需要2.6.5内核的驱动,config文件我已经发你了” “客户需要双核的 2.6.18-smp 的驱动” “客户的平台是自己定制的是2.6.12-xxx “ 你恨不得把驱动的源代码给客户,这样省得编译了。你的一部分工作时间编译内核,定制驱动

有问题产生必然会有想办法解决问题的人, libusb的出现给我们带来了某些方便,即节约了我们的时间,也降低了公司的成本。 所以在一些情况下,就可以考虑使用libusb的无驱设计了。

下面我们就来详细讨论一下libusb, 并以写一个hid设备的驱动来讲解如何运用libusb,至于文章中涉及的usb协议的知识,限于篇幅,就不详细讲解了,相关的可自行查看usb相关协议。

一 libusb 介绍

libusb 设计了一系列的外部API 为应用程序所调用,通过这些API应用程序可以操作硬件,从libusb的源代码可以看出,这些API 调用了内核的底层接口,和kernel driver中所用到的函数所实现的功能差不多,只是libusb更加接近USB 规范。使得libusb的使用也比开发内核驱动相对容易的多。

Libusb 的编译安装请查看Readme,这里不做详解

二 libusb 的外部接口

2.1 初始化设备接口

这些接口也可以称为核心函数,它们主要用来初始化并寻找相关设备。

usb_init

函数定义: void usb_init(void);

从函数名称可以看出这个函数是用来初始化相关数据的,这个函数大家只要记住必须调用就行了,而且是一开始就要调用的.

usb_find_busses

函数定义: int usb_find_busses(void);

寻找系统上的usb总线,任何usb设备都通过usb总线和计算机总线通信。进而和其他设备通信。此函数返回总线数。

usb_find_devices

函数定义: int usb_find_devices(void);

寻找总线上的usb设备,这个函数必要在调用usb_find_busses()后使用。以上的三个函数都是一开始就要用到的,此函数返回设备数量。

usb_get_busses

函数定义: struct usb_bus *usb_get_busses(void);

这个函数返回总线的列表,在高一些的版本中已经用不到了,这在下面的实例中会有讲解

2.2 操作设备接口

 usb_open

函数定义: usb_dev_handle *usb_open(struct *usb_device dev);

打开要使用的设备,在对硬件进行操作前必须要调用usb_open 来打开设备,这里大家看到有两个结构体 usb_dev_handle 和 usb_device 是我们在开发中经常碰到的,有必要把它们的结构看一看。在libusb 中的usb.h和usbi.h中有定义。

这里我们不妨理解为返回的 usb_dev_handle 指针是指向设备的句柄,而行参里输入就是需要打开的设备。

usb_close

函数定义: int usb_close(usb_dev_handle *dev);

与usb_open相对应,关闭设备,是必须调用的, 返回0成功,<0 失败。

usb_set_configuration

函数定义: int usb_set_configuration(usb_dev_handle *dev, int configuration);

设置当前设备使用的configuration,参数configuration 是你要使用的configurtation descriptoes中的bConfigurationValue, 返回0成功,<0失败( 一个设备可能包含多个configuration,比如同时支持高速和低速的设备就有对应的两个configuration,详细可查看usb标准)

usb_set_altinterface

函数定义: int usb_set_altinterface(usb_dev_handle *dev, int alternate);

和名字的意思一样,此函数设置当前设备配置的interface descriptor,参数alternate是指interface descriptor中的bAlternateSetting。返回0成功,<0失败

usb_resetep

函数定义: int usb_resetep(usb_dev_handle *dev, unsigned int ep);

复位指定的endpoint,参数ep 是指bEndpointAddress,。这个函数不经常用,被下面介绍的usb_clear_halt函数所替代。

usb_clear_halt

函数定义: int usb_clear_halt (usb_dev_handle *dev, unsigned int ep);

复位指定的endpoint,参数ep 是指bEndpointAddress。这个函数用来替代usb_resetep

usb_reset

函数定义: int usb_reset(usb_dev_handle *dev);

这个函数现在基本不怎么用,不过这里我也讲一下,和名字所起的意思一样,这个函数reset设备,因为重启设备后还是要重新打开设备,所以用usb_close就已经可以满足要求了。

usb_claim_interface

函数定义: int usb_claim_interface(usb_dev_handle *dev, int interface);

注册与操作系统通信的接口,这个函数必须被调用,因为只有注册接口,才能做相应的操作。

Interface 指 bInterfaceNumber. (下面介绍的usb_release_interface 与之相对应,也是必须调用的函数)

usb_release_interface

函数定义: int usb_release_interface(usb_dev_handle *dev, int interface);

注销被usb_claim_interface函数调用后的接口,释放资源,和usb_claim_interface对应使用。

2.3 控制传输接口

usb_control_msg

函数定义:int usb_control_msg(usb_dev_handle *dev, int requesttype, int request, int value, int index, char *bytes, int size, int timeout);

从默认的管道发送和接受控制数据

usb_get_string

函数定义: int usb_get_string(usb_dev_handle *dev, int index, int langid, char *buf, size_t buflen);

 usb_get_string_simple

函数定义: int usb_get_string_simple(usb_dev_handle *dev, int index, char *buf, size_t buflen);

usb_get_descriptor

函数定义: int usb_get_descriptor(usb_dev_handle *dev, unsigned char type, unsigned char index, void *buf, int size);

usb_get_descriptor_by_endpoint

函数定义: int usb_get_descriptor_by_endpoint(usb_dev_handle *dev, int ep, unsigned char type, unsigned char index, void *buf, int size);

2.4 批传输接口

usb_bulk_write

函数定义: int usb_bulk_write(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout);

 usb_interrupt_read

函数定义: int usb_interrupt_read(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout);

2.5 中断传输接口

usb_bulk_write

函数定义: int usb_bulk_write(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout);

usb_interrupt_read

函数定义: int usb_interrupt_read(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout);

基本上libusb所经常用到的函数就有这些了,和usb协议确实很接近吧。下面我们实例在介绍一个应用。

//----------------===================================

3 Libusb库的使用

使用libusb之前你的linux系统必须装有usb文件系统,这里还介绍了使用hiddev设备文件来访问设备,目的在于不仅可以比较出usb的易用性,还提供了一个转化成libusb驱动的案例。

3.1 find设备

任何驱动第一步首先是寻找到要操作的设备,我们先来看看HID驱动是怎样寻找到设备的。我们假设寻找设备的函数Device_Find(注:代码只是为了方便解说,不保证代码的健全)

/* 我们简单看一下使用hid驱动寻找设备的实现,然后在看一下libusb是如何寻找设备的 */
int Device_Find()
{
    char dir_str[100];   /* 这个变量我们用来保存设备文件的目录路径 */
    char hiddev[100];    /* 这个变量用来保存设备文件的全路径 */
DIR dir;              
/* 申请的字符串数组清空,这个编程习惯要养成 */
memset (dir_str, 0 , sizeof(dir_str));
memset (hiddev, 0 , sizeof(hiddev));
    /* hiddev 的设备描述符不在/dev/usb/hid下面,就在/dev/usb 下面
这里我们使用opendir函数来检验目录的有效性
打开目录返回的值保存在变量dir里,dir前面有声明
*/
dir=opendir("/dev/usb/hid");
    if(dir){
        /* 程序运行到这里,说明存在 /dev/usb/hid 路径的目录 */
        sprintf(dir_str,"/dev/usb/hid/");
        closedir(dir);
    }else{
        /* 如果不存在hid目录,那么设备文件就在/dev/usb下 */
        sprintf(dir_str,"/dev/usb/");
    }
    /* DEVICE_MINOR 是指设备数,HID一般是16个 */
for(i = 0; i < DEVICE_MINOR; i++) {
    /* 获得全路径的设备文件名,一般hid设备文件名是hiddev0 到 hiddev16 */
        sprintf(hiddev, "%shiddev%d", dir_str,i);
       /* 打开设备文件,获得文件句柄 */
       fd = open(hiddev, O_RDWR);
       if(fd > 0) {
           /* 操作设备获得设备信息 */
          ioctl(fd, HIDIOCGDEVINFO, &info);
   
              /* VENDOR_ID 和 PRODUCT_ID 是标识usb设备厂家和产品ID,驱动都需要这两个参数来寻找设备,到此我们寻找到了设备 */
           if(info.vendor== VENDOR_ID && info.product== PRODUCT_ID) {
                /* 这里添加设备的初始化代码 */
                  
               device_num++;   /* 找到的设备数 */
           }
           close(fd);
       }
    }
    return device_num;         /* 返回寻找的设备数量 */
}

我们再来看libusb是如何来寻找和初始化设备

int Device_Find()
{
struct usb_bus             *busses;
    int                           device_num = 0;
    device_num = 0;       /* 记录设备数量 */
   
    usb_init();            /* 初始化 */
    usb_find_busses();   /* 寻找系统上的usb总线 */
    usb_find_devices(); /* 寻找usb总线上的usb设备 */
   
    /* 获得系统总线链表的句柄 */
busses = usb_get_busses();
    struct usb_bus       *bus;
    /* 遍历总线 */
    for (bus = busses; bus; bus = bus->next) {
        struct usb_device *dev;
        /* 遍历总线上的设备 */
        for (dev = bus->devices; dev; dev = dev->next) {
           /* 寻找到相关设备, */
if(dev->descriptor.idVendor==VENDOR_ID&& dev->descriptor.idProduct == PRODUCT_ID) {
                /* 这里添加设备的初始化代码 */
                  
               device_num++;   /* 找到的设备数 */
}              
        }       
    }
    return device_num;        /* 返回设备数量 */
}

注:在新版本的libusb中,usb_get_busses就可以不用了 ,这个函数是返回系统上的usb总线链表句柄
这里我们直接用usb_busses变量,这个变量在usb.h中被定义为外部变量
所以可以直接写成这样:

struct usb_bus    *bus;
        for (bus = usb_busses; bus; bus = bus->next) {
               struct usb_device *dev;
        for (dev = bus->devices; dev; dev = dev->next) {
           /* 这里添加设备的初始化代码 */
        }
}

3.2 打开设备

假设我们定义的打开设备的函数名是device_open,

/* 使用hid驱动打开设备 */
int Device_Open()
{
    int handle;
    /* 传统HID驱动调用,通过open打开设备文件就可 */
handle = open(“hiddev0”, O_RDONLY);
}
/* 使用libusb打开驱动 */
int Device_Open()
{
/* LIBUSB 驱动打开设备,这里写的是伪代码,不保证代码有用 */
struct usb_device*    udev;
usb_dev_handle*        device_handle;
/* 当找到设备后,通过usb_open打开设备,这里的函数就相当open 函数 */
device_handle = usb_open(udev);
}

3.3 读写设备和操作设备

假设我们的设备使用控制传输方式,至于批处理传输和中断传输限于篇幅这里不介绍
我们这里定义三个函数,Device_Write, Device_Read, Device_Report
Device_Report 功能发送接收函数
Device_Write 功能写数据
Device_Read 功能读数据
Device_WriteDevice_Read调用Device_Report发送写的信息和读的信息,开发者根据发送的命令协议来设计,我们这里只简单实现发送数据的函数。
假设我们要给设备发送72字节的数据,头8个字节是报告头,是我们定义的和设备相关的规则,后64位是数据。
HID驱动的实现(这里只是用代码来有助理解,代码是伪代码)

int Device_Report(int fd, unsigned char *buffer72)
{
int       ret; /* 保存ioctl函数的返回值 */
int      index;
    unsigned char send_data[72]; /* 发送的数据 */
unsigned char recv_data[72]; /* 接收的数据 */
    struct hiddev_usage_ref uref; /* hid驱动定义的数据包 */
    struct hiddev_report_info rinfo; /* hid驱动定义的
    memset(send_data, 0, sizeof(send_data));
memset(recv_data, 0, sizeof(recv_data));
    memcpy(send_data, buffer72, 72);
   /* 这在发送数据之前必须调用的,初始化设备 */
    ret = ioctl(fd, HIDIOCINITREPORT, 0);
    if( ret !=0) {
        return NOT_OPENED_DEVICE;/* NOT_OPENED_DEVICE 属于自己定义宏 */
    }
    /* HID设备每次传输一个字节的数据包 */
    for(index = 0; index < 72; index++) {
        /* 设置发送数据的状态 */
    uref.report_type = HID_REPORT_TYPE_FEATURE;
    uref.report_id = HID_REPORT_ID_FIRST;
    uref.usage_index = index;
    uref.field_index = 0;
    uref.value = send_data[index];
    ioctl(fd, HIDIOCGUCODE, &uref);
    ret=ioctl(fd, HIDIOCSUSAGE, &uref);
    if(ret != 0 ){
           return UNKNOWN_ERROR;
    }
}
/* 发送数据 */
rinfo.report_type = HID_REPORT_TYPE_FEATURE;
rinfo.report_id = HID_REPORT_ID_FIRST;
rinfo.num_fields = 1;
ret=ioctl(fd, HIDIOCSREPORT, &rinfo);   /* 发送数据 */
if(ret != 0) {
        return WRITE_REPORT;
}
/* 接受数据 */
ret = ioctl(fd, HIDIOCINITREPORT, 0);
for(index = 0; index < 72; index++) {
    uref.report_type = HID_REPORT_TYPE_FEATURE;
    uref.report_id = HID_REPORT_ID_FIRST;
    uref.usage_index = index;
    uref.field_index = 0;
    ioctl(fd, HIDIOCGUCODE, &uref);
    ret = ioctl(fd, HIDIOCGUSAGE, &uref);
    if(ret != 0 ) {
        return UNKNOWN_ERROR;
    }
    recv_data[index] = uref.value;
}
memcpy(buffer72, recv_data, 72);
return SUCCESS;
}

libusb驱动的实现

int Device_Report(int fd, unsigned char *buffer72)
{
    /* 定义设备句柄 */
    usb_dev_handle* Device_handle;
   
    /* save the data of send and receive */
    unsigned char   send_data[72];
    unsigned char   recv_data[72];
   
    int              send_len;
    int             recv_len;
   
    /* 数据置空 */
    memset(send_data, 0 , sizeof(send_data));
    memset(recv_data, 0 , sizeof(recv_data));
   
    /* 这里的g_list是全局的数据变量,里面可以存储相关设备的所需信息,当然我们 也可以从函数形参中传输进来,设备的信息在打开设备时初始化,我们将在后面的总结中详细描述一下 */
    Device_handle = (usb_dev_handle*)(g_list[fd].device_handle);
    if (Device_handle == NULL) {
        return NOT_OPENED_DEVICE;
}
/* 这个函数前面已经说过,在操作设备前是必须调用的, 0是指用默认的设备 */
usb_claim_interface(Device_handle, 0);
/* 发送数据,所用到的宏定义在usb.h可以找到,我列出来大家看一下
        #define USB_ENDPOINT_OUT       0x00
       #define USB_TYPE_CLASS     (0x01 << 5)
       #define USB_RECIP_INTERFACE 0x01
      
       #define HID_REPORT_SET       0x09 */
send_len = usb_control_msg(Device_handle,
USB_ENDPOINT_OUT + USB_TYPE_CLASS + USB_RECIP_INTERFACE,
                               HID_REPORT_SET,
                               0x300,
                               0,
                               send_data, 72, USB_TIMEOUT);
/* 发送数据有错误 */
if (send_len < 0) {
        return WRITE_REPORT;
}
if (send_len != 72) {
        return send_len;
}
/* 接受数据
       #define USB_ENDPOINT_IN         0x80
       #define USB_TYPE_CLASS          (0x01 << 5)
       #define USB_RECIP_INTERFACE        0x01
       #define HID_REPORT_GET          0x01
    */
recv_len = usb_control_msg(Device_handle,
USB_ENDPOINT_IN + USB_TYPE_CLASS + USB_RECIP_INTERFACE,
                               HID_REPORT_GET,
                               0x300,
                                 0,
                               recv_data, 72, USB_TIMEOUT);
                                                   
    if (recv_len < 0) {
        printf("failed to retrieve report from USB device!\n");
        return READ_REPORT;
    }
   
    if (recv_len != 72) {
        return recv_len;
    }
   
   
    /* 和usb_claim_interface对应 */
    usb_release_interface(RY2_handle, 0);
    memcpy(buffer72, recv_data, 72);
return SUCCESS;
}

3.4 关闭设备

假设我们定义的关闭设备的函数名是Device_Close()

/* 使用hid驱动关闭设备 */
int Device_Close()
{
    int handle;
   
handle = open(“hiddev0”, O_RDONLY);
/* 传统HID驱动调用,通过close()设备文件就可 */
close( handle );
}
/* 使用libusb关闭驱动 */
int Device_Close()
{
/* LIBUSB 驱动打开设备,这里写的是伪代码,不保证代码有用 */
struct usb_device*    udev;
usb_dev_handle*        device_handle;
device_handle = usb_open(udev);
/* libusb库使用usb_close关闭程序 */
usb_close(device_handle);
}

libusb的驱动框架
前面我们看了些主要的libusb函数的使用,这里我们把前面的内容归纳下:
一般的驱动应该都包含如下接口:
Device_Find(); /* 寻找设备接口 /
Device_Open(); /
打开设备接口 /
Device_Write(); /
写设备接口 /
Device_Read(); /
读设备接口 /
Device_Close(); /
关闭设备接口 */
具体代码如下:

#include <usb.h>
/* usb.h这个头文件是要包括的,里面包含了必须要用到的数据结构 */
/* 我们将一个设备的属性用一个结构体来概括 */
typedef struct
{
    struct usb_device*    udev;
    usb_dev_handle*        device_handle;
    /* 这里可以添加设备的其他属性,这里只列出每个设备要用到的属性 */
} device_descript;
/* 用来设置传输数据的时间延迟 */
#define USB_TIMEOUT     10000
/* 厂家ID 和产品 ID */
#define VENDOR_ID    0xffff    
#define PRODUCT_ID   0xffff
/* 这里定义数组来保存设备的相关属性,DEVICE_MINOR可以设置能够同时操作的设备数量,用全局变量的目的在于方便保存属性 */
#define DEVICE_MINOR 16
int     g_num;
device_descript g_list[ DEVICE_MINOR ];
/* 我们写个设备先找到设备,并把相关信息保存在 g_list 中 */
int Device_Find()
{
    struct usb_bus       *bus;
    struct usb_device *dev;
    g_num = 0;
    usb_find_busses();
    usb_find_devices();
   
    /* 寻找设备 */
    for (bus = usb_busses; bus; bus = bus->next) {
        for (dev = bus->devices; dev; dev = dev->next) {
if(dev->descriptor.idVendor==VENDOR_ID&& dev->descriptor.idProduct == PRODUCT_ID) {
                    /* 保存设备信息 */
                    if (g_num < DEVICE_MINOR) {
                     g_list[g_num].udev = dev;  
                     g_num ++;
                     }              
            }       
        }
    }
   
    return g_num;
}
/* 找到设备后,我们根据信息打开设备 */
int Device_Open()
{
    /* 根据情况打开你所需要操作的设备,这里我们仅列出伪代码 */
    if(g_list[g_num].udev != NULL) {
        g_list[g_num].device_handle = usb_open(g_list[g_num].udev);
}
}
/* 下面就是操作设备的函数了,我们就不列出来拉,大家可以参考上面的介绍 */
int DeviceWite(int handle)
{
    /* 填写相关代码,具体查看设备协议*/
}
int DeviceOpen(int handle)
{
    /* 填写相关代码,具体查看设备协议 */
}
/* 最后不要忘记关闭设备 */
void Device_close(int handle)
{
    /* 调用usb_close */
}
  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
libusb1.0学习(一) 首先声明,这是看到国外论坛上的学习文章后,独立翻译过来作为笔记用,加入部分自我理解,并且全部原创。 介绍: libusb是一个开源库,可以帮助开发者在用户空间的层面上与UBS设备进行通讯。如果想了解更多,可以查看他们的主页:http://libusb.org/ 在其文档中,建议首先阅读USB2的规格说明:http://www.usb.org/developers/docs/,这可以帮助真正地了解USB是如何工作的。 libusb的安装: 你可以从官方的主页上获取源代码,并且编译安装。或者使用的发行版已经包含了软件包,可以很方便地安装。 如果已经安装完毕,请继续往下 通讯: 设备和客户端之间的通讯是个清楚的概念叫做使用管道。每个管道都是一个主机上的一个软件和设备上一个端点的通道。每个端点对于设备来说完成一部分特殊的目标,比如接受命令或者传输数据。一个全速设备最高可以拥有16个端点,然后低速的设备只拥有三个端点。 所有的USB设备当供电时都支持端口0。这个端口是默认的目标管道。当设备连接被检测到后,USBD软件会使用端口0来初始化设备,执行普通的(非特殊)配置,并且获得有设备提供的其他端点的信息。端点是以他们的端点数目(取决于设计的时间),总线宽带,访问频率,延迟和处理错误要求为特征区分的。 一旦设备里的端点识别并且配置完毕,管道就产生允许客户端软件与设备进行通讯。跟一个管道产生联系是以对总线的访问和带宽,传输的类型,传输的方向和最大数据负载大小为描述特征的。 USB定义了四种传输方式:控制传输,通常用来传输命令和状态操作;中断传输,通过设备初始化一些来自主机的请求;同步传输,用来传输投递关键事件的数据(比如视频和对话);批量传输,使用全部可以用的带宽但不是特定时间的。所有的数传使用相同格式的包装,包括控制信息,数据和错误效验区域。 这里有两种管道:消息管道和流管道。控制传输是使用消息管道。在消息管道中,在每个包中的数据部分对于USB系统软件是有意义的。 流管道被中断传输,同步传输和批量传输使用。在流管道中,在每个包中的数据部分对于USB是没有意义,仅仅在客户端软件和设备间传输。 同步接口: 同步接口允许你使用单独一个函数调用一个USB传输。当这个函数调用返回时,这个传输也已经完成并且返回结果供解析用。这种方式的优点是十分清晰的:你可以通过一个简单的函数调用做任何事。 尽管如此,这个接口还是有它的局限性。你的程序会进入休眠当在libusb_bulk_transfer()(当进行批量传输),直到传输完成。假如这需要花费三个小时,你的程序同样需要休眠同样的时间。实现将会在库里面结束,整体线程这期间是无用的。另一个问题是,当一个单独的传输线程结束,这里不存在可能多个端点和多个设备同时地进行I/O操作,除非你借助创造新的线程处理。另外的,当请求被提交后,这里没有机会可能取消传输。 设备和接口: 在libusb中,每个USB设备通过libusb_device和libusb_device_handle对象操作。libusb API 连接一个打开的设备至特定的接口。这意味着如果你在设备上请求多个接口,你必须同样多次打开设备来接受一个libusb_dev_handle,对应每个你想进行通讯的接口。不要忘记调用libusb_dev_handle。 这些意味着什么?这意味你在设备上操作以前,可以完成请求接口,同样,你可以在完成设备操作前,先释放接口。 每个设备都有自己独属的配置,比如vendor id,product id等。我们使用这些设置去发现需求的设备,并且通过这些配置来工作。首先我们写一个函数来查明这些配置并且打印出来,以便我们找到正确的一个;我们基本的操作如下: 1.通过调用libusb_init来初始化库,同时创建一个对话; 2.调用libusb_get_device_list来获得已经连接的设备的队列。这会创建一个libusb_device的数组,包含了所有连接到系统上的usb设备; 3.循环遍历所有的设备来检查他们的选项; 4.发现其中需要的一个,使用libusb_open或者libusb_open_device_with_vid_pid(当你知道这个设备vendor id和product id)来打开设备; 5.使用libusb_free_device_list清除使用libusb_get_device_list获得的队列; 6.通过libusb_claim_interface请求接口(需要你知道设备的接口数值); 7.操作想得到的I/O; 8.通过libusb_release_interface释放设备; 9.通过libusb_close将你之前打开的设备关闭; 10.通过libusb_exit来关闭对话; PS:英文需要苦练啊,一篇短的教程文章看的结结巴巴的 libusb1.0学习(二) 接学习一,学习二主要是看例程 ok,现在最简单的想法看看有多少信息包含在你的设备里,程序代码如下 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 #include <iostream> #include <libusb.h> using namespace std; void printdev(libusb_device *dev); //prototype of the function int main() { libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices libusb_context *ctx = NULL; //a libusb session int r; //for return values ssize_t cnt; //holding number of devices in list r = libusb_init(&ctx;); //initialize a library session if(r < 0) { cout<<"Init Error "<<r<<endl; //there was an error return 1; } libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation cnt = libusb_get_device_list(ctx, &devs;); //get the list of devices if(cnt < 0) { cout<<"Get Device Error"<<endl; //there was an error } cout<<cnt<<" Devices in list."<<endl; //print total number of usb device ssize_t i; //for iterating through the list for(i = 0; i < cnt; i++) { printdev(devs[i]); //print specs of this device } libusb_free_device_list(devs, 1); //free the list, unref the devices in it libusb_exit(ctx); //close the session return 0; } void printdev(libusb_device *dev) { libusb_device_descriptor desc; int r = libusb_get_device_descriptor(dev, &desc;); if (r < 0) { cout<<"failed to get device descriptor"<<endl; return; } cout<<"Number of possible configurations: "<<(int)desc.bNumConfigurations<<" "; cout<<"Device Class: "<<(int)desc.bDeviceClass<<" "; cout<<"VendorID: "<<desc.idVendor<<" "; cout<<"ProductID: "<<desc.idProduct<<endl; libusb_config_descriptor *config; libusb_get_config_descriptor(dev, 0, &config;); cout<<"Interfaces: "<<(int)config->bNumInterfaces<<" ||| "; const libusb_interface *inter; const libusb_interface_descriptor *interdesc; const libusb_endpoint_descriptor *epdesc; for(int i=0; i<(int)config->bNumInterfaces; i++) { inter = &config;->interface[i]; cout<<"Number of alternate settings: "<<inter->num_altsetting<<" | "; for(int j=0; j<inter->num_altsetting; j++) { interdesc = &inter;->altsetting[j]; cout<<"Interface Number: "<<(int)interdesc->bInterfaceNumber<<" | "; cout<<"Number of endpoints: "<<(int)interdesc->bNumEndpoints<<" | "; for(int k=0; k<(int)interdesc->bNumEndpoints; k++) { epdesc = &interdesc;->endpoint[k]; cout<<"Descriptor Type: "<<(int)epdesc->bDescriptorType<<" | "; cout<<"EP Address: "<<(int)epdesc->bEndpointAddress<<" | "; } } } cout<<endl<<endl<<endl; libusb_free_config_descriptor(config); } 写完之后,编译看看会出现什么。首先运行程序并检查设备,然后连上我自己的设备在执行程序。会发现有新的内容出现,可以根据vendor id和product id发现这正是我自己连上打开的设备。 注意:发现设备(调用libusb_get_device_list())会返回新的内存分配的设备队列。当你完成这个队列的使用后必须释放他。 Libusb同样需要知道当一切完成时清除队列的内容;设备的本身。 为处理这些问题,libusb提供了两个单独的条目: 一个释放队列本身的函数 一个针对设备内部的参考计数系统 新的设备由libusb_get_device_list()函数展示,都拥有一个参考计数1。你可以使用libubs_ref_device()和libusb_unref_device()增加或减少参考计数。当一个设备的参考计数为0时,该设备就被销毁 通过以上的信息,打开设备的基本流程可以视为如下步骤: 1. 使用libusb_get_device_list()发现设备; 2. 选择你想操作的设备,调用libusb_open(); 3. 在设备队列中unref所有的设备; 4. 释放已经发现的设备队列; 这个次序是十分重要的,在尝试打开设备之前,你不能够unreference设备,因此unreference操作有可能导致设备的销毁。 为了方便起见,libusb_free_device_list()函数包含一个参数,在释放队列本身前,该参数能够选择性地在队列中unreference所有设备。这包含了以上的步骤3和步骤4。 如果还有需要,可以去libusb1’s API(http://libusb.sourceforge.net/api-1.0/index.html)文档参考你需要的函数。 好了,现在你可以找到你需要的设备了。现在是打开设备,请求并且执行一个简单的I/O。如果你知道vendor ID和prouct ID,使用libusb_open_device_with_vid_pid。 另外需要注意的,如果内核(你的OS)已经连接到这个设备,你将无法请求到它。在这种情况下,你需要调用libusb_detach_kernel_drive来从内核中检测设备。如果你想知道内核是否可用的,使用libusb_kernel_drive_active,如果返回值为1,对于你的设备内核可以加载驱动。 批量传输 为了在你的设备上使用批量传输,你应该获得为你的USB设备获得一个设备句柄,并且你应该知道使用哪个端点(从之前设备说明获得)。 关于语法上的信息参考这里(http://libusb.sourceforge.net/api-1.0/group__syncio.html#gab8ae853ab492c22d707241dc26c8a805) 这里有个简单的例子包含所有我提到的相关部分: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 #include <iostream> #include <libusb.h> using namespace std; int main() { libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices libusb_device_handle *dev_handle; //a device handle libusb_context *ctx = NULL; //a libusb session int r; //for return values ssize_t cnt; //holding number of devices in list r = libusb_init(&ctx;); //initialize the library for the session we just declared if(r < 0) { cout<<"Init Error "<<r<<endl; //there was an error return 1; } libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation cnt = libusb_get_device_list(ctx, &devs;); //get the list of devices if(cnt < 0) { cout<<"Get Device Error"<<endl; //there was an error return 1; } cout<<cnt<<" Devices in list."<<endl; dev_handle = libusb_open_device_with_vid_pid(ctx, 5118, 7424); //these are vendorID and productID I found for my usb device if(dev_handle == NULL) cout<<"Cannot open device"<<endl; else cout<<"Device Opened"<<endl; libusb_free_device_list(devs, 1); //free the list, unref the devices in it unsigned char *data = new unsigned char[4]; //data to write data[0]='a';data[1]='b';data[2]='c';data[3]='d'; //some dummy values int actual; //used to find out how many bytes were written if(libusb_kernel_driver_active(dev_handle, 0) == 1) { //find out if kernel driver is attached cout<<"Kernel Driver Active"<<endl; if(libusb_detach_kernel_driver(dev_handle, 0) == 0) //detach it cout<<"Kernel Driver Detached!"<<endl; } r = libusb_claim_interface(dev_handle, 0); //claim interface 0 (the first) of device (mine had jsut 1) if(r < 0) { cout<<"Cannot Claim Interface"<<endl; return 1; } cout<<"Claimed Interface"<<endl; cout<<"Data->"<<data<<"<-"<<endl; //just to see the data we want to write : abcd cout<<"Writing Data..."<<endl; r = libusb_bulk_transfer(dev_handle, (2 | LIBUSB_ENDPOINT_OUT), data, 4, &actual;, 0); //my device's out endpoint was 2, found with trial- the device had 2 endpoints: 2 and 129 if(r == 0 && actual == 4) //we wrote the 4 bytes successfully cout<<"Writing Successful!"<<endl; else cout<<"Write Error"<<endl; r = libusb_release_interface(dev_handle, 0); //release the claimed interface if(r!=0) { cout<<"Cannot Release Interface"<<endl; return 1; } cout<<"Released Interface"<<endl; libusb_close(dev_handle); //close the device we opened libusb_exit(ctx); //needs to be called to end the delete[] data; //delete the allocated memory for data return 0; } 结尾:这个教程对于这个话题来说是十分简单的介绍,需要时间需联系同步传输,然后移动是异步的,这还有很多需要学习。 希望这些对你的初学有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值