【Qt】Linux HID API

来源:互联网 发布:约维蒂奇 知乎 编辑:程序博客网 时间:2024/04/28 15:42

Linux下HID可以使用libusb与hidapi结合,我是将hidapi略作修改变成一个自己的interface,以下在Qt中使用。


1、首先编译libusb(这里是libusb-1.0.21),本机直接make install --prefix=$(pwd)/_libusb,交叉编译需要设定对应编译器。

2、复制libusb.h和libusb的动态库(.so)和静态库(.a)到自己建立的文件夹,例如hidapi,我这里建立了三个平台的库,并且使用静态库。

3、使用修改hidapi的Qt程序如下,hidapi.h和hid-libusb.c从hidapi中提取修改,hidinterface为再封装的代码,其中可以自行修改PIC和VID,main的c为使用实例:


a) .pro文件

[cpp] view plain copy
  1. QT -= core  
  2. QT -= gui  
  3.   
  4. CONFIG += c++11  
  5.   
  6. TARGET = HIDAPI  
  7. CONFIG += console  
  8. CONFIG -= app_bundle  
  9.   
  10. TEMPLATE = app  
  11.   
  12. SOURCES += \  
  13.     hidlib/hid-libusb.c \  
  14.     hidlib/hidinterface.c \  
  15.     main.c  
  16.   
  17.   
  18. HEADERS += \  
  19.     hidlib/hidapi.h \  
  20.     hidlib/hidinterface.h  
  21.   
  22. #static  
  23.   
  24. message("$$myPlatform compile")  
  25. INCLUDEPATH += 
    PWD/lib/
    myPlatform/libusb/include/libusb-1.0/  
  26. LIBS += 
    PWD/lib/
    myPlatform/libusb/lib/libusb-1.0.a  


b) hidapi.h

[cpp] view plain copy
  1. /******************************************************* 
  2.  HIDAPI - Multi-Platform library for 
  3.  communication with HID devices. 
  4.  
  5.  Alan Ott 
  6.  Signal 11 Software 
  7.  
  8.  8/22/2009 
  9.  
  10.  Copyright 2009, All Rights Reserved. 
  11.  
  12.  At the discretion of the user of this library, 
  13.  this software may be licensed under the terms of the 
  14.  GNU Public License v3, a BSD-Style license, or the 
  15.  original HIDAPI license as outlined in the LICENSE.txt, 
  16.  LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt 
  17.  files located at the root of the source distribution. 
  18.  These files may also be found in the public source 
  19.  code repository located at: 
  20.         http://github.com/signal11/hidapi . 
  21. ********************************************************/  
  22.   
  23. /** @file 
  24.  * @defgroup API hidapi API 
  25.  */  
  26.   
  27. #ifndef HIDAPI_H__  
  28. #define HIDAPI_H__  
  29.   
  30. #include <wchar.h>  
  31.   
  32. #ifdef _WIN32  
  33.       #define HID_API_EXPORT __declspec(dllexport)  
  34.       #define HID_API_CALL  
  35. #else  
  36.       #define HID_API_EXPORT /**< API export macro */  
  37.       #define HID_API_CALL /**< API call macro */  
  38. #endif  
  39.   
  40. #define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/  
  41.   
  42. #ifdef __cplusplus  
  43. extern "C" {  
  44. #endif  
  45.         struct hid_device_;  
  46.         typedef struct hid_device_ hid_device; /**< opaque hidapi structure */  
  47.   
  48.         /** hidapi info structure */  
  49.         struct hid_device_info {  
  50.             /** Platform-specific device path */  
  51.             char *path;  
  52.             /** Device Vendor ID */  
  53.             unsigned short vendor_id;  
  54.             /** Device Product ID */  
  55.             unsigned short product_id;  
  56.             /** Serial Number */  
  57.             wchar_t *serial_number;  
  58.             /** Device Release Number in binary-coded decimal, 
  59.                 also known as Device Version Number */  
  60.             unsigned short release_number;  
  61.             /** Manufacturer String */  
  62.             wchar_t *manufacturer_string;  
  63.             /** Product string */  
  64.             wchar_t *product_string;  
  65.             /** Usage Page for this Device/Interface 
  66.                 (Windows/Mac only). */  
  67.             unsigned short usage_page;  
  68.             /** Usage for this Device/Interface 
  69.                 (Windows/Mac only).*/  
  70.             unsigned short usage;  
  71.             /** The USB interface which this logical device 
  72.                 represents. Valid on both Linux implementations 
  73.                 in all cases, and valid on the Windows implementation 
  74.                 only if the device contains more than one interface. */  
  75.             int interface_number;  
  76.   
  77.             /** Pointer to the next device */  
  78.             struct hid_device_info *next;  
  79.         };  
  80.   
  81.   
  82.         /** @brief Initialize the HIDAPI library. 
  83.  
  84.             This function initializes the HIDAPI library. Calling it is not 
  85.             strictly necessary, as it will be called automatically by 
  86.             hid_enumerate() and any of the hid_open_*() functions if it is 
  87.             needed.  This function should be called at the beginning of 
  88.             execution however, if there is a chance of HIDAPI handles 
  89.             being opened by different threads simultaneously. 
  90.              
  91.             @ingroup API 
  92.  
  93.             @returns 
  94.                 This function returns 0 on success and -1 on error. 
  95.         */  
  96.         int HID_API_EXPORT HID_API_CALL hid_init(void);  
  97.   
  98.         /** @brief Finalize the HIDAPI library. 
  99.  
  100.             This function frees all of the static data associated with 
  101.             HIDAPI. It should be called at the end of execution to avoid 
  102.             memory leaks. 
  103.  
  104.             @ingroup API 
  105.  
  106.             @returns 
  107.                 This function returns 0 on success and -1 on error. 
  108.         */  
  109.         int HID_API_EXPORT HID_API_CALL hid_exit(void);  
  110.   
  111.         /** @brief Enumerate the HID Devices. 
  112.  
  113.             This function returns a linked list of all the HID devices 
  114.             attached to the system which match vendor_id and product_id. 
  115.             If @p vendor_id and @p product_id are both set to 0, then 
  116.             all HID devices will be returned. 
  117.  
  118.             @ingroup API 
  119.             @param vendor_id The Vendor ID (VID) of the types of device 
  120.                 to open. 
  121.             @param product_id The Product ID (PID) of the types of 
  122.                 device to open. 
  123.  
  124.             @returns 
  125.                 This function returns a pointer to a linked list of type 
  126.                 struct #hid_device, containing information about the HID devices 
  127.                 attached to the system, or NULL in the case of failure. Free 
  128.                 this linked list by calling hid_free_enumeration(). 
  129.         */  
  130.         struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);  
  131.   
  132.         /** @brief Free an enumeration Linked List 
  133.  
  134.             This function frees a linked list created by hid_enumerate(). 
  135.  
  136.             @ingroup API 
  137.             @param devs Pointer to a list of struct_device returned from 
  138.                       hid_enumerate(). 
  139.         */  
  140.         void  HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs);  
  141.   
  142.         /** @brief Open a HID device using a Vendor ID (VID), Product ID 
  143.             (PID) and optionally a serial number. 
  144.  
  145.             If @p serial_number is NULL, the first device with the 
  146.             specified VID and PID is opened. 
  147.  
  148.             @ingroup API 
  149.             @param vendor_id The Vendor ID (VID) of the device to open. 
  150.             @param product_id The Product ID (PID) of the device to open. 
  151.             @param serial_number The Serial Number of the device to open 
  152.                                (Optionally NULL). 
  153.  
  154.             @returns 
  155.                 This function returns a pointer to a #hid_device object on 
  156.                 success or NULL on failure. 
  157.         */  
  158.         HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number);  
  159.   
  160.         /** @brief Open a HID device by its path name. 
  161.  
  162.             The path name be determined by calling hid_enumerate(), or a 
  163.             platform-specific path name can be used (eg: /dev/hidraw0 on 
  164.             Linux). 
  165.  
  166.             @ingroup API 
  167.             @param path The path name of the device to open 
  168.  
  169.             @returns 
  170.                 This function returns a pointer to a #hid_device object on 
  171.                 success or NULL on failure. 
  172.         */  
  173.         HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path);  
  174.   
  175.         /** @brief Write an Output report to a HID device. 
  176.  
  177.             The first byte of @p data[] must contain the Report ID. For 
  178.             devices which only support a single report, this must be set 
  179.             to 0x0. The remaining bytes contain the report data. Since 
  180.             the Report ID is mandatory, calls to hid_write() will always 
  181.             contain one more byte than the report contains. For example, 
  182.             if a hid report is 16 bytes long, 17 bytes must be passed to 
  183.             hid_write(), the Report ID (or 0x0, for devices with a 
  184.             single report), followed by the report data (16 bytes). In 
  185.             this example, the length passed in would be 17. 
  186.  
  187.             hid_write() will send the data on the first OUT endpoint, if 
  188.             one exists. If it does not, it will send the data through 
  189.             the Control Endpoint (Endpoint 0). 
  190.  
  191.             @ingroup API 
  192.             @param device A device handle returned from hid_open(). 
  193.             @param data The data to send, including the report number as 
  194.                 the first byte. 
  195.             @param length The length in bytes of the data to send. 
  196.  
  197.             @returns 
  198.                 This function returns the actual number of bytes written and 
  199.                 -1 on error. 
  200.         */  
  201.         int  HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);  
  202.   
  203.         /** @brief Read an Input report from a HID device with timeout. 
  204.  
  205.             Input reports are returned 
  206.             to the host through the INTERRUPT IN endpoint. The first byte will 
  207.             contain the Report number if the device uses numbered reports. 
  208.  
  209.             @ingroup API 
  210.             @param device A device handle returned from hid_open(). 
  211.             @param data A buffer to put the read data into. 
  212.             @param length The number of bytes to read. For devices with 
  213.                 multiple reports, make sure to read an extra byte for 
  214.                 the report number. 
  215.             @param milliseconds timeout in milliseconds or -1 for blocking wait. 
  216.  
  217.             @returns 
  218.                 This function returns the actual number of bytes read and 
  219.                 -1 on error. 
  220.         */  
  221.         int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds);  
  222.   
  223.         /** @brief Read an Input report from a HID device. 
  224.  
  225.             Input reports are returned 
  226.             to the host through the INTERRUPT IN endpoint. The first byte will 
  227.             contain the Report number if the device uses numbered reports. 
  228.  
  229.             @ingroup API 
  230.             @param device A device handle returned from hid_open(). 
  231.             @param data A buffer to put the read data into. 
  232.             @param length The number of bytes to read. For devices with 
  233.                 multiple reports, make sure to read an extra byte for 
  234.                 the report number. 
  235.  
  236.             @returns 
  237.                 This function returns the actual number of bytes read and 
  238.                 -1 on error. 
  239.         */  
  240.         int  HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);  
  241.   
  242.         /** @brief Set the device handle to be non-blocking. 
  243.  
  244.             In non-blocking mode calls to hid_read() will return 
  245.             immediately with a value of 0 if there is no data to be 
  246.             read. In blocking mode, hid_read() will wait (block) until 
  247.             there is data to read before returning. 
  248.  
  249.             Nonblocking can be turned on and off at any time. 
  250.  
  251.             @ingroup API 
  252.             @param device A device handle returned from hid_open(). 
  253.             @param nonblock enable or not the nonblocking reads 
  254.              - 1 to enable nonblocking 
  255.              - 0 to disable nonblocking. 
  256.  
  257.             @returns 
  258.                 This function returns 0 on success and -1 on error. 
  259.         */  
  260.         int  HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock);  
  261.   
  262.         /** @brief Send a Feature report to the device. 
  263.  
  264.             Feature reports are sent over the Control endpoint as a 
  265.             Set_Report transfer.  The first byte of @p data[] must 
  266.             contain the Report ID. For devices which only support a 
  267.             single report, this must be set to 0x0. The remaining bytes 
  268.             contain the report data. Since the Report ID is mandatory, 
  269.             calls to hid_send_feature_report() will always contain one 
  270.             more byte than the report contains. For example, if a hid 
  271.             report is 16 bytes long, 17 bytes must be passed to 
  272.             hid_send_feature_report(): the Report ID (or 0x0, for 
  273.             devices which do not use numbered reports), followed by the 
  274.             report data (16 bytes). In this example, the length passed 
  275.             in would be 17. 
  276.  
  277.             @ingroup API 
  278.             @param device A device handle returned from hid_open(). 
  279.             @param data The data to send, including the report number as 
  280.                 the first byte. 
  281.             @param length The length in bytes of the data to send, including 
  282.                 the report number. 
  283.  
  284.             @returns 
  285.                 This function returns the actual number of bytes written and 
  286.                 -1 on error. 
  287.         */  
  288.         int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length);  
  289.   
  290.         /** @brief Get a feature report from a HID device. 
  291.  
  292.             Make sure to set the first byte of @p data[] to the Report 
  293.             ID of the report to be read.  Make sure to allow space for 
  294.             this extra byte in @p data[]. 
  295.  
  296.             @ingroup API 
  297.             @param device A device handle returned from hid_open(). 
  298.             @param data A buffer to put the read data into, including 
  299.                 the Report ID. Set the first byte of @p data[] to the 
  300.                 Report ID of the report to be read. 
  301.             @param length The number of bytes to read, including an 
  302.                 extra byte for the report ID. The buffer can be longer 
  303.                 than the actual report. 
  304.  
  305.             @returns 
  306.                 This function returns the number of bytes read and 
  307.                 -1 on error. 
  308.         */  
  309.         int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length);  
  310.   
  311.         /** @brief Close a HID device. 
  312.  
  313.             @ingroup API 
  314.             @param device A device handle returned from hid_open(). 
  315.         */  
  316.         void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device);  
  317.   
  318.         /** @brief Get The Manufacturer String from a HID device. 
  319.  
  320.             @ingroup API 
  321.             @param device A device handle returned from hid_open(). 
  322.             @param string A wide string buffer to put the data into. 
  323.             @param maxlen The length of the buffer in multiples of wchar_t. 
  324.  
  325.             @returns 
  326.                 This function returns 0 on success and -1 on error. 
  327.         */  
  328.         int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);  
  329.   
  330.         /** @brief Get The Product String from a HID device. 
  331.  
  332.             @ingroup API 
  333.             @param device A device handle returned from hid_open(). 
  334.             @param string A wide string buffer to put the data into. 
  335.             @param maxlen The length of the buffer in multiples of wchar_t. 
  336.  
  337.             @returns 
  338.                 This function returns 0 on success and -1 on error. 
  339.         */  
  340.         int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen);  
  341.   
  342.         /** @brief Get The Serial Number String from a HID device. 
  343.  
  344.             @ingroup API 
  345.             @param device A device handle returned from hid_open(). 
  346.             @param string A wide string buffer to put the data into. 
  347.             @param maxlen The length of the buffer in multiples of wchar_t. 
  348.  
  349.             @returns 
  350.                 This function returns 0 on success and -1 on error. 
  351.         */  
  352.         int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen);  
  353.   
  354.         /** @brief Get a string from a HID device, based on its string index. 
  355.  
  356.             @ingroup API 
  357.             @param device A device handle returned from hid_open(). 
  358.             @param string_index The index of the string to get. 
  359.             @param string A wide string buffer to put the data into. 
  360.             @param maxlen The length of the buffer in multiples of wchar_t. 
  361.  
  362.             @returns 
  363.                 This function returns 0 on success and -1 on error. 
  364.         */  
  365.         int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen);  
  366.   
  367.         /** @brief Get a string describing the last error which occurred. 
  368.  
  369.             @ingroup API 
  370.             @param device A device handle returned from hid_open(). 
  371.  
  372.             @returns 
  373.                 This function returns a string containing the last error 
  374.                 which occurred or NULL if none has occurred. 
  375.         */  
  376.         HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device);  
  377.   
  378. #ifdef __cplusplus  
  379. }  
  380. #endif  
  381.   
  382. #endif  


