程式語言 - GNU - C/C++ - Read Data from USB HID



main.c

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <linux/hidraw.h>
#include <linux/input.h>
#include <linux/types.h>

static uint32_t get_ticks(void)
{
    struct timeval tv = {0};
    static struct timeval init_tv = {0};

    gettimeofday(&tv, 0);
    if (init_tv.tv_sec == 0) {
        init_tv = tv;
    }
    return ((tv.tv_sec - init_tv.tv_sec) * 1000000) + tv.tv_usec - init_tv.tv_usec;
}

int main(int argc, char **argv)
{
    uint8_t buf[255] = {0};
    struct hidraw_devinfo info = {0};
    int fd = -1, x = 0, r = 0, desc_size = 0;
    struct hidraw_report_descriptor rpt_desc = {0};

    fd = open("/dev/hidraw3", O_RDWR);
    if (fd < 0) {
        printf("failed to open device\n");
        return -1;
    }

    ioctl(fd, HIDIOCGRDESCSIZE, &desc_size);
    rpt_desc.size = desc_size;
    ioctl(fd, HIDIOCGRDESC, &rpt_desc);
    ioctl(fd, HIDIOCGRAWNAME(sizeof(buf)), buf);
    ioctl(fd, HIDIOCGRAWPHYS(sizeof(buf)), buf);
    ioctl(fd, HIDIOCGRAWINFO, &info);

    buf[0] = 0x9;
    buf[1] = 0xff;
    buf[2] = 0xff;
    buf[3] = 0xff;
    ioctl(fd, HIDIOCSFEATURE(4), buf);

    buf[0] = 0x9;
    ioctl(fd, HIDIOCGFEATURE(sizeof(buf)), buf);

    get_ticks();
    for (x = 0; x < 1000; x++) {
        r = read(fd, buf, 64);
        if (r == 64) {
            for (int x = 0; x < 64; x++) {
                printf("%04d, ", (uint8_t)buf[x]);
            }
            printf("\n");
        }
    }
    printf("elapsed time: %dus\n", get_ticks());
    close(fd);
    return 0;
}