Read and write custom HID device with libusb under linux

Originally it was a program to help a friend to write an RFID reader device. At first, the USB interface was not required, and this function was added halfway. And the windows version has been completed, the Linux version has not been done. Today, I finally have time to tune the USB communication under Linux, and hereby record it.

The debugging process of using libusb for communication under Linux is probably as follows:

1. Use the command line tool lsusb to view the communication method of the communication endpoint of the current device. After lsusb -v, you can see in the Transfer Type in Endpoint, the communication method of this device I use is interrupt, interrupt mode.

2. Use lsusb to view the output endpoint and input endpoint, and record the endpoint number. In general, the writing device is 0x01 (the friend's device is 0x02), and the reading device is 0x81.

3. Check the size of the output buffer, it will be used when writing to the device --- It takes a long time to stumble.

After completing the above three points, you can program. The case code is as follows:

#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;
}

  

Guess you like

Origin www.cnblogs.com/youyipin/p/12733125.html