HID是一种USB通信协议,无需安装驱动就能进行交互
内核打开hid配置如下
menuconfig > Device Drivers > USB support > USB Gadget Support > <M> HID Gadget
ko加载
insmod usb_f_hid.ko
insmod g_hid.ko hid_mode='key' #支持键盘
insmod g_hid.ko hid_mode='mouse' #支持鼠标
insmod g_hid.ko hid_mode='composite' #支持键盘/鼠标
demo
/*a~z,A~Z通过usb循环回显到host端*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <poll.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#define DevName "/dev/hidg0"
static int key_fd = -1;
static int g_bExit = 0;
#define DELAY_WAIT_TIME(); usleep(100*1000);
static int Hid_Send_OneGBKEnglish(const unsigned char charactor)
{
int offset = 0;
static unsigned char charBase = 0x04; /* A or a */
unsigned char keyType = 0;
unsigned char report[8] = {0};
if(charactor >= 'a' && charactor <= 'z')
{
keyType = 0;
offset = charactor - 'a';
}
else if(charactor >= 'A' && charactor <= 'Z')
{
keyType = 0x02;
offset = charactor - 'A';
}
else
{
printf("[fun:%s - Line:%d]unable to support charactor:0x%02x\n", __FUNCTION__, __LINE__, charactor);
}
memset(report, 0, 8);
report[0] = 0x00;
report[2] = 0x00;
write(key_fd, report, 8);
memset(report, 0, 8);
report[0] = keyType;
report[2] = charBase + offset;
write(key_fd, report, 8);
memset(report, 0, 8);
report[0] = keyType;
report[2] = 0x00;
write(key_fd, report, 8);
memset(report, 0, 8);
report[0] = 0x00;
report[2] = 0x00;
write(key_fd, report, 8);
DELAY_WAIT_TIME();
return 0;
}
static int Hid_Send_Enter()
{
unsigned char report[8] = {0};
memset(report, 0, 8);
report[0] = 0x00;
report[2] = 0x28;
write(key_fd, report, 8);
memset(report, 0, 8);
report[0] = 0x00;
report[2] = 0x00;
write(key_fd, report, 8);
DELAY_WAIT_TIME();
return 0;
}
static int Hid_Send_Space()
{
unsigned char report[8] = {0};
memset(report, 0, 8);
report[0] = 0x00;
report[2] = 0x2C;
write(key_fd, report, 8);
memset(report, 0, 8);
report[0] = 0x00;
report[2] = 0x00;
write(key_fd, report, 8);
DELAY_WAIT_TIME();
return 0;
}
void HandleSig(signed int signo)
{
if (signo == SIGINT)
{
printf("catch Ctrl + C, exit normally\n");
g_bExit = 1;
}
}
extern void HandleSig(signed int signo);
int main(int argc, char *argv[])
{
unsigned char charactor;
struct sigaction sigAction;
sigAction.sa_handler = HandleSig;
sigemptyset(&sigAction.sa_mask);
sigAction.sa_flags = 0;
sigaction(SIGINT, &sigAction, NULL);
key_fd = open("/dev/hidg0", O_RDWR, 0666);
if (key_fd<0)
{
printf("error\n");
return -1;
}
while(!g_bExit)
{
charactor = 'a';
while(charactor <= 'z')
{
Hid_Send_OneGBKEnglish(charactor++);
Hid_Send_Space();
}
Hid_Send_Enter();
charactor = 'A';
while(charactor <= 'Z')
{
Hid_Send_OneGBKEnglish(charactor++);
Hid_Send_Space();
}
Hid_Send_Enter();
}
close(key_fd);
return 0;
}