linux下的用libusb读写自定义HID设备

本来是帮朋友写个RFID读写器设备的程序,最开始没要求USB接口,半路加了这个功能。而且windows版的早都完成了,Linux版的迟迟未做。今天终于抽空将Linux下的usb通信调通,特此记录一下。

使用libusb做linux下的通信的调试过程大概如下:

1、使用命令行工具lsusb,查看当前设备的通信端点的通信方式。lsusb -v后,在Endpoint中的Transfer Type可以看到,我用的这个设备的通信方式为interrupt,中断模式。

2、使用lsusb查看输出端点和输入端点,记录端点号。一般情况为,写设备为0x01(朋友的设备为0x02),读设备为0x81.

3、查看输出缓冲区的大小,在写设备时会用到---绊在这块时间比较久。

完成了上述三点就可以进行编程了,事例代码如下:

#include <string.h>
#include <stdio.h>
#include <libusb-1.0/libusb.h>

static libusb_device_handle *dev_handle = NULL; 

int main() {
    int i = 0;
    int ret = 1;
    int transferred = 0;
    ssize_t cnt;  
    unsigned char cmd[64] = {0x5A, 0x00, 0x01, 0x02, 0x10, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x01, 0xF4, 0x87};    // 64为上述第3步获取到的缓冲区大小

    struct libusb_device_descriptor desc;  
    libusb_device **devs; 

    libusb_context *ctx = NULL;   

    ret = libusb_init(NULL);  
    if(ret < 0) {
        fprintf(stderr, "failed to initialise libusb\n");
        return 1;    
    }

    dev_handle = libusb_open_device_with_vid_pid(NULL, 0x03eb, 0x2421);
    if(dev_handle == NULL){
    	perror("Cannot open device\n");
    }else{
        printf("Device Opened\n");
    }

	if(libusb_kernel_driver_active(dev_handle, 0) == 1) {  
		printf("Kernel Driver Active\n");
		if(libusb_detach_kernel_driver(dev_handle, 0) == 0){ 
			printf("Kernel Driver Detached!\n");
		}
	}   

	ret = libusb_claim_interface(dev_handle, 0); 
	if(ret < 0) {
		perror("Cannot Claim Interface\n");
		return 1;
	}

    ret = libusb_interrupt_transfer(dev_handle, 0x02, cmd, sizeof(cmd), &transferred, 0);
    if(ret==0 && transferred==sizeof(cmd_ir_start)){
        printf("write Successful!\n");
    }else{
        printf("write error!\n");
    }

	char buf[1024] = {0};
	ret = libusb_interrupt_transfer(dev_handle, 0x81, buf, sizeof(buf), &transferred, 0);
	if (ret != 0) {
		printf("failed to read \n");
	}

    ret = libusb_release_interface(dev_handle, 0);
    if(ret != 0){
        printf("Cannot Released Interface!\n");
    }else{
        printf("Released Interface!\n");
    }
   
    libusb_close(dev_handle); 
    libusb_exit(ctx);  

    return 0;
}

  

posted @ 2020-04-19 19:49  太极者  阅读(5103)  评论(0编辑  收藏  举报