http://blog.chinaunix.net/uid-20543183-id-1930836.html
- read(): This is the event interface. When the HID device performs an interrupt transfer, indicating a change of state, data will be made available at the associated hiddev device with the content of a struct hiddev_event:struct hiddev_event { unsigned hid; signed int value; };containing the HID usage identifier for the status that changed, and the value that it was changed to.
- ioctl(): This is the control interface. There are a number of controls:
HIDIOCGVERSION int (read) Gets the version code out of the hiddev driver. HIDIOCAPPLICATION (none) This ioctl call returns the HID application usage associated with the hid device. The third argument to ioctl() specifies which application index to get. This is useful when the device has more than one application collection. If the index is invalid (greater or equal to the number of application collections this device has) the ioctl returns -1. You can find out beforehand how many application collections the device has from the num_applications field from the hiddev_devinfo structure. HIDIOCGDEVINFO struct hiddev_devinfo (read) Gets a hiddev_devinfo structure which describes the device. HIDIOCGSTRING struct struct hiddev_string_descriptor (read/write) Gets a string descriptor from the device. The caller must fill in the "index" field to indicate which descriptor should be returned. HIDIOCINITREPORT Instructs the kernel to retrieve all input and feature report values from the device. At this point, all the usage structures will contain current values for the device, and will maintain it as the device changes. HIDIOCGNAME string (variable length) Gets the device name HIDIOCGREPORT struct hiddev_report_info (write) Instructs the kernel to get a feature or input report from the device, in order to selectively update the usage structures (in contrast to INITREPORT). HIDIOCSREPORT struct hiddev_report_info (write) Instructs the kernel to send a report to the device. This report can be filled in by the user throughHIDIOCSUSAGE calls (below) to fill in individual usage values in the report before sending the report in full to the device. HIDIOCGREPORTINFO struct hiddev_report_info (read/write) Fills in a hiddev_report_info structure for the user. The report is looked up by type (input, output or feature) and id, so these fields must be filled in by the user. The ID can be absolute -- the actual report id as reported by the device -- or relative -- HID_REPORT_ID_FIRST for the first report, and (HID_REPORT_ID_NEXT | report_id) for the next report after report_id. Without a-priori information about report ids, the right way to use this ioctl is to use the relative IDs above to enumerate the valid IDs. The ioctl returns non-zero when there is no more next ID. The real report ID is filled into the returned hiddev_report_info structure. HIDIOCGFIELDINFO struct hiddev_field_info (read/write) Returns the field information associated with a report in a hiddev_field_info structure. The user must fill in report_id and report_type in this structure, as above. The field_index should also be filled in, which should be a number from 0 and maxfield-1, as returned from a previous HIDIOCGREPORTINFO call. HIDIOCGUCODE struct hiddev_usage_ref (read/write) Returns the usage_code in a hiddev_usage_ref structure, given that given its report type, report id, field index, and index within the field have already been filled into the structure. HIDIOCGUSAGE struct hiddev_usage_ref (read/write) Returns the value of a usage in a hiddev_usage_ref structure. The usage to be retrieved can be specified as above, or the user can choose to fill in the report_type field and specify the report_id asHID_REPORT_ID_UNKNOWN. In this case, the hiddev_usage_ref will be filled in with the report and field infomation associated with this usage if it is found. HIDIOCSUSAGE struct hiddev_usage_ref (write) Sets the value of a usage in an output report.
Linux 2.6內核中包含了HID驅動,能夠自動把USB Key等HID外設識別成“/dev/hiddev0”之類的設備。但是該驅動沒有實現write接口,因此無法象Windows平台那樣使用 ReadFile和WriteFile來讀寫HID設備,而只能使用ioctl接口。
網上有各種各樣讀寫HID設備的源代碼例子,有的是通過HIDIOCSUSAGE和HIDIOCGUSAGE來每次收發4個字節,適合鼠標、鍵盤之類數據傳輸量小的設備;有的是通過HIDIOCSUSAGES和HIDIOCGUSAGES來連續接收和發送多個字節,適合USB Key一類的設備。
在上一篇日志(已刪除)中,介紹了如何利用《USB and PIC: quick guide to an USB HID framework》一文提供的方法與USB Key進行通信(先發送HIDIOCSUSAGES和HIDIOCSREPORT進行寫操作,再發送HIDIOCGREPORT和HIDIOCGUSAGES進行讀操作,從而完成一次通信過程)。但是經過好友測試,發現該方法不論是在PC機上,還是在Cavium Octeon 52XX開發板上均存在問題,讀出的數據始終是第一次通信的結果,除非在每次通信之前都發送HIDIOCINITREPORT控制碼,但這又會造成相當長時間的阻塞。
進一步的測試表明,如果按照HIDIOCGUCODE、HIDIOCSUSAGES、HIDIOCSREPORT、HIDIOCGUCODE、HIDIOCGUSAGES的順序發送控制碼,那么可以每次都讀出正確數據。不過該方法雖然在PC機上只需400毫秒延時,但是在Octeon開發板上仍會長時間阻塞在usbhid_wait_io函數那里。
無奈之下,我只好根據Cavium SDK自帶的Linux內核源碼中的usb_skeleton.c寫了一個USB設備驅動程序,試圖通過直接讀寫USB端點來完成通信過程。以下是在開發和調試過程中需要注意的幾個問題:
首先,必須卸載Linux內核自帶的HID驅動,否則它會自動“接管”新插入的USB Key,導致我們自己編寫的驅動程序找不到設備。對於開發板,可以在編譯內核時去掉HID相關的選項;對於PC機上已經安裝好的Linux,我也不知道該怎么卸載其中的HID驅動。
其次,端點類型。在usb_skeleton.c中是通過bulk端點來訪問USB設備的,而USB Key作為HID設備,一般只有0號控制端點和一個中斷輸入端點(例如3號)。對於中斷端點,可以用usb_interrupt_msg(其實就是usb_bulk_msg)函數進行訪問;對於控制端點,則稍微麻煩一些,因為除了數據,還需要構造一個8字節的setup包。有關setup包的詳細結構,可以參考USB和HID規范。獲取setup包具體數值最簡單的方法,就是在Windows環境下用BusHound觀察USB Key的通信過程。
最后,關於Report ID。在Windows環境下通過ReadFile和WriteFile訪問HID設備時,必須在數據開頭附加1字節的Report ID(一般為0)。在Linux環境下,如果使用HID驅動的ioctl接口,那么需要在hiddev_usage_ref結構中指定Report ID;如果使用自己編寫的USB驅動程序,則不需要考慮Report ID,直接發送數據就得了。
經過測試,利用自己編寫的驅動程序,可以在Octeon開發板上正確讀寫HID類型的USB Key,而且讀寫之間的時間間隔也可以縮短至50毫秒。
write: Broken pipe
在內核 2.6.35以后進行了修正, 參考如下:
https://patchwork.kernel.org/patch/99990/
點擊(此處)折疊或打開
- diff --git a/drivers/hid/usbhid/hid-core.c b/drivers/hid/usbhid/hid-core.c
- index 56d06cd..6fd833d 100644
- --- a/drivers/hid/usbhid/hid-core.c
- +++ b/drivers/hid/usbhid/hid-core.c
- static int usbhid_output_raw_report(struct hid_device *hid, __u8 *buf, size_t count,
- unsigned char report_type)
- {
- struct usbhid_device *usbhid = hid->driver_data;
- struct usb_device *dev = hid_to_usb_dev(hid);
- struct usb_interface *intf = usbhid->intf;
- struct usb_host_interface *interface = intf->cur_altsetting;
- int ret;
- - ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
- - HID_REQ_SET_REPORT,
- - USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
- - ((report_type + 1) << 8) | *buf,
- - interface->desc.bInterfaceNumber, buf + 1, count - 1,
- - USB_CTRL_SET_TIMEOUT);
- -
- - /* count also the report id */
- - if (ret > 0)
- - ret++;
- + if (usbhid->urbout) {
- + int actual_length;
- + int skipped_report_id = 0;
- + if (buf[0] == 0x0) {
- + /* Don't send the Report ID */
- + buf++;
- + count--;
- + skipped_report_id = 1;
- + }
- + ret = usb_interrupt_msg(dev, usbhid->urbout->pipe,
- + buf, count, &actual_length,
- + USB_CTRL_SET_TIMEOUT);
- + /* return the number of bytes transferred */
- + if (ret == 0) {
- + ret = actual_length;
- + /* count also the report id */
- + if (skipped_report_id)
- + ret++;
- + }
- + } else {
- + ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
- + HID_REQ_SET_REPORT,
- + USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
- + ((report_type + 1) << 8) | *buf,
- + interface->desc.bInterfaceNumber, buf + 1, count - 1,
- + USB_CTRL_SET_TIMEOUT);
- + /* count also the report id */
- + if (ret > 0)
- + ret++;
- + }
- return ret;
- }
點擊(此處)折疊或打開
- /*
- * Hidraw Userspace Example
- *
- * Copyright (c) 2010 Alan Ott <alan@signal11.us>
- * Copyright (c) 2010 Signal 11 Software
- *
- * The code may be used by anyone for any purpose,
- * and can serve as a starting point for developing
- * applications using hidraw.
- */
- /* Linux */
- #include <linux/types.h>
- #include <linux/input.h>
- #include <linux/hidraw.h>
- /*
- * Ugly hack to work around failing compilation on systems that don't
- * yet populate new version of hidraw.h to userspace.
- *
- * If you need this, please have your distro update the kernel headers.
- */
- #ifndef HIDIOCSFEATURE
- #define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
- #define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len)
- #endif
- /* Unix */
- #include <sys/ioctl.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- /* C */
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <errno.h>
- const char *bus_str(int bus);
- int main(int argc, char **argv)
- {
- int fd;
- int i, res, desc_size = 0;
- char buf[256];
- struct hidraw_report_descriptor rpt_desc;
- struct hidraw_devinfo info;
- /* Open the Device with non-blocking reads. In real life,
- don't use a hard coded path; use libudev instead. */
- fd = open("/dev/hidraw0", O_RDWR|O_NONBLOCK);
- if (fd < 0) {
- perror("Unable to open device");
- return 1;
- }
- memset(&rpt_desc, 0x0, sizeof(rpt_desc));
- memset(&info, 0x0, sizeof(info));
- memset(buf, 0x0, sizeof(buf));
- /* Get Report Descriptor Size */
- res = ioctl(fd, HIDIOCGRDESCSIZE, &desc_size);
- if (res < 0)
- perror("HIDIOCGRDESCSIZE");
- else
- printf("Report Descriptor Size: %d\n", desc_size);
- /* Get Report Descriptor */
- rpt_desc.size = desc_size;
- res = ioctl(fd, HIDIOCGRDESC, &rpt_desc);
- if (res < 0) {
- perror("HIDIOCGRDESC");
- } else {
- printf("Report Descriptor:\n");
- for (i = 0; i < rpt_desc.size; i++)
- printf("%hhx ", rpt_desc.value[i]);
- puts("\n");
- }
- /* Get Raw Name */
- res = ioctl(fd, HIDIOCGRAWNAME(256), buf);
- if (res < 0)
- perror("HIDIOCGRAWNAME");
- else
- printf("Raw Name: %s\n", buf);
- /* Get Physical Location */
- res = ioctl(fd, HIDIOCGRAWPHYS(256), buf);
- if (res < 0)
- perror("HIDIOCGRAWPHYS");
- else
- printf("Raw Phys: %s\n", buf);
- /* Get Raw Info */
- res = ioctl(fd, HIDIOCGRAWINFO, &info);
- if (res < 0) {
- perror("HIDIOCGRAWINFO");
- } else {
- printf("Raw Info:\n");
- printf("\tbustype: %d (%s)\n",
- info.bustype, bus_str(info.bustype));
- printf("\tvendor: 0x%04hx\n", info.vendor);
- printf("\tproduct: 0x%04hx\n", info.product);
- }
- /* Set Feature */
- buf[0] = 0x9; /* Report Number */
- buf[1] = 0xff;
- buf[2] = 0xff;
- buf[3] = 0xff;
- res = ioctl(fd, HIDIOCSFEATURE(4), buf);
- if (res < 0)
- perror("HIDIOCSFEATURE");
- else
- printf("ioctl HIDIOCGFEATURE returned: %d\n", res);
- /* Get Feature */
- buf[0] = 0x9; /* Report Number */
- res = ioctl(fd, HIDIOCGFEATURE(256), buf);
- if (res < 0) {
- perror("HIDIOCGFEATURE");
- } else {
- printf("ioctl HIDIOCGFEATURE returned: %d\n", res);
- printf("Report data (not containing the report number):\n\t");
- for (i = 0; i < res; i++)
- printf("%hhx ", buf[i]);
- puts("\n");
- }
- /* Send a Report to the Device */
- buf[0] = 0x1; /* Report Number */
- buf[1] = 0x77;
- res = write(fd, buf, 2);
- if (res < 0) {
- printf("Error: %d\n", errno);
- perror("write");
- } else {
- printf("write() wrote %d bytes\n", res);
- }
- /* Get a report from the device */
- res = read(fd, buf, 16);
- if (res < 0) {
- perror("read");
- } else {
- printf("read() read %d bytes:\n\t", res);
- for (i = 0; i < res; i++)
- printf("%hhx ", buf[i]);
- puts("\n");
- }
- close(fd);
- return 0;
- }
- const char *
- bus_str(int bus)
- {
- switch (bus) {
- case BUS_USB:
- return "USB";
- break;
- case BUS_HIL:
- return "HIL";
- break;
- case BUS_BLUETOOTH:
- return "Bluetooth";
- break;
- case BUS_VIRTUAL:
- return "Virtual";
- break;
- default:
- return "Other";
- break;
- }
- }
點擊(此處)折疊或打開
- #if 1
- ucNeedSend = 1;
- Pos = HID_OFFSET_LENGTH + 1;
- #if 0
- ucSendData = 64;
- for (i=0; i<ucSendData-2; i++)
- SendBuffer[i+Pos] = 0x70 + i;
- #else
- ucSendData = RcvBuffer[HID_OFFSET_LENGTH];
- for (i=0; i<ucSendData-2; i++)
- SendBuffer[i+Pos] = RcvBuffer[i+Pos];
- #endif
- if (ucNeedSend) {
- /* SendBuffer format
- 1st byte : ID_SEND_HID_RESPONSE
- 2nd byte : repply or error code flag
- 3rd byte : nb byte
- others bytes: data
- #define HID_SEND_HID_RESPONSE 0x07
- #define HID_OFFSET 0x00
- #define HID_OFFSET_CMDCODE HID_OFFSET + 1
- #define HID_OFFSET_LENGTH HID_OFFSET + 2
- */
- SendBuffer[HID_OFFSET] = HID_SEND_HID_RESPONSE;
- //SendBuffer[HID_OFFSET_LENGTH] = MIN(HID_MAX_BUFFER_SIZE, SendBuffer[HID_OFFSET_LENGTH]);
- SendBuffer[HID_OFFSET_LENGTH] = ucSendData;
- /* Allows the transmission */
- SetEPTxStatus(ENDP3, EP_TX_VALID);
- USB_SIL_Write(EP3_IN, SendBuffer, HID_MAX_BUFFER_SIZE);
- }