c) hidapi-libusb.c

[cpp] view plain copy
  1. /******************************************************* 
  2.  HIDAPI - Multi-Platform library for 
  3.  communication with HID devices. 
  4.  
  5.  Alan Ott 
  6.  Signal 11 Software 
  7.  
  8.  8/22/2009 
  9.  Linux Version - 6/2/2010 
  10.  Libusb Version - 8/13/2010 
  11.  
  12.  Copyright 2009, All Rights Reserved. 
  13.   
  14.  At the discretion of the user of this library, 
  15.  this software may be licensed under the terms of the 
  16.  GNU Public License v3, a BSD-Style license, or the 
  17.  original HIDAPI license as outlined in the LICENSE.txt, 
  18.  LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt 
  19.  files located at the root of the source distribution. 
  20.  These files may also be found in the public source 
  21.  code repository located at: 
  22.         http://github.com/signal11/hidapi . 
  23. ********************************************************/  
  24.   
  25. #define _GNU_SOURCE // needed for wcsdup() before glibc 2.10  
  26.   
  27. /* C */  
  28. #include <stdio.h>  
  29. #include <string.h>  
  30. #include <stdlib.h>  
  31. #include <ctype.h>  
  32. #include <locale.h>  
  33. #include <errno.h>  
  34.   
  35. /* Unix */  
  36. #include <unistd.h>  
  37. #include <sys/types.h>  
  38. #include <sys/stat.h>  
  39. #include <sys/ioctl.h>  
  40. #include <sys/utsname.h>  
  41. #include <fcntl.h>  
  42. #include <pthread.h>  
  43. #include <wchar.h>  
  44.   
  45. /* GNU / LibUSB */  
  46. #include <libusb.h>  
  47. #include "iconv.h"  
  48.   
  49. #include "hidapi.h"  
  50.   
  51. #ifdef __cplusplus  
  52. extern "C" {  
  53. #endif  
  54.   
  55. #ifdef DEBUG_PRINTF  
  56. #define LOG(...) fprintf(stderr, __VA_ARGS__)  
  57. #else  
  58. #define LOG(...) do {} while (0)  
  59. #endif  
  60.   
  61.   
  62. /* Uncomment to enable the retrieval of Usage and Usage Page in 
  63. hid_enumerate(). Warning, this is very invasive as it requires the detach 
  64. and re-attach of the kernel driver. See comments inside hid_enumerate(). 
  65. Linux/libusb HIDAPI programs are encouraged to use the interface number 
  66. instead to differentiate between interfaces on a composite HID device. */  
  67. /*#define INVASIVE_GET_USAGE*/  
  68.   
  69. /* Linked List of input reports received from the device. */  
  70. struct input_report {  
  71.     uint8_t *data;  
  72.     size_t len;  
  73.     struct input_report *next;  
  74. };  
  75.   
  76.   
  77. struct hid_device_ {  
  78.     /* Handle to the actual device. */  
  79.     libusb_device_handle *device_handle;  
  80.       
  81.     /* Endpoint information */  
  82.     int input_endpoint;  
  83.     int output_endpoint;  
  84.     int input_ep_max_packet_size;  
  85.   
  86.     /* The interface number of the HID */     
  87.     int interface;  
  88.       
  89.     /* Indexes of Strings */  
  90.     int manufacturer_index;  
  91.     int product_index;  
  92.     int serial_index;  
  93.       
  94.     /* Whether blocking reads are used */  
  95.     int blocking; /* boolean */  
  96.       
  97.     /* Read thread objects */  
  98.     pthread_t thread;  
  99.     pthread_mutex_t mutex; /* Protects input_reports */  
  100.     pthread_cond_t condition;  
  101.     pthread_barrier_t barrier; /* Ensures correct startup sequence */  
  102.     int shutdown_thread;  
  103.     struct libusb_transfer *transfer;  
  104.   
  105.     /* List of received input reports. */  
  106.     struct input_report *input_reports;  
  107. };  
  108.   
  109. static int initialized = 0;  
  110.   
  111. uint16_t get_usb_code_for_current_locale(void);  
  112. static int return_data(hid_device *dev, unsigned char *data, size_t length);  
  113.   
  114. static hid_device *new_hid_device(void)  
  115. {  
  116.     hid_device *dev = calloc(1, sizeof(hid_device));  
  117.     dev->device_handle = NULL;  
  118.     dev->input_endpoint = 0;  
  119.     dev->output_endpoint = 0;  
  120.     dev->input_ep_max_packet_size = 0;  
  121.     dev->interface = 0;  
  122.     dev->manufacturer_index = 0;  
  123.     dev->product_index = 0;  
  124.     dev->serial_index = 0;  
  125.     dev->blocking = 1;  
  126.     dev->shutdown_thread = 0;  
  127.     dev->transfer = NULL;  
  128.     dev->input_reports = NULL;  
  129.       
  130.     pthread_mutex_init(&dev->mutex, NULL);  
  131.     pthread_cond_init(&dev->condition, NULL);  
  132.     pthread_barrier_init(&dev->barrier, NULL, 2);  
  133.       
  134.     return dev;  
  135. }  
  136.   
  137. static void free_hid_device(hid_device *dev)  
  138. {  
  139.     /* Clean up the thread objects */  
  140.     pthread_barrier_destroy(&dev->barrier);  
  141.     pthread_cond_destroy(&dev->condition);  
  142.     pthread_mutex_destroy(&dev->mutex);  
  143.   
  144.     /* Free the device itself */  
  145.     free(dev);  
  146. }  
  147.   
  148. #if 0  
  149. //TODO: Implement this funciton on Linux.  
  150. static void register_error(hid_device *device, const char *op)  
  151. {  
  152.   
  153. }  
  154. #endif  
  155.   
  156. #ifdef INVASIVE_GET_USAGE  
  157. /* Get bytes from a HID Report Descriptor. 
  158.    Only call with a num_bytes of 0, 1, 2, or 4. */  
  159. static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)  
  160. {  
  161.     /* Return if there aren't enough bytes. */  
  162.     if (cur + num_bytes >= len)  
  163.         return 0;  
  164.   
  165.     if (num_bytes == 0)  
  166.         return 0;  
  167.     else if (num_bytes == 1) {  
  168.         return rpt[cur+1];  
  169.     }  
  170.     else if (num_bytes == 2) {  
  171.         return (rpt[cur+2] * 256 + rpt[cur+1]);  
  172.     }  
  173.     else if (num_bytes == 4) {  
  174.         return (rpt[cur+4] * 0x01000000 +  
  175.                 rpt[cur+3] * 0x00010000 +  
  176.                 rpt[cur+2] * 0x00000100 +  
  177.                 rpt[cur+1] * 0x00000001);  
  178.     }  
  179.     else  
  180.         return 0;  
  181. }  
  182.   
  183. /* Retrieves the device's Usage Page and Usage from the report 
  184.    descriptor. The algorithm is simple, as it just returns the first 
  185.    Usage and Usage Page that it finds in the descriptor. 
  186.    The return value is 0 on success and -1 on failure. */  
  187. static int get_usage(uint8_t *report_descriptor, size_t size,  
  188.                      unsigned short *usage_page, unsigned short *usage)  
  189. {  
  190.     int i = 0;  
  191.     int size_code;  
  192.     int data_len, key_size;  
  193.     int usage_found = 0, usage_page_found = 0;  
  194.       
  195.     while (i < size) {  
  196.         int key = report_descriptor[i];  
  197.         int key_cmd = key & 0xfc;  
  198.   
  199.         //printf("key: %02hhx\n", key);  
  200.           
  201.         if ((key & 0xf0) == 0xf0) {  
  202.             /* This is a Long Item. The next byte contains the 
  203.                length of the data section (value) for this key. 
  204.                See the HID specification, version 1.11, section 
  205.                6.2.2.3, titled "Long Items." */  
  206.             if (i+1 < size)  
  207.                 data_len = report_descriptor[i+1];  
  208.             else  
  209.                 data_len = 0; /* malformed report */  
  210.             key_size = 3;  
  211.         }  
  212.         else {  
  213.             /* This is a Short Item. The bottom two bits of the 
  214.                key contain the size code for the data section 
  215.                (value) for this key.  Refer to the HID 
  216.                specification, version 1.11, section 6.2.2.2, 
  217.                titled "Short Items." */  
  218.             size_code = key & 0x3;  
  219.             switch (size_code) {  
  220.             case 0:  
  221.             case 1:  
  222.             case 2:  
  223.                 data_len = size_code;  
  224.                 break;  
  225.             case 3:  
  226.                 data_len = 4;  
  227.                 break;  
  228.             default:  
  229.                 /* Can't ever happen since size_code is & 0x3 */  
  230.                 data_len = 0;  
  231.                 break;  
  232.             };  
  233.             key_size = 1;  
  234.         }  
  235.           
  236.         if (key_cmd == 0x4) {  
  237.             *usage_page  = get_bytes(report_descriptor, size, data_len, i);  
  238.             usage_page_found = 1;  
  239.             //printf("Usage Page: %x\n", (uint32_t)*usage_page);  
  240.         }  
  241.         if (key_cmd == 0x8) {  
  242.             *usage = get_bytes(report_descriptor, size, data_len, i);  
  243.             usage_found = 1;  
  244.             //printf("Usage: %x\n", (uint32_t)*usage);  
  245.         }  
  246.   
  247.         if (usage_page_found && usage_found)  
  248.             return 0; /* success */  
  249.           
  250.         /* Skip over this key and it's associated data */  
  251.         i += data_len + key_size;  
  252.     }  
  253.       
  254.     return -1; /* failure */  
  255. }  
  256. #endif // INVASIVE_GET_USAGE  
  257.   
  258.   
  259. /* Get the first language the device says it reports. This comes from 
  260.    USB string #0. */  
  261. static uint16_t get_first_language(libusb_device_handle *dev)  
  262. {  
  263.     uint16_t buf[32];  
  264.     int len;  
  265.       
  266.     /* Get the string from libusb. */  
  267.     len = libusb_get_string_descriptor(dev,  
  268.             0x0, /* String ID */  
  269.             0x0, /* Language */  
  270.             (unsigned char*)buf,  
  271.             sizeof(buf));  
  272.     if (len < 4)  
  273.         return 0x0;  
  274.       
  275.     return buf[1]; // First two bytes are len and descriptor type.  
  276. }  
  277.   
  278. static int is_language_supported(libusb_device_handle *dev, uint16_t lang)  
  279. {  
  280.     uint16_t buf[32];  
  281.     int len;  
  282.     int i;  
  283.       
  284.     /* Get the string from libusb. */  
  285.     len = libusb_get_string_descriptor(dev,  
  286.             0x0, /* String ID */  
  287.             0x0, /* Language */  
  288.             (unsigned char*)buf,  
  289.             sizeof(buf));  
  290.     if (len < 4)  
  291.         return 0x0;  
  292.       
  293.       
  294.     len /= 2; /* language IDs are two-bytes each. */  
  295.     /* Start at index 1 because there are two bytes of protocol data. */  
  296.     for (i = 1; i < len; i++) {  
  297.         if (buf[i] == lang)  
  298.             return 1;  
  299.     }  
  300.   
  301.     return 0;  
  302. }  
  303.   
  304.   
  305. /* This function returns a newly allocated wide string containing the USB 
  306.    device string numbered by the index. The returned string must be freed 
  307.    by using free(). */  
  308. static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)  
  309. {  
  310.     char buf[512];  
  311.     int len;  
  312.     wchar_t *str = NULL;  
  313.     wchar_t wbuf[256];  
  314.   
  315.     /* iconv variables */  
  316.     iconv_t ic;  
  317.     size_t inbytes;  
  318.     size_t outbytes;  
  319.     size_t res;  
  320.     char *inptr;  
  321.     char *outptr;  
  322.   
  323.     /* Determine which language to use. */  
  324.     uint16_t lang;  
  325.     lang = get_usb_code_for_current_locale();  
  326.     if (!is_language_supported(dev, lang))  
  327.         lang = get_first_language(dev);  
  328.           
  329.     /* Get the string from libusb. */  
  330.     len = libusb_get_string_descriptor(dev,  
  331.             idx,  
  332.             lang,  
  333.             (unsigned char*)buf,  
  334.             sizeof(buf));  
  335.     if (len < 0)  
  336.         return NULL;  
  337.       
  338.     buf[sizeof(buf)-1] = '\0';  
  339.       
  340.     if (len+1 < sizeof(buf))  
  341.         buf[len+1] = '\0';  
  342.       
  343.     /* Initialize iconv. */  
  344.     ic = iconv_open("UTF-32""UTF-16");  
  345.     if (ic == (iconv_t)-1)  
  346.         return NULL;  
  347.       
  348.     /* Convert to UTF-32 (wchar_t on glibc systems). 
  349.        Skip the first character (2-bytes). */  
  350.     inptr = buf+2;  
  351.     inbytes = len-2;  
  352.     outptr = (char*) wbuf;  
  353.     outbytes = sizeof(wbuf);  
  354.     res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);  
  355.     if (res == (size_t)-1)  
  356.         goto err;  
  357.   
  358.     /* Write the terminating NULL. */  
  359.     wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;  
  360.     if (outbytes >= sizeof(wbuf[0]))  
  361.         *((wchar_t*)outptr) = 0x00000000;  
  362.       
  363.     /* Allocate and copy the string. */  
  364.     str = wcsdup(wbuf+1);  
  365.   
  366. err:  
  367.     iconv_close(ic);  
  368.       
  369.     return str;  
  370. }  
  371.   
  372. static char *make_path(libusb_device *dev, int interface_number)  
  373. {  
  374.     char str[64];  
  375.     snprintf(str, sizeof(str), "%04x:%04x:%02x",  
  376.         libusb_get_bus_number(dev),  
  377.         libusb_get_device_address(dev),  
  378.         interface_number);  
  379.     str[sizeof(str)-1] = '\0';  
  380.       
  381.     return strdup(str);  
  382. }  
  383.   
  384.   
  385. int HID_API_EXPORT hid_init(void)  
  386. {  
  387.     if (!initialized) {  
  388.         if (libusb_init(NULL))  
  389.             return -1;  
  390.         initialized = 1;  
  391.     }  
  392.   
  393.     return 0;  
  394. }  
  395.   
  396. int HID_API_EXPORT hid_exit(void)  
  397. {  
  398.     if (initialized) {  
  399.         libusb_exit(NULL);  
  400.         initialized = 0;  
  401.     }  
  402.   
  403.     return 0;  
  404. }  
  405.   
  406. struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)  
  407. {  
  408.     libusb_device **devs;  
  409.     libusb_device *dev;  
  410.     libusb_device_handle *handle;  
  411.     ssize_t num_devs;  
  412.     int i = 0;  
  413.       
  414.     struct hid_device_info *root = NULL; // return object  
  415.     struct hid_device_info *cur_dev = NULL;  
  416.       
  417.     setlocale(LC_ALL,"");  
  418.       
  419.     if (!initialized)  
  420.         hid_init();  
  421.   
  422.     num_devs = libusb_get_device_list(NULL, &devs);  
  423.     if (num_devs < 0)  
  424.         return NULL;  
  425.     while ((dev = devs[i++]) != NULL) {  
  426.         struct libusb_device_descriptor desc;  
  427.         struct libusb_config_descriptor *conf_desc = NULL;  
  428.         int j, k;  
  429.         int interface_num = 0;  
  430.   
  431.         int res = libusb_get_device_descriptor(dev, &desc);  
  432.         unsigned short dev_vid = desc.idVendor;  
  433.         unsigned short dev_pid = desc.idProduct;  
  434.           
  435.         /* HID's are defined at the interface level. */  
  436.         if (desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE)  
  437.             continue;  
  438.   
  439.         res = libusb_get_active_config_descriptor(dev, &conf_desc);  
  440.         if (res < 0)  
  441.             libusb_get_config_descriptor(dev, 0, &conf_desc);  
  442.         if (conf_desc) {  
  443.             for (j = 0; j < conf_desc->bNumInterfaces; j++) {  
  444.                 const struct libusb_interface *intf = &conf_desc->interface[j];  
  445.                 for (k = 0; k < intf->num_altsetting; k++) {  
  446.                     const struct libusb_interface_descriptor *intf_desc;  
  447.                     intf_desc = &intf->altsetting[k];  
  448.                     if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {  
  449.                         interface_num = intf_desc->bInterfaceNumber;  
  450.   
  451.                         /* Check the VID/PID against the arguments */  
  452.                         if ((vendor_id == 0x0 && product_id == 0x0) ||  
  453.                             (vendor_id == dev_vid && product_id == dev_pid)) {  
  454.                             struct hid_device_info *tmp;  
  455.   
  456.                             /* VID/PID match. Create the record. */  
  457.                             tmp = calloc(1, sizeof(struct hid_device_info));  
  458.                             if (cur_dev) {  
  459.                                 cur_dev->next = tmp;  
  460.                             }  
  461.                             else {  
  462.                                 root = tmp;  
  463.                             }  
  464.                             cur_dev = tmp;  
  465.                               
  466.                             /* Fill out the record */  
  467.                             cur_dev->next = NULL;  
  468.                             cur_dev->path = make_path(dev, interface_num);  
  469.                               
  470.                             res = libusb_open(dev, &handle);  
  471.   
  472.                             if (res >= 0) {  
  473.                                 /* Serial Number */  
  474.                                 if (desc.iSerialNumber > 0)  
  475.                                     cur_dev->serial_number =  
  476.                                         get_usb_string(handle, desc.iSerialNumber);  
  477.   
  478.                                 /* Manufacturer and Product strings */  
  479.                                 if (desc.iManufacturer > 0)  
  480.                                     cur_dev->manufacturer_string =  
  481.                                         get_usb_string(handle, desc.iManufacturer);  
  482.                                 if (desc.iProduct > 0)  
  483.                                     cur_dev->product_string =  
  484.                                         get_usb_string(handle, desc.iProduct);  
  485.   
  486. #ifdef INVASIVE_GET_USAGE  
  487.                             /* 
  488.                             This section is removed because it is too 
  489.                             invasive on the system. Getting a Usage Page 
  490.                             and Usage requires parsing the HID Report 
  491.                             descriptor. Getting a HID Report descriptor 
  492.                             involves claiming the interface. Claiming the 
  493.                             interface involves detaching the kernel driver. 
  494.                             Detaching the kernel driver is hard on the system 
  495.                             because it will unclaim interfaces (if another 
  496.                             app has them claimed) and the re-attachment of 
  497.                             the driver will sometimes change /dev entry names. 
  498.                             It is for these reasons that this section is 
  499.                             #if 0. For composite devices, use the interface 
  500.                             field in the hid_device_info struct to distinguish 
  501.                             between interfaces. */  
  502.                                 int detached = 0;  
  503.                                 unsigned char data[256];  
  504.                               
  505.                                 /* Usage Page and Usage */  
  506.                                 res = libusb_kernel_driver_active(handle, interface_num);  
  507.                                 if (res == 1) {  
  508.                                     res = libusb_detach_kernel_driver(handle, interface_num);  
  509.                                     if (res < 0)  
  510.                                         LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");  
  511.                                     else  
  512.                                         detached = 1;  
  513.                                 }  
  514.                                 res = libusb_claim_interface(handle, interface_num);  
  515.                                 if (res >= 0) {  
  516.                                     /* Get the HID Report Descriptor. */  
  517.                                     res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);  
  518.                                     if (res >= 0) {  
  519.                                         unsigned short page=0, usage=0;  
  520.                                         /* Parse the usage and usage page 
  521.                                            out of the report descriptor. */  
  522.                                         get_usage(data, res,  &page, &usage);  
  523.                                         cur_dev->usage_page = page;  
  524.                                         cur_dev->usage = usage;  
  525.                                     }  
  526.                                     else  
  527.                                         LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);  
  528.   
  529.                                     /* Release the interface */  
  530.                                     res = libusb_release_interface(handle, interface_num);  
  531.                                     if (res < 0)  
  532.                                         LOG("Can't release the interface.\n");  
  533.                                 }  
  534.                                 else  
  535.                                     LOG("Can't claim interface %d\n", res);  
  536.   
  537.                                 /* Re-attach kernel driver if necessary. */  
  538.                                 if (detached) {  
  539.                                     res = libusb_attach_kernel_driver(handle, interface_num);  
  540.                                     if (res < 0)  
  541.                                         LOG("Couldn't re-attach kernel driver.\n");  
  542.                                 }  
  543. #endif /*******************/  
  544.   
  545.                                 libusb_close(handle);  
  546.                             }  
  547.                             /* VID/PID */  
  548.                             cur_dev->vendor_id = dev_vid;  
  549.                             cur_dev->product_id = dev_pid;  
  550.   
  551.                             /* Release Number */  
  552.                             cur_dev->release_number = desc.bcdDevice;  
  553.                               
  554.                             /* Interface Number */  
  555.                             cur_dev->interface_number = interface_num;  
  556.                         }  
  557.                     }  
  558.                 } /* altsettings */  
  559.             } /* interfaces */  
  560.             libusb_free_config_descriptor(conf_desc);  
  561.         }  
  562.     }  
  563.   
  564.     libusb_free_device_list(devs, 1);  
  565.   
  566.     return root;  
  567. }  
  568.   
  569. void  HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)  
  570. {  
  571.     struct hid_device_info *d = devs;  
  572.     while (d) {  
  573.         struct hid_device_info *next = d->next;  
  574.         free(d->path);  
  575.         free(d->serial_number);  
  576.         free(d->manufacturer_string);  
  577.         free(d->product_string);  
  578.         free(d);  
  579.         d = next;  
  580.     }  
  581. }  
  582.   
  583. hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, wchar_t *serial_number)  
  584. {  
  585.     struct hid_device_info *devs, *cur_dev;  
  586.     const char *path_to_open = NULL;  
  587.     hid_device *handle = NULL;  
  588.       
  589.     devs = hid_enumerate(vendor_id, product_id);  
  590.     cur_dev = devs;  
  591.     while (cur_dev) {  
  592.         if (cur_dev->vendor_id == vendor_id &&  
  593.             cur_dev->product_id == product_id) {  
  594.             if (serial_number) {  
  595.                 if (wcscmp(serial_number, cur_dev->serial_number) == 0) {  
  596.                     path_to_open = cur_dev->path;  
  597.                     break;  
  598.                 }  
  599.             }  
  600.             else {  
  601.                 path_to_open = cur_dev->path;  
  602.                 break;  
  603.             }  
  604.         }  
  605.         cur_dev = cur_dev->next;  
  606.     }  
  607.   
  608.     if (path_to_open) {  
  609.         /* Open the device */  
  610.         handle = hid_open_path(path_to_open);  
  611.     }  
  612.   
  613.     hid_free_enumeration(devs);  
  614.       
  615.     return handle;  
  616. }  
  617.   
  618. static void read_callback(struct libusb_transfer *transfer)  
  619. {  
  620.     hid_device *dev = transfer->user_data;  
  621.       
  622.     if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {  
  623.   
  624.         struct input_report *rpt = malloc(sizeof(*rpt));  
  625.         rpt->data = malloc(transfer->actual_length);  
  626.         memcpy(rpt->data, transfer->buffer, transfer->actual_length);  
  627.         rpt->len = transfer->actual_length;  
  628.         rpt->next = NULL;  
  629.   
  630.         pthread_mutex_lock(&dev->mutex);  
  631.   
  632.         /* Attach the new report object to the end of the list. */  
  633.         if (dev->input_reports == NULL) {  
  634.             /* The list is empty. Put it at the root. */  
  635.             dev->input_reports = rpt;  
  636.             pthread_cond_signal(&dev->condition);  
  637.         }  
  638.         else {  
  639.             /* Find the end of the list and attach. */  
  640.             struct input_report *cur = dev->input_reports;  
  641.             int num_queued = 0;  
  642.             while (cur->next != NULL) {  
  643.                 cur = cur->next;  
  644.                 num_queued++;  
  645.             }  
  646.             cur->next = rpt;  
  647.               
  648.             /* Pop one off if we've reached 30 in the queue. This 
  649.                way we don't grow forever if the user never reads 
  650.                anything from the device. */  
  651.             if (num_queued > 30) {  
  652.                 return_data(dev, NULL, 0);  
  653.             }             
  654.         }  
  655.         pthread_mutex_unlock(&dev->mutex);  
  656.     }  
  657.     else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {  
  658.         dev->shutdown_thread = 1;  
  659.         return;  
  660.     }  
  661.     else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {  
  662.         dev->shutdown_thread = 1;  
  663.         return;  
  664.     }  
  665.     else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {  
  666.         //LOG("Timeout (normal)\n");  
  667.     }  
  668.     else {  
  669.         LOG("Unknown transfer code: %d\n", transfer->status);  
  670.     }  
  671.       
  672.     /* Re-submit the transfer object. */  
  673.     libusb_submit_transfer(transfer);  
  674. }  
  675.   
  676.   
  677. static void *read_thread(void *param)  
  678. {  
  679.     hid_device *dev = param;  
  680.     unsigned char *buf;  
  681.     const size_t length = dev->input_ep_max_packet_size;  
  682.   
  683.     /* Set up the transfer object. */  
  684.     buf = malloc(length);  
  685.     dev->transfer = libusb_alloc_transfer(0);  
  686.     libusb_fill_interrupt_transfer(dev->transfer,  
  687.         dev->device_handle,  
  688.         dev->input_endpoint,  
  689.         buf,  
  690.         length,  
  691.         read_callback,  
  692.         dev,  
  693.         5000/*timeout*/);  
  694.       
  695.     /* Make the first submission. Further submissions are made 
  696.        from inside read_callback() */  
  697.     libusb_submit_transfer(dev->transfer);  
  698.   
  699.     // Notify the main thread that the read thread is up and running.  
  700.     pthread_barrier_wait(&dev->barrier);  
  701.       
  702.     /* Handle all the events. */  
  703.     while (!dev->shutdown_thread) {  
  704.         int res;  
  705.         res = libusb_handle_events(NULL);  
  706.         if (res < 0) {  
  707.             /* There was an error. Break out of this loop. */  
  708.             break;  
  709.         }  
  710.     }  
  711.       
  712.     /* Cancel any transfer that may be pending. This call will fail 
  713.        if no transfers are pending, but that's OK. */  
  714.     if (libusb_cancel_transfer(dev->transfer) == 0) {  
  715.         /* The transfer was cancelled, so wait for its completion. */  
  716.         libusb_handle_events(NULL);  
  717.     }  
  718.       
  719.     /* Now that the read thread is stopping, Wake any threads which are 
  720.        waiting on data (in hid_read_timeout()). Do this under a mutex to 
  721.        make sure that a thread which is about to go to sleep waiting on 
  722.        the condition acutally will go to sleep before the condition is 
  723.        signaled. */  
  724.     pthread_mutex_lock(&dev->mutex);  
  725.     pthread_cond_broadcast(&dev->condition);  
  726.     pthread_mutex_unlock(&dev->mutex);  
  727.   
  728.     /* The dev->transfer->buffer and dev->transfer objects are cleaned up 
  729.        in hid_close(). They are not cleaned up here because this thread 
  730.        could end either due to a disconnect or due to a user 
  731.        call to hid_close(). In both cases the objects can be safely 
  732.        cleaned up after the call to pthread_join() (in hid_close()), but 
  733.        since hid_close() calls libusb_cancel_transfer(), on these objects, 
  734.        they can not be cleaned up here. */  
  735.       
  736.     return NULL;  
  737. }  
  738.   
  739.   
  740. hid_device * HID_API_EXPORT hid_open_path(const char *path)  
  741. {  
  742.     hid_device *dev = NULL;  
  743.   
  744.     dev = new_hid_device();  
  745.   
  746.     libusb_device **devs;  
  747.     libusb_device *usb_dev;  
  748.     ssize_t num_devs;  
  749.     int res;  
  750.     int d = 0;  
  751.     int good_open = 0;  
  752.       
  753.     setlocale(LC_ALL,"");  
  754.       
  755.     if (!initialized)  
  756.         hid_init();  
  757.   
  758.     num_devs = libusb_get_device_list(NULL, &devs);  
  759.     while ((usb_dev = devs[d++]) != NULL) {  
  760.         struct libusb_device_descriptor desc;  
  761.         struct libusb_config_descriptor *conf_desc = NULL;  
  762.         int i,j,k;  
  763.         libusb_get_device_descriptor(usb_dev, &desc);  
  764.   
  765.         if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)  
  766.             continue;  
  767.         for (j = 0; j < conf_desc->bNumInterfaces; j++) {  
  768.             const struct libusb_interface *intf = &conf_desc->interface[j];  
  769.             for (k = 0; k < intf->num_altsetting; k++) {  
  770.                 const struct libusb_interface_descriptor *intf_desc;  
  771.                 intf_desc = &intf->altsetting[k];  
  772.                 if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {  
  773.                     char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);  
  774.                     if (!strcmp(dev_path, path)) {  
  775.                         /* Matched Paths. Open this device */  
  776.   
  777.                         // OPEN HERE //  
  778.                         res = libusb_open(usb_dev, &dev->device_handle);  
  779.                         if (res < 0) {  
  780.                             LOG("can't open device\n");  
  781.                             free(dev_path);  
  782.                             break;  
  783.                         }  
  784.                         good_open = 1;  
  785.                           
  786.                         /* Detach the kernel driver, but only if the 
  787.                            device is managed by the kernel */  
  788.                         if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {  
  789.                             res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);  
  790.                             if (res < 0) {  
  791.                                 libusb_close(dev->device_handle);  
  792.                                 LOG("Unable to detach Kernel Driver\n");  
  793.                                 free(dev_path);  
  794.                                 good_open = 0;  
  795.                                 break;  
  796.                             }  
  797.                         }  
  798.                           
  799.                         res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);  
  800.                         if (res < 0) {  
  801.                             LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);  
  802.                             free(dev_path);  
  803.                             libusb_close(dev->device_handle);  
  804.                             good_open = 0;  
  805.                             break;  
  806.                         }  
  807.   
  808.                         /* Store off the string descriptor indexes */  
  809.                         dev->manufacturer_index = desc.iManufacturer;  
  810.                         dev->product_index      = desc.iProduct;  
  811.                         dev->serial_index       = desc.iSerialNumber;  
  812.   
  813.                         /* Store off the interface number */  
  814.                         dev->interface = intf_desc->bInterfaceNumber;  
  815.                                                   
  816.                         /* Find the INPUT and OUTPUT endpoints. An 
  817.                            OUTPUT endpoint is not required. */  
  818.                         for (i = 0; i < intf_desc->bNumEndpoints; i++) {  
  819.                             const struct libusb_endpoint_descriptor *ep  
  820.                                 = &intf_desc->endpoint[i];  
  821.   
  822.                             /* Determine the type and direction of this 
  823.                                endpoint. */  
  824.                             int is_interrupt =  
  825.                                 (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)  
  826.                                   == LIBUSB_TRANSFER_TYPE_INTERRUPT;  
  827.                             int is_output =   
  828.                                 (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)  
  829.                                   == LIBUSB_ENDPOINT_OUT;  
  830.                             int is_input =   
  831.                                 (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)  
  832.                                   == LIBUSB_ENDPOINT_IN;  
  833.   
  834.                             /* Decide whether to use it for intput or output. */  
  835.                             if (dev->input_endpoint == 0 &&  
  836.                                 is_interrupt && is_input) {  
  837.                                 /* Use this endpoint for INPUT */  
  838.                                 dev->input_endpoint = ep->bEndpointAddress;  
  839.                                 dev->input_ep_max_packet_size = ep->wMaxPacketSize;  
  840.                             }  
  841.                             if (dev->output_endpoint == 0 &&  
  842.                                 is_interrupt && is_output) {  
  843.                                 /* Use this endpoint for OUTPUT */  
  844.                                 dev->output_endpoint = ep->bEndpointAddress;  
  845.                             }  
  846.                         }  
  847.                           
  848.                         pthread_create(&dev->thread, NULL, read_thread, dev);  
  849.                           
  850.                         // Wait here for the read thread to be initialized.  
  851.                         pthread_barrier_wait(&dev->barrier);  
  852.                           
  853.                     }  
  854.                     free(dev_path);  
  855.                 }  
  856.             }  
  857.         }  
  858.         libusb_free_config_descriptor(conf_desc);  
  859.   
  860.     }  
  861.   
  862.     libusb_free_device_list(devs, 1);  
  863.       
  864.     // If we have a good handle, return it.  
  865.     if (good_open) {  
  866.         return dev;  
  867.     }  
  868.     else {  
  869.         // Unable to open any devices.  
  870.         free_hid_device(dev);  
  871.         return NULL;  
  872.     }  
  873. }  
  874.   
  875.   
  876. int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)  
  877. {  
  878.     int res;  
  879.     int report_number = data[0];  
  880.     int skipped_report_id = 0;  
  881.   
  882.     if (report_number == 0x0) {  
  883.         data++;  
  884.         length--;  
  885.         skipped_report_id = 1;  
  886.     }  
  887.   
  888.   
  889.     if (dev->output_endpoint <= 0) {  
  890.         /* No interrput out endpoint. Use the Control Endpoint */  
  891.         res = libusb_control_transfer(dev->device_handle,  
  892.             LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,  
  893.             0x09/*HID Set_Report*/,  
  894.             (2/*HID output*/ << 8) | report_number,  
  895.             dev->interface,  
  896.             (unsigned char *)data, length,  
  897.             1000/*timeout millis*/);  
  898.           
  899.         if (res < 0)  
  900.             return -1;  
  901.           
  902.         if (skipped_report_id)  
  903.             length++;  
  904.           
  905.         return length;  
  906.     }  
  907.     else {  
  908.         /* Use the interrupt out endpoint */  
  909.         int actual_length;  
  910.         res = libusb_interrupt_transfer(dev->device_handle,  
  911.             dev->output_endpoint,  
  912.             (unsigned char*)data,  
  913.             length,  
  914.             &actual_length, 1000);  
  915.           
  916.         if (res < 0)  
  917.             return -1;  
  918.           
  919.         if (skipped_report_id)  
  920.             actual_length++;  
  921.           
  922.         return actual_length;  
  923.     }  
  924. }  
  925.   
  926. /* Helper function, to simplify hid_read(). 
  927.    This should be called with dev->mutex locked. */  
  928. static int return_data(hid_device *dev, unsigned char *data, size_t length)  
  929. {  
  930.     /* Copy the data out of the linked list item (rpt) into the 
  931.        return buffer (data), and delete the liked list item. */  
  932.     struct input_report *rpt = dev->input_reports;  
  933.     size_t len = (length < rpt->len)? length: rpt->len;  
  934.     if (len > 0)  
  935.         memcpy(data, rpt->data, len);  
  936.     dev->input_reports = rpt->next;  
  937.     free(rpt->data);  
  938.     free(rpt);  
  939.     return len;  
  940. }  
  941.   
  942. static void cleanup_mutex(void *param)  
  943. {  
  944.     hid_device *dev = param;  
  945.     pthread_mutex_unlock(&dev->mutex);  
  946. }  
  947.   
  948.   
  949. int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)  
  950. {  
  951.     int bytes_read = -1;  
  952.   
  953. #if 0  
  954.     int transferred;  
  955.     int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);  
  956.     LOG("transferred: %d\n", transferred);  
  957.     return transferred;  
  958. #endif  
  959.   
  960.     pthread_mutex_lock(&dev->mutex);  
  961.     pthread_cleanup_push(&cleanup_mutex, dev);  
  962.   
  963.     /* There's an input report queued up. Return it. */  
  964.     if (dev->input_reports) {  
  965.         /* Return the first one */  
  966.         bytes_read = return_data(dev, data, length);  
  967.         goto ret;  
  968.     }  
  969.       
  970.     if (dev->shutdown_thread) {  
  971.         /* This means the device has been disconnected. 
  972.            An error code of -1 should be returned. */  
  973.         bytes_read = -1;  
  974.         goto ret;  
  975.     }  
  976.       
  977.     if (milliseconds == -1) {  
  978.         /* Blocking */  
  979.         while (!dev->input_reports && !dev->shutdown_thread) {  
  980.             pthread_cond_wait(&dev->condition, &dev->mutex);  
  981.         }  
  982.         if (dev->input_reports) {  
  983.             bytes_read = return_data(dev, data, length);  
  984.         }  
  985.     }  
  986.     else if (milliseconds > 0) {  
  987.         /* Non-blocking, but called with timeout. */  
  988.         int res;  
  989.         struct timespec ts;  
  990.         clock_gettime(CLOCK_REALTIME, &ts);  
  991.         ts.tv_sec += milliseconds / 1000;  
  992.         ts.tv_nsec += (milliseconds % 1000) * 1000000;  
  993.         if (ts.tv_nsec >= 1000000000L) {  
  994.             ts.tv_sec++;  
  995.             ts.tv_nsec -= 1000000000L;  
  996.         }  
  997.           
  998.         while (!dev->input_reports && !dev->shutdown_thread) {  
  999.             res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);  
  1000.             if (res == 0) {  
  1001.                 if (dev->input_reports) {  
  1002.                     bytes_read = return_data(dev, data, length);  
  1003.                     break;  
  1004.                 }  
  1005.                   
  1006.                 /* If we're here, there was a spurious wake up 
  1007.                    or the read thread was shutdown. Run the 
  1008.                    loop again (ie: don't break). */  
  1009.             }  
  1010.             else if (res == ETIMEDOUT) {  
  1011.                 /* Timed out. */  
  1012.                 bytes_read = 0;  
  1013.                 break;  
  1014.             }  
  1015.             else {  
  1016.                 /* Error. */  
  1017.                 bytes_read = -1;  
  1018.                 break;  
  1019.             }  
  1020.         }  
  1021.     }  
  1022.     else {  
  1023.         /* Purely non-blocking */  
  1024.         bytes_read = 0;  
  1025.     }  
  1026.   
  1027. ret:  
  1028.     pthread_mutex_unlock(&dev->mutex);  
  1029.     pthread_cleanup_pop(0);  
  1030.   
  1031.     return bytes_read;  
  1032. }  
  1033.   
  1034. int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)  
  1035. {  
  1036.     return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);  
  1037. }  
  1038.   
  1039. int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)  
  1040. {  
  1041.     dev->blocking = !nonblock;  
  1042.       
  1043.     return 0;  
  1044. }  
  1045.   
  1046.   
  1047. int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)  
  1048. {  
  1049.     int res = -1;  
  1050.     int skipped_report_id = 0;  
  1051.     int report_number = data[0];  
  1052.   
  1053.     if (report_number == 0x0) {  
  1054.         data++;  
  1055.         length--;  
  1056.         skipped_report_id = 1;  
  1057.     }  
  1058.   
  1059.     res = libusb_control_transfer(dev->device_handle,  
  1060.         LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,  
  1061.         0x09/*HID set_report*/,  
  1062.         (3/*HID feature*/ << 8) | report_number,  
  1063.         dev->interface,  
  1064.         (unsigned char *)data, length,  
  1065.         1000/*timeout millis*/);  
  1066.       
  1067.     if (res < 0)  
  1068.         return -1;  
  1069.       
  1070.     /* Account for the report ID */  
  1071.     if (skipped_report_id)  
  1072.         length++;  
  1073.       
  1074.     return length;  
  1075. }  
  1076.   
  1077. int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)  
  1078. {  
  1079.     int res = -1;  
  1080.     int skipped_report_id = 0;  
  1081.     int report_number = data[0];  
  1082.   
  1083.     if (report_number == 0x0) {  
  1084.         /* Offset the return buffer by 1, so that the report ID 
  1085.            will remain in byte 0. */  
  1086.         data++;  
  1087.         length--;  
  1088.         skipped_report_id = 1;  
  1089.     }  
  1090.     res = libusb_control_transfer(dev->device_handle,  
  1091.         LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,  
  1092.         0x01/*HID get_report*/,  
  1093.         (3/*HID feature*/ << 8) | report_number,  
  1094.         dev->interface,  
  1095.         (unsigned char *)data, length,  
  1096.         1000/*timeout millis*/);  
  1097.       
  1098.     if (res < 0)  
  1099.         return -1;  
  1100.   
  1101.     if (skipped_report_id)  
  1102.         res++;  
  1103.       
  1104.     return res;  
  1105. }  
  1106.   
  1107.   
  1108. void HID_API_EXPORT hid_close(hid_device *dev)  
  1109. {  
  1110.     if (!dev)  
  1111.         return;  
  1112.       
  1113.     /* Cause read_thread() to stop. */  
  1114.     dev->shutdown_thread = 1;  
  1115.     libusb_cancel_transfer(dev->transfer);  
  1116.   
  1117.     /* Wait for read_thread() to end. */  
  1118.     pthread_join(dev->thread, NULL);  
  1119.       
  1120.     /* Clean up the Transfer objects allocated in read_thread(). */  
  1121.     free(dev->transfer->buffer);  
  1122.     libusb_free_transfer(dev->transfer);  
  1123.       
  1124.     /* release the interface */  
  1125.     libusb_release_interface(dev->device_handle, dev->interface);  
  1126.       
  1127.     /* Close the handle */  
  1128.     libusb_close(dev->device_handle);  
  1129.       
  1130.     /* Clear out the queue of received reports. */  
  1131.     pthread_mutex_lock(&dev->mutex);  
  1132.     while (dev->input_reports) {  
  1133.         return_data(dev, NULL, 0);  
  1134.     }  
  1135.     pthread_mutex_unlock(&dev->mutex);  
  1136.       
  1137.     free_hid_device(dev);  
  1138. }  
  1139.   
  1140.   
  1141. int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)  
  1142. {  
  1143.     return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);  
  1144. }  
  1145.   
  1146. int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)  
  1147. {  
  1148.     return hid_get_indexed_string(dev, dev->product_index, string, maxlen);  
  1149. }  
  1150.   
  1151. int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)  
  1152. {  
  1153.     return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);  
  1154. }  
  1155.   
  1156. int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)  
  1157. {  
  1158.     wchar_t *str;  
  1159.   
  1160.     str = get_usb_string(dev->device_handle, string_index);  
  1161.     if (str) {  
  1162.         wcsncpy(string, str, maxlen);  
  1163.         string[maxlen-1] = L'\0';  
  1164.         free(str);  
  1165.         return 0;  
  1166.     }  
  1167.     else  
  1168.         return -1;  
  1169. }  
  1170.   
  1171.   
  1172. HID_API_EXPORT const wchar_t * HID_API_CALL  hid_error(hid_device *dev)  
  1173. {  
  1174.     return NULL;  
  1175. }  
  1176.   
  1177.   
  1178. struct lang_map_entry {  
  1179.     const char *name;  
  1180.     const char *string_code;  
  1181.     uint16_t usb_code;  
  1182. };  
  1183.   
  1184. #define LANG(name,code,usb_code) { name, code, usb_code }  
  1185. static struct lang_map_entry lang_map[] = {  
  1186.     LANG("Afrikaans""af", 0x0436),  
  1187.     LANG("Albanian""sq", 0x041C),  
  1188.     LANG("Arabic - United Arab Emirates""ar_ae", 0x3801),  
  1189.     LANG("Arabic - Bahrain""ar_bh", 0x3C01),  
  1190.     LANG("Arabic - Algeria""ar_dz", 0x1401),  
  1191.     LANG("Arabic - Egypt""ar_eg", 0x0C01),  
  1192.     LANG("Arabic - Iraq""ar_iq", 0x0801),  
  1193.     LANG("Arabic - Jordan""ar_jo", 0x2C01),  
  1194.     LANG("Arabic - Kuwait""ar_kw", 0x3401),  
  1195.     LANG("Arabic - Lebanon""ar_lb", 0x3001),  
  1196.     LANG("Arabic - Libya""ar_ly", 0x1001),  
  1197.     LANG("Arabic - Morocco""ar_ma", 0x1801),  
  1198.     LANG("Arabic - Oman""ar_om", 0x2001),  
  1199.     LANG("Arabic - Qatar""ar_qa", 0x4001),  
  1200.     LANG("Arabic - Saudi Arabia""ar_sa", 0x0401),  
  1201.     LANG("Arabic - Syria""ar_sy", 0x2801),  
  1202.     LANG("Arabic - Tunisia""ar_tn", 0x1C01),  
  1203.     LANG("Arabic - Yemen""ar_ye", 0x2401),  
  1204.     LANG("Armenian""hy", 0x042B),  
  1205.     LANG("Azeri - Latin""az_az", 0x042C),  
  1206.     LANG("Azeri - Cyrillic""az_az", 0x082C),  
  1207.     LANG("Basque""eu", 0x042D),  
  1208.     LANG("Belarusian""be", 0x0423),  
  1209.     LANG("Bulgarian""bg", 0x0402),  
  1210.     LANG("Catalan""ca", 0x0403),  
  1211.     LANG("Chinese - China""zh_cn", 0x0804),  
  1212.     LANG("Chinese - Hong Kong SAR""zh_hk", 0x0C04),  
  1213.     LANG("Chinese - Macau SAR""zh_mo", 0x1404),  
  1214.     LANG("Chinese - Singapore""zh_sg", 0x1004),  
  1215.     LANG("Chinese - Taiwan""zh_tw", 0x0404),  
  1216.     LANG("Croatian""hr", 0x041A),  
  1217.     LANG("Czech""cs", 0x0405),  
  1218.     LANG("Danish""da", 0x0406),  
  1219.     LANG("Dutch - Netherlands""nl_nl", 0x0413),  
  1220.     LANG("Dutch - Belgium""nl_be", 0x0813),  
  1221.     LANG("English - Australia""en_au", 0x0C09),  
  1222.     LANG("English - Belize""en_bz", 0x2809),  
  1223.     LANG("English - Canada""en_ca", 0x1009),  
  1224.     LANG("English - Caribbean""en_cb", 0x2409),  
  1225.     LANG("English - Ireland""en_ie", 0x1809),  
  1226.     LANG("English - Jamaica""en_jm", 0x2009),  
  1227.     LANG("English - New Zealand""en_nz", 0x1409),  
  1228.     LANG("English - Phillippines""en_ph", 0x3409),  
  1229.     LANG("English - Southern Africa""en_za", 0x1C09),  
  1230.     LANG("English - Trinidad""en_tt", 0x2C09),  
  1231.     LANG("English - Great Britain""en_gb", 0x0809),  
  1232.     LANG("English - United States""en_us", 0x0409),  
  1233.     LANG("Estonian""et", 0x0425),  
  1234.     LANG("Farsi""fa", 0x0429),  
  1235.     LANG("Finnish""fi", 0x040B),  
  1236.     LANG("Faroese""fo", 0x0438),  
  1237.     LANG("French - France""fr_fr", 0x040C),  
  1238.     LANG("French - Belgium""fr_be", 0x080C),  
  1239.     LANG("French - Canada""fr_ca", 0x0C0C),  
  1240.     LANG("French - Luxembourg""fr_lu", 0x140C),  
  1241.     LANG("French - Switzerland""fr_ch", 0x100C),  
  1242.     LANG("Gaelic - Ireland""gd_ie", 0x083C),  
  1243.     LANG("Gaelic - Scotland""gd", 0x043C),  
  1244.     LANG("German - Germany""de_de", 0x0407),  
  1245.     LANG("German - Austria""de_at", 0x0C07),  
  1246.     LANG("German - Liechtenstein""de_li", 0x1407),  
  1247.     LANG("German - Luxembourg""de_lu", 0x1007),  
  1248.     LANG("German - Switzerland""de_ch", 0x0807),  
  1249.     LANG("Greek""el", 0x0408),  
  1250.     LANG("Hebrew""he", 0x040D),  
  1251.     LANG("Hindi""hi", 0x0439),  
  1252.     LANG("Hungarian""hu", 0x040E),  
  1253.     LANG("Icelandic""is", 0x040F),  
  1254.     LANG("Indonesian""id", 0x0421),  
  1255.     LANG("Italian - Italy""it_it", 0x0410),  
  1256.     LANG("Italian - Switzerland""it_ch", 0x0810),  
  1257.     LANG("Japanese""ja", 0x0411),  
  1258.     LANG("Korean""ko", 0x0412),  
  1259.     LANG("Latvian""lv", 0x0426),  
  1260.     LANG("Lithuanian""lt", 0x0427),  
  1261.     LANG("F.Y.R.O. Macedonia""mk", 0x042F),  
  1262.     LANG("Malay - Malaysia""ms_my", 0x043E),  
  1263.     LANG("Malay – Brunei""ms_bn", 0x083E),  
  1264.     LANG("Maltese""mt", 0x043A),  
  1265.     LANG("Marathi""mr", 0x044E),  
  1266.     LANG("Norwegian - Bokml""no_no", 0x0414),  
  1267.     LANG("Norwegian - Nynorsk""no_no", 0x0814),  
  1268.     LANG("Polish""pl", 0x0415),  
  1269.     LANG("Portuguese - Portugal""pt_pt", 0x0816),  
  1270.     LANG("Portuguese - Brazil""pt_br", 0x0416),  
  1271.     LANG("Raeto-Romance""rm", 0x0417),  
  1272.     LANG("Romanian - Romania""ro", 0x0418),  
  1273.     LANG("Romanian - Republic of Moldova""ro_mo", 0x0818),  
  1274.     LANG("Russian""ru", 0x0419),  
  1275.     LANG("Russian - Republic of Moldova""ru_mo", 0x0819),  
  1276.     LANG("Sanskrit""sa", 0x044F),  
  1277.     LANG("Serbian - Cyrillic""sr_sp", 0x0C1A),  
  1278.     LANG("Serbian - Latin""sr_sp", 0x081A),  
  1279.     LANG("Setsuana""tn", 0x0432),  
  1280.     LANG("Slovenian""sl", 0x0424),  
  1281.     LANG("Slovak""sk", 0x041B),  
  1282.     LANG("Sorbian""sb", 0x042E),  
  1283.     LANG("Spanish - Spain (Traditional)""es_es", 0x040A),  
  1284.     LANG("Spanish - Argentina""es_ar", 0x2C0A),  
  1285.     LANG("Spanish - Bolivia""es_bo", 0x400A),  
  1286.     LANG("Spanish - Chile""es_cl", 0x340A),  
  1287.     LANG("Spanish - Colombia""es_co", 0x240A),  
  1288.     LANG("Spanish - Costa Rica""es_cr", 0x140A),  
  1289.     LANG("Spanish - Dominican Republic""es_do", 0x1C0A),  
  1290.     LANG("Spanish - Ecuador""es_ec", 0x300A),  
  1291.     LANG("Spanish - Guatemala""es_gt", 0x100A),  
  1292.     LANG("Spanish - Honduras""es_hn", 0x480A),  
  1293.     LANG("Spanish - Mexico""es_mx", 0x080A),  
  1294.     LANG("Spanish - Nicaragua""es_ni", 0x4C0A),  
  1295.     LANG("Spanish - Panama""es_pa", 0x180A),  
  1296.     LANG("Spanish - Peru""es_pe", 0x280A),  
  1297.     LANG("Spanish - Puerto Rico""es_pr", 0x500A),  
  1298.     LANG("Spanish - Paraguay""es_py", 0x3C0A),  
  1299.     LANG("Spanish - El Salvador""es_sv", 0x440A),  
  1300.     LANG("Spanish - Uruguay""es_uy", 0x380A),  
  1301.     LANG("Spanish - Venezuela""es_ve", 0x200A),  
  1302.     LANG("Southern Sotho""st", 0x0430),  
  1303.     LANG("Swahili""sw", 0x0441),  
  1304.     LANG("Swedish - Sweden""sv_se", 0x041D),  
  1305.     LANG("Swedish - Finland""sv_fi", 0x081D),  
  1306.     LANG("Tamil""ta", 0x0449),  
  1307.     LANG("Tatar""tt", 0X0444),  
  1308.     LANG("Thai""th", 0x041E),  
  1309.     LANG("Turkish""tr", 0x041F),  
  1310.     LANG("Tsonga""ts", 0x0431),  
  1311.     LANG("Ukrainian""uk", 0x0422),  
  1312.     LANG("Urdu""ur", 0x0420),  
  1313.     LANG("Uzbek - Cyrillic""uz_uz", 0x0843),  
  1314.     LANG("Uzbek – Latin""uz_uz", 0x0443),  
  1315.     LANG("Vietnamese""vi", 0x042A),  
  1316.     LANG("Xhosa""xh", 0x0434),  
  1317.     LANG("Yiddish""yi", 0x043D),  
  1318.     LANG("Zulu""zu", 0x0435),  
  1319.     LANG(NULL, NULL, 0x0),    
  1320. };  
  1321.   
  1322. uint16_t get_usb_code_for_current_locale(void)  
  1323. {  
  1324.     char *locale;  
  1325.     char search_string[64];  
  1326.     char *ptr;  
  1327.       
  1328.     /* Get the current locale. */  
  1329.     locale = setlocale(0, NULL);  
  1330.     if (!locale)  
  1331.         return 0x0;  
  1332.       
  1333.     /* Make a copy of the current locale string. */  
  1334.     strncpy(search_string, locale, sizeof(search_string));  
  1335.     search_string[sizeof(search_string)-1] = '\0';  
  1336.       
  1337.     /* Chop off the encoding part, and make it lower case. */  
  1338.     ptr = search_string;  
  1339.     while (*ptr) {  
  1340.         *ptr = tolower(*ptr);  
  1341.         if (*ptr == '.') {  
  1342.             *ptr = '\0';  
  1343.             break;  
  1344.         }  
  1345.         ptr++;  
  1346.     }  
  1347.   
  1348.     /* Find the entry which matches the string code of our locale. */  
  1349.     struct lang_map_entry *lang = lang_map;  
  1350.     while (lang->string_code) {  
  1351.         if (!strcmp(lang->string_code, search_string)) {  
  1352.             return lang->usb_code;  
  1353.         }     
  1354.         lang++;  
  1355.     }  
  1356.       
  1357.     /* There was no match. Find with just the language only. */  
  1358.     /* Chop off the variant. Chop it off at the '_'. */  
  1359.     ptr = search_string;  
  1360.     while (*ptr) {  
  1361.         *ptr = tolower(*ptr);  
  1362.         if (*ptr == '_') {  
  1363.             *ptr = '\0';  
  1364.             break;  
  1365.         }  
  1366.         ptr++;  
  1367.     }  
  1368.       
  1369. #if 0 // TODO: Do we need this?  
  1370.     /* Find the entry which matches the string code of our language. */  
  1371.     lang = lang_map;  
  1372.     while (lang->string_code) {  
  1373.         if (!strcmp(lang->string_code, search_string)) {  
  1374.             return lang->usb_code;  
  1375.         }     
  1376.         lang++;  
  1377.     }  
  1378. #endif  
  1379.       
  1380.     /* Found nothing. */  
  1381.     return 0x0;  
  1382. }  
  1383.   
  1384. #ifdef __cplusplus  
  1385. }  
  1386. #endif  



d) hidinterface.h

[cpp] view plain copy
  1. #ifndef DeltaHIDINTERFACE_H  
  2. #define DeltaHIDINTERFACE_H  
  3.   
  4. #include <stdio.h>  
  5. #include <wchar.h>  
  6. #include <string.h>  
  7. #include <stdlib.h>  
  8. #include "hidapi.h"  
  9.   
  10. // Headers needed for sleeping.  
  11. #include <unistd.h>  
  12.   
  13. #define hidDataLength 64  
  14.   
  15. //hid data receive callback function  
  16. typedef void (*DataArriveCallBackFunc)(unsigned char *recData,unsigned char length);  
  17.   
  18. DataArriveCallBackFunc hidDataArriveCallBack;  
  19.   
  20. hid_device *handle;  
  21.   
  22. unsigned char isOpen;  
  23.   
  24.   
  25. int hidApi_Init(DataArriveCallBackFunc DataArriveCallBack);  
  26.   
  27. int hidApi_Write(unsigned char *data, unsigned char length);  
  28.   
  29. //when data arrived, the function will be called  
  30. void hidApi_DataReceive(unsigned char *recData,unsigned char length);  
  31.   
  32. int hidApi_Close(void);  
  33.   
  34. #endif // HIDINTERFACE_H  


e) hidinterface.c

[cpp] view plain copy
  1. /******************************************************* 
  2.  Windows HID simplification 
  3.  
  4.  Alan Ott 
  5.  Signal 11 Software 
  6.  
  7.  8/22/2009 
  8.  
  9.  Copyright 2009, All Rights Reserved. 
  10.   
  11.  This contents of this file may be used by anyone 
  12.  for any reason without any conditions and may be 
  13.  used as a starting point for your own applications 
  14.  which use HIDAPI. 
  15. ********************************************************/  
  16.   
  17.   
  18. #include "hidinterface.h"  
  19. #include <pthread.h>  
  20.   
  21. void hidRead_thread(void);  
  22.   
  23. int hidApi_Init(DataArriveCallBackFunc DataArriveCallBack)  
  24. {  
  25.     hidDataArriveCallBack = NULL;  
  26.     // Open the device using the VID, PID,  
  27.     // and optionally the Serial number.  
  28.     ////handle = hid_open(0x4d8, 0x3f, L"12345");  
  29.     handle = hid_open(0x4d8, 0x3f, NULL);  
  30.     if (!handle) {  
  31.         printf("unable to open device\n");  
  32.         isOpen = 0;  
  33.         return -1;  
  34.     }  
  35.   
  36.     printf("open device success\n");  
  37.     isOpen = 1;  
  38.     hidDataArriveCallBack = DataArriveCallBack;  
  39.     hidRead_thread();  
  40.   
  41.   
  42.     // Set the hid_read() function to be non-blocking.  
  43.     hid_set_nonblocking(handle, 1);  
  44.   
  45.     return 0;  
  46. }  
  47.   
  48. int hidApi_Write(unsigned char *data, unsigned char length)  
  49. {  
  50.     int res;  
  51.     unsigned char realData[length+1];  
  52.   
  53.     realData[0]=length;  
  54.     int i;  
  55.     for(i=0;i<length;i++)  
  56.     {  
  57.         realData[i+1]=data[i];  
  58.     }  
  59.   
  60.     res = hid_write(handle, realData, length+1);  
  61.     if (res < 0) {  
  62.         printf("Unable to write()\n");  
  63.         printf("Error: %ls\n", hid_error(handle));  
  64.         return -1;  
  65.     }  
  66.   
  67.     printf("write success\n");  
  68.     return 0;  
  69. }  
  70.   
  71. void hidApi_DataReceive(unsigned char *recData,unsigned char length)  
  72. {  
  73.     if(hidDataArriveCallBack==NULL)  
  74.         return;  
  75.   
  76.     hidDataArriveCallBack(recData,length);  
  77. }  
  78.   
  79. void hidApi_Read()  
  80. {  
  81.     unsigned char recData[hidDataLength];  
  82.   
  83.     int res;  
  84.     while (isOpen==1) {  
  85.         res = hid_read(handle, recData, hidDataLength);  
  86.         if (res == 0)  
  87.             ;//printf("waiting...\n");  
  88.         else if (res < 0)  
  89.         {  
  90.             printf("Unable to read()\n");  
  91.             return -1;  
  92.         }  
  93.         else  
  94.         {  
  95.   
  96.             int i;  
  97.   
  98. //            printf("Data read:\n   ");  
  99. //            // Print out the returned buffer.  
  100. //  
  101. //            for (i = 0; i < res; i++)  
  102. //                printf("%02hhx ", recData[i]);  
  103. //            printf("\n");  
  104.   
  105.             unsigned char length = recData[0];  
  106.   
  107.             unsigned char datas[length];  
  108.             for(i=0;i<length;i++)  
  109.             {  
  110.                 datas[i]=recData[i+1];  
  111.             }  
  112.   
  113.             hidApi_DataReceive(datas,length);  
  114.         }  
  115.   
  116.   
  117.         usleep(50*1000);  
  118.   
  119.     }  
  120.   
  121. }  
  122.   
  123. void hidRead_thread(void)  
  124. {  
  125.    pthread_t id;  
  126.    int ret, i;  
  127.    ret=pthread_create(&id,NULL,(void *) hidApi_Read,NULL); // 成功返回0,错误返回错误编号  
  128.    if(ret!=0) {  
  129.        printf ("Create pthread error!\n");  
  130.        exit (1);  
  131.    }  
  132.   
  133.   
  134.    //pthread_join(id,NULL);  
  135.   
  136.    printf ("Create pthread success!\n");  
  137. }  
  138.   
  139. int hidApi_Close(void)  
  140. {  
  141.     hid_close(handle);  
  142.     isOpen = 0;  
  143.     /* Free static HIDAPI objects. */  
  144.     hid_exit();  
  145.   
  146.     return 0;  
  147.   
  148. }  



f) main.c

[cpp] view plain copy
  1. #include <hidlib/hidinterface.h>  
  2.   
  3. // down 50000 50 : FA 00 00 04 03 01 00 00 00 50 C3 00 00 32 00 00 00 A7 A5  
  4. unsigned char bufferDown50[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x01, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0xA7, 0xA5};  
  5. // down 50000 10 : FA 00 00 04 03 01 00 00 00 50 C3 00 00 0A 00 00 00 9F A5  
  6. unsigned char bufferDown10[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x01, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x9F, 0xA5};  
  7.   
  8. // up 50000 50 : FA 00 00 04 03 00 00 00 00 50 C3 00 00 32 00 00 00 A6 A5  
  9. unsigned char bufferUp50[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0xA6, 0xA5};  
  10. // up 50000 10 : FA 00 00 04 03 00 00 00 00 50 C3 00 00 0A 00 00 00 9E A5  
  11. unsigned char bufferUp10[] = {0xFA, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x50, 0xC3, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x9E, 0xA5};  
  12.   
  13.   
  14. // go home FA 00 02 04 03 00 00 00 00 00 00 00 00 0A 00 00 00 0D A5  
  15. unsigned char bufferGoHome[] = { 0xFA, 0x00, 0x02, 0x04, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0xA5};  
  16.   
  17. char isReponse = 0;  
  18.   
  19. void datarec(unsigned char *recData,unsigned char length)  
  20. {  
  21.     printf("Data Receive: ");  
  22.     int i;  
  23.     for(i=0;i<length;i++)  
  24.     {  
  25.         printf("%02hhx ", recData[i]);  
  26.     }  
  27.     printf("\n");  
  28.     isReponse = 1;  
  29. }  
  30.   
  31. int main(int argc, char* argv[])  
  32. {  
  33.   
  34.     hidApi_Init(datarec);  
  35.   
  36.     isReponse = 1;  
  37.     while(1)  
  38.     {  
  39.         while(isReponse==0) usleep(500*1000);  
  40.         isReponse =0;  
  41.         hidApi_Write(bufferGoHome,0x13);  
  42.         usleep(500*1000);  
  43.   
  44.         while(isReponse==0) usleep(500*1000);  
  45.         isReponse =0;  
  46.         hidApi_Write(bufferDown10,0x13);  
  47.         usleep(500*1000);  
  48.   
  49.         while(isReponse==0) usleep(500*1000);  
  50.         isReponse =0;  
  51.         hidApi_Write(bufferDown50,0x13);  
  52.   
  53.         while(isReponse==0) usleep(500*1000);  
  54.         isReponse =0;  
  55.         hidApi_Write(bufferDown10,0x13);  
  56.         usleep(500*1000);  
  57.   
  58.         usleep(2*1000*1000);  
  59.         while(isReponse==0) usleep(500*1000);  
  60.         isReponse =0;  
  61.         hidApi_Write(bufferGoHome,0x13);  
  62.   
  63.         usleep(2*1000*1000);  
  64.     }  
  65.   
  66.     hidApi_Close();  
  67.   
  68.     return 0;  
  69. }  


from: http://blog.csdn.net/u010875635/article/details/73277779