From ba3c3aa62c22161bf4219cbf905f522e8b0e241e Mon Sep 17 00:00:00 2001 From: JoergAtGithub Date: Mon, 30 May 2022 19:21:11 +0200 Subject: [PATCH] Add excludes for lib/hidapi to .gitignore Delete unused files from lib/hidapi Updated hidapi from 0.10.1 to 0.11.2 Increased minimum required hidapi version to 0.11.2 --- .gitignore | 23 +- CMakeLists.txt | 4 +- lib/hidapi/.gitattributes | 7 - lib/hidapi/.gitignore | 24 - lib/hidapi/AUTHORS.txt | 2 +- lib/hidapi/Makefile.am | 85 ---- lib/hidapi/README.md | 307 +++--------- lib/hidapi/VERSION | 2 +- lib/hidapi/bootstrap | 2 - lib/hidapi/configure.ac | 245 --------- lib/hidapi/hidapi/hidapi.h | 4 +- lib/hidapi/libusb/.gitignore | 8 - lib/hidapi/libusb/Makefile-manual | 22 - lib/hidapi/libusb/Makefile.am | 34 -- lib/hidapi/libusb/Makefile.freebsd | 39 -- lib/hidapi/libusb/Makefile.haiku | 39 -- lib/hidapi/libusb/Makefile.linux | 42 -- lib/hidapi/libusb/hid.c | 492 +++++++++++------- lib/hidapi/libusb/hidapi_libusb.h | 54 ++ lib/hidapi/linux/.gitignore | 18 - lib/hidapi/linux/Makefile-manual | 42 -- lib/hidapi/linux/Makefile.am | 10 - lib/hidapi/linux/hid.c | 41 +- lib/hidapi/m4/.gitignore | 5 - lib/hidapi/m4/ax_pthread.m4 | 309 ------------ lib/hidapi/m4/pkg.m4 | 157 ------ lib/hidapi/mac/.gitignore | 17 - lib/hidapi/mac/Makefile-manual | 27 - lib/hidapi/mac/Makefile.am | 9 - lib/hidapi/mac/hid.c | 131 +++-- lib/hidapi/pc/.gitignore | 1 - lib/hidapi/pc/hidapi-hidraw.pc.in | 10 - lib/hidapi/pc/hidapi-libusb.pc.in | 10 - lib/hidapi/pc/hidapi.pc.in | 10 - lib/hidapi/udev/69-hid.rules | 36 ++ lib/hidapi/udev/99-hid.rules | 33 -- lib/hidapi/windows/.gitignore | 17 - lib/hidapi/windows/Makefile-manual | 14 - lib/hidapi/windows/Makefile.am | 16 - lib/hidapi/windows/Makefile.mingw | 30 -- lib/hidapi/windows/hid.c | 746 +++++++++++++++++----------- lib/hidapi/windows/hidapi.sln | 41 -- lib/hidapi/windows/hidapi.vcproj | 201 -------- lib/hidapi/windows/hidapi.vcxproj | 160 ------ lib/hidapi/windows/hidtest.vcproj | 196 -------- lib/hidapi/windows/hidtest.vcxproj | 156 ------ src/controllers/hid/hidiothread.cpp | 2 - 47 files changed, 1034 insertions(+), 2846 deletions(-) delete mode 100644 lib/hidapi/.gitattributes delete mode 100644 lib/hidapi/.gitignore delete mode 100644 lib/hidapi/Makefile.am delete mode 100755 lib/hidapi/bootstrap delete mode 100644 lib/hidapi/configure.ac delete mode 100644 lib/hidapi/libusb/.gitignore delete mode 100644 lib/hidapi/libusb/Makefile-manual delete mode 100644 lib/hidapi/libusb/Makefile.am delete mode 100644 lib/hidapi/libusb/Makefile.freebsd delete mode 100644 lib/hidapi/libusb/Makefile.haiku delete mode 100644 lib/hidapi/libusb/Makefile.linux create mode 100644 lib/hidapi/libusb/hidapi_libusb.h delete mode 100644 lib/hidapi/linux/.gitignore delete mode 100644 lib/hidapi/linux/Makefile-manual delete mode 100644 lib/hidapi/linux/Makefile.am delete mode 100644 lib/hidapi/m4/.gitignore delete mode 100644 lib/hidapi/m4/ax_pthread.m4 delete mode 100644 lib/hidapi/m4/pkg.m4 delete mode 100644 lib/hidapi/mac/.gitignore delete mode 100644 lib/hidapi/mac/Makefile-manual delete mode 100644 lib/hidapi/mac/Makefile.am delete mode 100644 lib/hidapi/pc/.gitignore delete mode 100644 lib/hidapi/pc/hidapi-hidraw.pc.in delete mode 100644 lib/hidapi/pc/hidapi-libusb.pc.in delete mode 100644 lib/hidapi/pc/hidapi.pc.in create mode 100644 lib/hidapi/udev/69-hid.rules delete mode 100644 lib/hidapi/udev/99-hid.rules delete mode 100644 lib/hidapi/windows/.gitignore delete mode 100644 lib/hidapi/windows/Makefile-manual delete mode 100644 lib/hidapi/windows/Makefile.am delete mode 100644 lib/hidapi/windows/Makefile.mingw mode change 100755 => 100644 lib/hidapi/windows/hid.c delete mode 100644 lib/hidapi/windows/hidapi.sln delete mode 100644 lib/hidapi/windows/hidapi.vcproj delete mode 100644 lib/hidapi/windows/hidapi.vcxproj delete mode 100644 lib/hidapi/windows/hidtest.vcproj delete mode 100644 lib/hidapi/windows/hidtest.vcxproj diff --git a/.gitignore b/.gitignore index 6c35698759d..b6c32a00ab7 100644 --- a/.gitignore +++ b/.gitignore @@ -40,11 +40,24 @@ lib/googletest/googletest/test # Exclude unneeded files from the bundled hidapi library in the lib/ # directory for future updates -lib/hidapi/android -lib/hidapi/dist -lib/hidapi/doxygen -lib/hidapi/hidtest -lib/hidapi/testgui +lib/hidapi/android/ +lib/hidapi/dist/ +lib/hidapi/documentation/ +lib/hidapi/doxygen/ +lib/hidapi/hidtest/ +lib/hidapi/m4/ +lib/hidapi/pc/ +lib/hidapi/src/ +lib/hidapi/testgui/ +lib/hidapi/bootstrap +lib/hidapi/configure.ac +lib/hidapi/BUILD.* +lib/hidapi/windows/* +!lib/hidapi/windows/*.c +!lib/hidapi/windows/*.h +lib/hidapi/**/.gitignore +lib/hidapi/**/CMakeLists.txt +lib/hidapi/**/Makefile* # Legacy compilation artifacts that are obsolete starting with 2.3 # TODO: Delete after 2.2 with SCons has been abandoned. Developers diff --git a/CMakeLists.txt b/CMakeLists.txt index 429b7e34a91..888bb076a38 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2792,7 +2792,9 @@ find_package(LibUSB) # USB HID controller support option(HID "USB HID controller support" ON) if(HID) - find_package(hidapi 0.10.1) + # hidapi 0.11.2 is the first release, that implements hid_get_input_report + # for the Linux hidraw backend. + find_package(hidapi 0.11.2) if(NOT hidapi_FOUND) message(STATUS "Linking internal libhidapi statically") add_library(mixxx-hidapi STATIC EXCLUDE_FROM_ALL) diff --git a/lib/hidapi/.gitattributes b/lib/hidapi/.gitattributes deleted file mode 100644 index edb79febc56..00000000000 --- a/lib/hidapi/.gitattributes +++ /dev/null @@ -1,7 +0,0 @@ -* text=auto - -*.sln text eol=crlf -*.vcproj text eol=crlf - -bootstrap text eol=lf -configure.ac text eol=lf diff --git a/lib/hidapi/.gitignore b/lib/hidapi/.gitignore deleted file mode 100644 index 9963751f30e..00000000000 --- a/lib/hidapi/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ - -# Autotools-added generated files -Makefile.in -aclocal.m4 -ar-lib -autom4te.cache/ -config.* -configure -compile -depcomp -install-sh -libusb/Makefile.in -linux/Makefile.in -ltmain.sh -mac/Makefile.in -missing -testgui/Makefile.in -windows/Makefile.in - -Makefile -stamp-h1 -libtool - -.DS_Store diff --git a/lib/hidapi/AUTHORS.txt b/lib/hidapi/AUTHORS.txt index e08cb16196f..7193d71e0b0 100644 --- a/lib/hidapi/AUTHORS.txt +++ b/lib/hidapi/AUTHORS.txt @@ -14,5 +14,5 @@ libusb/hidapi Team: Development/maintainance since June 4th 2019 For a comprehensive list of contributions, see the commit list at github: - https://github.com/libusb/hidapi/commits/master + https://github.com/libusb/hidapi/graphs/contributors diff --git a/lib/hidapi/Makefile.am b/lib/hidapi/Makefile.am deleted file mode 100644 index 00bcb73cf41..00000000000 --- a/lib/hidapi/Makefile.am +++ /dev/null @@ -1,85 +0,0 @@ - -ACLOCAL_AMFLAGS = -I m4 - -if OS_FREEBSD -pkgconfigdir=$(prefix)/libdata/pkgconfig -else -pkgconfigdir=$(libdir)/pkgconfig -endif - -if OS_LINUX -pkgconfig_DATA=pc/hidapi-hidraw.pc pc/hidapi-libusb.pc -else -pkgconfig_DATA=pc/hidapi.pc -endif - -SUBDIRS= - -if OS_LINUX -SUBDIRS += linux libusb -endif - -if OS_DARWIN -SUBDIRS += mac -endif - -if OS_FREEBSD -SUBDIRS += libusb -endif - -if OS_KFREEBSD -SUBDIRS += libusb -endif - -if OS_HAIKU -SUBDIRS += libusb -endif - -if OS_WINDOWS -SUBDIRS += windows -endif - -SUBDIRS += hidtest - -if BUILD_TESTGUI -SUBDIRS += testgui -endif - -EXTRA_DIST = udev doxygen - -dist_doc_DATA = \ - README.md \ - AUTHORS.txt \ - LICENSE-bsd.txt \ - LICENSE-gpl3.txt \ - LICENSE-orig.txt \ - LICENSE.txt - -SCMCLEAN_TARGETS= \ - aclocal.m4 \ - config.guess \ - config.sub \ - configure \ - config.h.in \ - depcomp \ - install-sh \ - ltmain.sh \ - missing \ - mac/Makefile.in \ - testgui/Makefile.in \ - libusb/Makefile.in \ - Makefile.in \ - linux/Makefile.in \ - windows/Makefile.in \ - m4/libtool.m4 \ - m4/lt~obsolete.m4 \ - m4/ltoptions.m4 \ - m4/ltsugar.m4 \ - m4/ltversion.m4 - -SCMCLEAN_DIR_TARGETS = \ - autom4te.cache - -scm-clean: distclean - rm -f $(SCMCLEAN_TARGETS) - rm -Rf $(SCMCLEAN_DIR_TARGETS) diff --git a/lib/hidapi/README.md b/lib/hidapi/README.md index f5582d7a9a1..c2f378f89a7 100644 --- a/lib/hidapi/README.md +++ b/lib/hidapi/README.md @@ -2,9 +2,9 @@ | CI instance | Status | |----------------------|--------| -| `macOS master` | [![Build Status](https://travis-ci.org/libusb/hidapi.svg?branch=master)](https://travis-ci.org/libusb/hidapi) | -| `Windows master` | [![Build status](https://ci.appveyor.com/api/projects/status/r482aevuigmi86rk/branch/master?svg=true)](https://ci.appveyor.com/project/Youw/hidapi/branch/master) | -| `Linux/BSD, last build (branch/PR)` | [![builds.sr.ht status](https://builds.sr.ht/~qbicz/hidapi.svg)](https://builds.sr.ht/~qbicz/hidapi?) | +| `Linux/macOS/Windows master` | [![GitHub Builds](https://github.com/libusb/hidapi/workflows/GitHub%20Builds/badge.svg?branch=master)](https://github.com/libusb/hidapi/actions/workflows/builds.yml?query=branch%3Amaster) | +| `Windows master` | [![Build status](https://ci.appveyor.com/api/projects/status/xfmr5fo8w0re8ded/branch/master?svg=true)](https://ci.appveyor.com/project/libusb/hidapi/branch/master) | +| `Linux/BSD, last build (branch/PR)` | [![builds.sr.ht status](https://builds.sr.ht/~z3ntu/hidapi.svg)](https://builds.sr.ht/~z3ntu/hidapi) | HIDAPI is a multi-platform library which allows an application to interface with USB and Bluetooth HID-Class devices on Windows, Linux, FreeBSD, and macOS. @@ -19,35 +19,34 @@ It was moved to [libusb/hidapi](https://github.com/libusb/hidapi) on June 4th, 2 ## Table of Contents * [About](#about) + * [Test GUI](#test-gui) + * [Console Test App](#console-test-app) * [What Does the API Look Like?](#what-does-the-api-look-like) * [License](#license) -* [Download](#download) -* [Build Instructions](#build-instructions) - * [Prerequisites](#prerequisites) - * [Linux](#linux) - * [FreeBSD](#freebsd) - * [Mac](#mac) - * [Windows](#windows) - * [Building HIDAPI into a shared library on Unix Platforms](#building-hidapi-into-a-shared-library-on-unix-platforms) - * [Building the manual way on Unix platforms](#building-the-manual-way-on-unix-platforms) - * [Building on Windows](#building-on-windows) -* [Cross Compiling](#cross-compiling) - * [Prerequisites](#prerequisites-1) - * [Building HIDAPI](#building-hidapi) +* [Installing HIDAPI](#installing-hidapi) +* [Build from Source](#build-from-source) + ## About -HIDAPI has five back-ends: +### HIDAPI has four back-ends: * Windows (using `hid.dll`) * Linux/hidraw (using the Kernel's hidraw driver) -* Linux/libusb (using libusb-1.0) -* FreeBSD (using libusb-1.0) -* Mac (using IOHidManager) +* libusb (using libusb-1.0 - Linux/BSD/other UNIX-like systems) +* macOS (using IOHidManager) On Linux, either the hidraw or the libusb back-end can be used. There are -tradeoffs, and the functionality supported is slightly different. +tradeoffs, and the functionality supported is slightly different. Both are +built by default. It is up to the application linking to hidapi to choose +the backend at link time by linking to either `libhidapi-libusb` or +`libhidapi-hidraw`. + +Note that you will need to install an udev rule file with your application +for unprivileged users to be able to access HID devices with hidapi. Refer +to the [69-hid.rules](udev/69-hid.rules) file in the `udev` directory +for an example. -__Linux/hidraw__ (`linux/hid.c`): +#### __Linux/hidraw__ (`linux/hid.c`): This back-end uses the hidraw interface in the Linux kernel, and supports both USB and Bluetooth HID devices. It requires kernel version at least 2.6.39 @@ -57,17 +56,35 @@ Keyboards, mice, and some other devices which are blacklisted from having hidraw nodes will not work. Fortunately, for nearly all the uses of hidraw, this is not a problem. -__Linux/FreeBSD/libusb__ (`libusb/hid.c`): +#### __Linux/FreeBSD/libusb__ (`libusb/hid.c`): This back-end uses libusb-1.0 to communicate directly to a USB device. This back-end will of course not work with Bluetooth devices. +### Test GUI + HIDAPI also comes with a Test GUI. The Test GUI is cross-platform and uses Fox Toolkit . It will build on every platform which HIDAPI supports. Since it relies on a 3rd party library, building it -is optional but recommended because it is so useful when debugging hardware. +is optional but it is useful when debugging hardware. + +NOTE: Test GUI based on Fox Toolkit is not actively developed nor supported +by HIDAPI team. It is kept as a historical artifact. It may even work sometime +or on some platforms, but it is not going to get any new features or bugfixes. + +Instructions for installing Fox-Toolkit on each platform is not provided. +Make sure to use Fox-Toolkit v1.6 if you choose to use it. + +### Console Test App + +If you want to play around with your HID device before starting +any development with HIDAPI and using a GUI app is not an option for you, you may try [`hidapitester`](https://github.com/todbot/hidapitester). + +This app has a console interface for most of the features supported +by HIDAPI library. ## What Does the API Look Like? + The API provides the most commonly used HID functions including sending and receiving of input, output, and feature reports. The sample program, which communicates with a heavily hacked up version of the Microchip USB @@ -75,15 +92,13 @@ Generic HID sample looks like this (with error checking removed for simplicity): **Warning: Only run the code you understand, and only when it conforms to the -device spec. Writing data at random to your HID devices can break them.** +device spec. Writing data (`hid_write`) at random to your HID devices can break them.** ```c -#ifdef WIN32 -#include -#endif -#include -#include -#include "hidapi.h" +#include // printf +#include // wprintf + +#include #define MAX_STR 255 @@ -150,231 +165,25 @@ as a starting point for your applications. ## License -HIDAPI may be used by one of three licenses as outlined in [LICENSE.txt](LICENSE.txt). - -## Download -HIDAPI can be downloaded from GitHub -```sh -git clone git://github.com/libusb/hidapi.git -``` - -## Build Instructions - -This section is long. Don't be put off by this. It's not long because it's -complicated to build HIDAPI; it's quite the opposite. This section is long -because of the flexibility of HIDAPI and the large number of ways in which -it can be built and used. You will likely pick a single build method. - -HIDAPI can be built in several different ways. If you elect to build a -shared library, you will need to build it from the HIDAPI source -distribution. If you choose instead to embed HIDAPI directly into your -application, you can skip the building and look at the provided platform -Makefiles for guidance. These platform Makefiles are located in `linux/`, -`libusb/`, `mac/` and `windows/` and are called `Makefile-manual`. In addition, -Visual Studio projects are provided. Even if you're going to embed HIDAPI -into your project, it is still beneficial to build the example programs. +HIDAPI may be used by one of three licenses as outlined in [LICENSE.txt](LICENSE.txt). -### Prerequisites: - -#### Linux: -On Linux, you will need to install development packages for libudev, -libusb and optionally Fox-toolkit (for the test GUI). On -Debian/Ubuntu systems these can be installed by running: -```sh -sudo apt-get install libudev-dev libusb-1.0-0-dev libfox-1.6-dev -``` - -If you downloaded the source directly from the git repository (using -git clone), you'll need Autotools: -```sh -sudo apt-get install autotools-dev autoconf automake libtool -``` - -#### FreeBSD: -On FreeBSD you will need to install GNU make, libiconv, and -optionally Fox-Toolkit (for the test GUI). This is done by running -the following: -```sh -pkg_add -r gmake libiconv fox16 -``` - -If you downloaded the source directly from the git repository (using -git clone), you'll need Autotools: -```sh -pkg_add -r autotools -``` - -#### Mac: -On Mac, you will need to install Fox-Toolkit if you wish to build -the Test GUI. There are two ways to do this, and each has a slight -complication. Which method you use depends on your use case. - -If you wish to build the Test GUI just for your own testing on your -own computer, then the easiest method is to install Fox-Toolkit -using ports: -```sh -sudo port install fox -``` - -If you wish to build the TestGUI app bundle to redistribute to -others, you will need to install Fox-toolkit from source. This is -because the version of fox that gets installed using ports uses the -ports X11 libraries which are not compatible with the Apple X11 -libraries. If you install Fox with ports and then try to distribute -your built app bundle, it will simply fail to run on other systems. -To install Fox-Toolkit manually, download the source package from -, extract it, and run the following from -within the extracted source: -```sh -./configure && make && make install -``` - -#### Windows: -On Windows, if you want to build the test GUI, you will need to get -the `hidapi-externals.zip` package from the download site. This -contains pre-built binaries for Fox-toolkit. Extract -`hidapi-externals.zip` just outside of hidapi, so that -hidapi-externals and hidapi are on the same level, as shown: -``` - Parent_Folder - | - +hidapi - +hidapi-externals -``` -Again, this step is not required if you do not wish to build the -test GUI. - - -### Building HIDAPI into a shared library on Unix Platforms: - -On Unix-like systems such as Linux, FreeBSD, macOS, and even Windows, using -MinGW or Cygwin, the easiest way to build a standard system-installed shared -library is to use the GNU Autotools build system. If you checked out the -source from the git repository, run the following: - -```sh -./bootstrap -./configure -make -make install # as root, or using sudo -``` - -If you downloaded a source package (i.e.: if you did not run git clone), you -can skip the `./bootstrap` step. - -`./configure` can take several arguments which control the build. The two most -likely to be used are: -```sh - --enable-testgui - Enable build of the Test GUI. This requires Fox toolkit to - be installed. Instructions for installing Fox-Toolkit on - each platform are in the Prerequisites section above. - - --prefix=/usr - Specify where you want the output headers and libraries to - be installed. The example above will put the headers in - /usr/include and the binaries in /usr/lib. The default is to - install into /usr/local which is fine on most systems. -``` -### Building the manual way on Unix platforms: - -Manual Makefiles are provided mostly to give the user and idea what it takes -to build a program which embeds HIDAPI directly inside of it. These should -really be used as examples only. If you want to build a system-wide shared -library, use the Autotools method described above. - -To build HIDAPI using the manual Makefiles, change to the directory -of your platform and run make. For example, on Linux run: -```sh -cd linux/ -make -f Makefile-manual -``` - -To build the Test GUI using the manual makefiles: -```sh -cd testgui/ -make -f Makefile-manual -``` - -### Building on Windows: - -To build the HIDAPI DLL on Windows using Visual Studio, build the `.sln` file -in the `windows/` directory. - -To build the Test GUI on windows using Visual Studio, build the `.sln` file in -the `testgui/` directory. - -To build HIDAPI using MinGW or Cygwin using Autotools, use the instructions -in the section [Building HIDAPI into a shared library on Unix Platforms](#building-hidapi-into-a-shared-library-on-unix-platforms) -above. Note that building the Test GUI with MinGW or Cygwin will -require the Windows procedure in the [Prerequisites](#prerequisites-1) section -above (i.e.: `hidapi-externals.zip`). - -To build HIDAPI using MinGW using the Manual Makefiles, see the section -[Building the manual way on Unix platforms](#building-the-manual-way-on-unix-platforms) -above. - -HIDAPI can also be built using the Windows DDK (now also called the Windows -Driver Kit or WDK). This method was originally required for the HIDAPI build -but not anymore. However, some users still prefer this method. It is not as -well supported anymore but should still work. Patches are welcome if it does -not. To build using the DDK: - - 1. Install the Windows Driver Kit (WDK) from Microsoft. - 2. From the Start menu, in the Windows Driver Kits folder, select Build - Environments, then your operating system, then the x86 Free Build - Environment (or one that is appropriate for your system). - 3. From the console, change directory to the `windows/ddk_build/` directory, - which is part of the HIDAPI distribution. - 4. Type build. - 5. You can find the output files (DLL and LIB) in a subdirectory created - by the build system which is appropriate for your environment. On - Windows XP, this directory is `objfre_wxp_x86/i386`. - -## Cross Compiling - -This section talks about cross compiling HIDAPI for Linux using Autotools. -This is useful for using HIDAPI on embedded Linux targets. These -instructions assume the most raw kind of embedded Linux build, where all -prerequisites will need to be built first. This process will of course vary -based on your embedded Linux build system if you are using one, such as -OpenEmbedded or Buildroot. - -For the purpose of this section, it will be assumed that the following -environment variables are exported. -```sh -$ export STAGING=$HOME/out -$ export HOST=arm-linux -``` - -`STAGING` and `HOST` can be modified to suit your setup. +## Installing HIDAPI -### Prerequisites +If you want to build your own application that uses HID devices with HIDAPI, +you need to get HIDAPI development package. -Note that the build of libudev is the very basic configuration. +Depending on what your development environment is, HIDAPI likely to be provided +by your package manager. -Build libusb. From the libusb source directory, run: +For instance on Ubuntu, HIDAPI is available via APT: ```sh -./configure --host=$HOST --prefix=$STAGING -make -make install +sudo apt install libhidapi-dev ``` -Build libudev. From the libudev source directory, run: -```sh -./configure --disable-gudev --disable-introspection --disable-hwdb \ - --host=$HOST --prefix=$STAGING -make -make install -``` +HIDAPI package name for other systems/package managers may differ. +Check the documentation/package list of your package manager. -### Building HIDAPI +## Build from Source -Build HIDAPI: -``` -PKG_CONFIG_DIR= \ -PKG_CONFIG_LIBDIR=$STAGING/lib/pkgconfig:$STAGING/share/pkgconfig \ -PKG_CONFIG_SYSROOT_DIR=$STAGING \ -./configure --host=$HOST --prefix=$STAGING -``` +Check [BUILD.md](BUILD.md) for details. diff --git a/lib/hidapi/VERSION b/lib/hidapi/VERSION index 71172b43ae9..a8839f70de0 100644 --- a/lib/hidapi/VERSION +++ b/lib/hidapi/VERSION @@ -1 +1 @@ -0.10.1 \ No newline at end of file +0.11.2 \ No newline at end of file diff --git a/lib/hidapi/bootstrap b/lib/hidapi/bootstrap deleted file mode 100755 index 81e9b74b617..00000000000 --- a/lib/hidapi/bootstrap +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -x -autoreconf --install --verbose --force diff --git a/lib/hidapi/configure.ac b/lib/hidapi/configure.ac deleted file mode 100644 index 220909a0529..00000000000 --- a/lib/hidapi/configure.ac +++ /dev/null @@ -1,245 +0,0 @@ -AC_PREREQ(2.63) - -AC_INIT([hidapi],[m4_normalize(m4_builtin([include], VERSION))],[https://github.com/libusb/hidapi/issues]) - -# Library soname version -# Follow the following rules (particularly the ones in the second link): -# http://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html -# http://sourceware.org/autobook/autobook/autobook_91.html -lt_current="0" -lt_revision="0" -lt_age="0" -LTLDFLAGS="-version-info ${lt_current}:${lt_revision}:${lt_age}" - -AC_CONFIG_MACRO_DIR([m4]) -AM_INIT_AUTOMAKE([foreign -Wall -Werror]) -AC_CONFIG_MACRO_DIR([m4]) - -m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) -LT_INIT - -AC_PROG_CC -AC_PROG_CXX -AC_PROG_OBJC -PKG_PROG_PKG_CONFIG - - -m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) - -hidapi_lib_error() { - echo "" - echo " Library $1 was not found on this system." - echo " Please install it and re-run ./configure" - echo "" - exit 1 -} - -hidapi_prog_error() { - echo "" - echo " Program $1 was not found on this system." - echo " This program is part of $2." - echo " Please install it and re-run ./configure" - echo "" - exit 1 -} - -AC_MSG_CHECKING([operating system]) -AC_MSG_RESULT($host) -case $host in -*-linux*) - AC_MSG_RESULT([ (Linux back-end)]) - AC_DEFINE(OS_LINUX, 1, [Linux implementations]) - AC_SUBST(OS_LINUX) - backend="linux" - os="linux" - threads="pthreads" - - # HIDAPI/hidraw libs - PKG_CHECK_MODULES([libudev], [libudev], true, [hidapi_lib_error libudev]) - LIBS_HIDRAW_PR="${LIBS_HIDRAW_PR} $libudev_LIBS" - CFLAGS_HIDRAW="${CFLAGS_HIDRAW} $libudev_CFLAGS" - - # HIDAPI/libusb libs - AC_CHECK_LIB([rt], [clock_gettime], [LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} -lrt"], [hidapi_lib_error librt]) - PKG_CHECK_MODULES([libusb], [libusb-1.0 >= 1.0.9], true, [hidapi_lib_error libusb-1.0]) - LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} $libusb_LIBS" - CFLAGS_LIBUSB="${CFLAGS_LIBUSB} $libusb_CFLAGS" - ;; -*-darwin*) - AC_MSG_RESULT([ (Mac OS X back-end)]) - AC_DEFINE(OS_DARWIN, 1, [Mac implementation]) - AC_SUBST(OS_DARWIN) - backend="mac" - os="darwin" - threads="pthreads" - LIBS="${LIBS} -framework IOKit -framework CoreFoundation -framework AppKit" - ;; -*-freebsd*) - AC_MSG_RESULT([ (FreeBSD back-end)]) - AC_DEFINE(OS_FREEBSD, 1, [FreeBSD implementation]) - AC_SUBST(OS_FREEBSD) - backend="libusb" - os="freebsd" - threads="pthreads" - - CFLAGS="$CFLAGS -I/usr/local/include" - LDFLAGS="$LDFLAGS -L/usr/local/lib" - LIBS="${LIBS}" - PKG_CHECK_MODULES([libusb], [libusb-1.0 >= 1.0.9], true, [hidapi_lib_error libusb-1.0]) - LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} $libusb_LIBS" - CFLAGS_LIBUSB="${CFLAGS_LIBUSB} $libusb_CFLAGS" - AC_CHECK_LIB([iconv], [iconv_open], [LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} -liconv"], [hidapi_lib_error libiconv]) - ;; -*-kfreebsd*) - AC_MSG_RESULT([ (kFreeBSD back-end)]) - AC_DEFINE(OS_KFREEBSD, 1, [kFreeBSD implementation]) - AC_SUBST(OS_KFREEBSD) - backend="libusb" - os="kfreebsd" - threads="pthreads" - - PKG_CHECK_MODULES([libusb], [libusb-1.0 >= 1.0.9], true, [hidapi_lib_error libusb-1.0]) - LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} $libusb_LIBS" - CFLAGS_LIBUSB="${CFLAGS_LIBUSB} $libusb_CFLAGS" - ;; -*-*-haiku) - AC_MSG_RESULT([ (Haiku back-end)]) - AC_DEFINE(OS_HAIKU, 1, [Haiku implementation]) - AC_SUBST(OS_HAIKU) - backend="libusb" - os="haiku" - threads="pthreads" - - PKG_CHECK_MODULES([libusb], [libusb-1.0 >= 1.0.9], true, [hidapi_lib_error libusb-1.0]) - LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} $libusb_LIBS" - CFLAGS_LIBUSB="${CFLAGS_LIBUSB} $libusb_CFLAGS" - AC_CHECK_LIB([iconv], [libiconv_open], [LIBS_LIBUSB_PRIVATE="${LIBS_LIBUSB_PRIVATE} -liconv"], [hidapi_lib_error libiconv]) - ;; -*-mingw*) - AC_MSG_RESULT([ (Windows back-end, using MinGW)]) - backend="windows" - os="windows" - threads="windows" - win_implementation="mingw" - ;; -*-cygwin*) - AC_MSG_RESULT([ (Windows back-end, using Cygwin)]) - backend="windows" - os="windows" - threads="windows" - win_implementation="cygwin" - ;; -*) - AC_MSG_ERROR([HIDAPI is not supported on your operating system yet]) -esac - -LIBS_HIDRAW="${LIBS} ${LIBS_HIDRAW_PR}" -LIBS_LIBUSB="${LIBS} ${LIBS_LIBUSB_PRIVATE}" -AC_SUBST([LIBS_HIDRAW]) -AC_SUBST([LIBS_LIBUSB]) -AC_SUBST([CFLAGS_LIBUSB]) -AC_SUBST([CFLAGS_HIDRAW]) - -if test "x$os" = xwindows; then - AC_DEFINE(OS_WINDOWS, 1, [Windows implementations]) - AC_SUBST(OS_WINDOWS) - LDFLAGS="${LDFLAGS} -no-undefined" - LIBS="${LIBS} -lsetupapi" -fi - -if test "x$threads" = xpthreads; then - AX_PTHREAD([found_pthreads=yes], [found_pthreads=no]) - - if test "x$found_pthreads" = xyes; then - if test "x$os" = xlinux; then - # Only use pthreads for libusb implementation on Linux. - LIBS_LIBUSB="$PTHREAD_LIBS $LIBS_LIBUSB" - CFLAGS_LIBUSB="$CFLAGS_LIBUSB $PTHREAD_CFLAGS" - # There's no separate CC on Linux for threading, - # so it's ok that both implementations use $PTHREAD_CC - CC="$PTHREAD_CC" - else - LIBS="$PTHREAD_LIBS $LIBS" - CFLAGS="$CFLAGS $PTHREAD_CFLAGS" - CC="$PTHREAD_CC" - fi - fi -fi - -# Test GUI -AC_ARG_ENABLE([testgui], - [AS_HELP_STRING([--enable-testgui], - [enable building of test GUI (default n)])], - [testgui_enabled=$enableval], - [testgui_enabled='no']) -AM_CONDITIONAL([BUILD_TESTGUI], [test "x$testgui_enabled" != "xno"]) - -# Configure the MacOS TestGUI app bundle -rm -Rf testgui/TestGUI.app -mkdir -p testgui/TestGUI.app -cp -R ${srcdir}/testgui/TestGUI.app.in/* testgui/TestGUI.app -chmod -R u+w testgui/TestGUI.app -mkdir testgui/TestGUI.app/Contents/MacOS/ - -if test "x$testgui_enabled" != "xno"; then - if test "x$os" = xdarwin; then - # On Mac OS, don't use pkg-config. - AC_CHECK_PROG([foxconfig], [fox-config], [fox-config], false) - if test "x$foxconfig" = "xfalse"; then - hidapi_prog_error fox-config "FOX Toolkit" - fi - LIBS_TESTGUI="${LIBS_TESTGUI} `$foxconfig --libs`" - LIBS_TESTGUI="${LIBS_TESTGUI} -framework Cocoa -L/usr/X11R6/lib" - CFLAGS_TESTGUI="${CFLAGS_TESTGUI} `$foxconfig --cflags`" - OBJCFLAGS="${OBJCFLAGS} -x objective-c++" - elif test "x$os" = xwindows; then - # On Windows, just set the paths for Fox toolkit - if test "x$win_implementation" = xmingw; then - CFLAGS_TESTGUI="-I\$(srcdir)/../../hidapi-externals/fox/include -g -c" - LIBS_TESTGUI=" -mwindows \$(srcdir)/../../hidapi-externals/fox/lib/libFOX-1.6.a -lgdi32 -Wl,--enable-auto-import -static-libgcc -static-libstdc++ -lkernel32" - else - # Cygwin - CFLAGS_TESTGUI="-DWIN32 -I\$(srcdir)/../../hidapi-externals/fox/include -g -c" - LIBS_TESTGUI="\$(srcdir)/../../hidapi-externals/fox/lib/libFOX-cygwin-1.6.a -lgdi32 -Wl,--enable-auto-import -static-libgcc -static-libstdc++ -lkernel32" - fi - else - # On Linux and FreeBSD platforms, use pkg-config to find fox. - PKG_CHECK_MODULES([fox], [fox17], [], [PKG_CHECK_MODULES([fox], [fox])]) - LIBS_TESTGUI="${LIBS_TESTGUI} $fox_LIBS" - if test "x$os" = xfreebsd; then - LIBS_TESTGUI="${LIBS_TESTGUI} -L/usr/local/lib" - fi - CFLAGS_TESTGUI="${CFLAGS_TESTGUI} $fox_CFLAGS" - fi -fi -AC_SUBST([LIBS_TESTGUI]) -AC_SUBST([CFLAGS_TESTGUI]) -AC_SUBST([backend]) - -# OS info for Automake -AM_CONDITIONAL(OS_LINUX, test "x$os" = xlinux) -AM_CONDITIONAL(OS_DARWIN, test "x$os" = xdarwin) -AM_CONDITIONAL(OS_FREEBSD, test "x$os" = xfreebsd) -AM_CONDITIONAL(OS_KFREEBSD, test "x$os" = xkfreebsd) -AM_CONDITIONAL(OS_HAIKU, test "x$os" = xhaiku) -AM_CONDITIONAL(OS_WINDOWS, test "x$os" = xwindows) - -AC_CONFIG_HEADERS([config.h]) - -if test "x$os" = "xlinux"; then - AC_CONFIG_FILES([pc/hidapi-hidraw.pc]) - AC_CONFIG_FILES([pc/hidapi-libusb.pc]) -else - AC_CONFIG_FILES([pc/hidapi.pc]) -fi - -AC_SUBST(LTLDFLAGS) - -AC_CONFIG_FILES([Makefile \ - hidtest/Makefile \ - libusb/Makefile \ - linux/Makefile \ - mac/Makefile \ - testgui/Makefile \ - windows/Makefile]) -AC_OUTPUT diff --git a/lib/hidapi/hidapi/hidapi.h b/lib/hidapi/hidapi/hidapi.h index efba3188bb9..3a2dab46e25 100644 --- a/lib/hidapi/hidapi/hidapi.h +++ b/lib/hidapi/hidapi/hidapi.h @@ -48,12 +48,12 @@ @ingroup API */ -#define HID_API_VERSION_MINOR 10 +#define HID_API_VERSION_MINOR 11 /** @brief Static/compile-time patch version of the library. @ingroup API */ -#define HID_API_VERSION_PATCH 1 +#define HID_API_VERSION_PATCH 2 /* Helper macros */ #define HID_API_AS_STR_IMPL(x) #x diff --git a/lib/hidapi/libusb/.gitignore b/lib/hidapi/libusb/.gitignore deleted file mode 100644 index 67460db93e8..00000000000 --- a/lib/hidapi/libusb/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.o -*.so -*.la -*.lo -*.a -.libs -.deps -hidtest-libusb diff --git a/lib/hidapi/libusb/Makefile-manual b/lib/hidapi/libusb/Makefile-manual deleted file mode 100644 index 0acf707a4d9..00000000000 --- a/lib/hidapi/libusb/Makefile-manual +++ /dev/null @@ -1,22 +0,0 @@ - - -OS=$(shell uname) - -ifeq ($(OS), Linux) - FILE=Makefile.linux -endif - -ifeq ($(OS), FreeBSD) - FILE=Makefile.freebsd -endif - -ifeq ($(OS), Haiku) - FILE=Makefile.haiku -endif - -ifeq ($(FILE), ) -all: - $(error Your platform ${OS} is not supported by hidapi/libusb at this time.) -endif - -include $(FILE) diff --git a/lib/hidapi/libusb/Makefile.am b/lib/hidapi/libusb/Makefile.am deleted file mode 100644 index 1da06bc1618..00000000000 --- a/lib/hidapi/libusb/Makefile.am +++ /dev/null @@ -1,34 +0,0 @@ -AM_CPPFLAGS = -I$(top_srcdir)/hidapi $(CFLAGS_LIBUSB) - -if OS_LINUX -lib_LTLIBRARIES = libhidapi-libusb.la -libhidapi_libusb_la_SOURCES = hid.c -libhidapi_libusb_la_LDFLAGS = $(LTLDFLAGS) $(PTHREAD_CFLAGS) -libhidapi_libusb_la_LIBADD = $(LIBS_LIBUSB) -endif - -if OS_FREEBSD -lib_LTLIBRARIES = libhidapi.la -libhidapi_la_SOURCES = hid.c -libhidapi_la_LDFLAGS = $(LTLDFLAGS) -libhidapi_la_LIBADD = $(LIBS_LIBUSB) -endif - -if OS_KFREEBSD -lib_LTLIBRARIES = libhidapi.la -libhidapi_la_SOURCES = hid.c -libhidapi_la_LDFLAGS = $(LTLDFLAGS) -libhidapi_la_LIBADD = $(LIBS_LIBUSB) -endif - -if OS_HAIKU -lib_LTLIBRARIES = libhidapi.la -libhidapi_la_SOURCES = hid.c -libhidapi_la_LDFLAGS = $(LTLDFLAGS) -libhidapi_la_LIBADD = $(LIBS_LIBUSB) -endif - -hdrdir = $(includedir)/hidapi -hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h - -EXTRA_DIST = Makefile-manual diff --git a/lib/hidapi/libusb/Makefile.freebsd b/lib/hidapi/libusb/Makefile.freebsd deleted file mode 100644 index cb24d6a9429..00000000000 --- a/lib/hidapi/libusb/Makefile.freebsd +++ /dev/null @@ -1,39 +0,0 @@ -########################################### -# Simple Makefile for HIDAPI test program -# -# Alan Ott -# Signal 11 Software -# 2010-06-01 -########################################### - -all: hidtest libs - -libs: libhidapi.so - -CC ?= cc -CFLAGS ?= -Wall -g -fPIC - -COBJS = hid.o ../hidtest/test.o -OBJS = $(COBJS) -INCLUDES = -I../hidapi -I/usr/local/include -LDFLAGS = -L/usr/local/lib -LIBS = -lusb -liconv -pthread - - -# Console Test Program -hidtest: $(OBJS) - $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@ $(LIBS) - -# Shared Libs -libhidapi.so: $(COBJS) - $(CC) $(LDFLAGS) -shared -Wl,-soname,$@.0 $^ -o $@ $(LIBS) - -# Objects -$(COBJS): %.o: %.c - $(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@ - - -clean: - rm -f $(OBJS) hidtest libhidapi.so ../hidtest/hidtest.o - -.PHONY: clean libs diff --git a/lib/hidapi/libusb/Makefile.haiku b/lib/hidapi/libusb/Makefile.haiku deleted file mode 100644 index 975e8ba6747..00000000000 --- a/lib/hidapi/libusb/Makefile.haiku +++ /dev/null @@ -1,39 +0,0 @@ -########################################### -# Simple Makefile for HIDAPI test program -# -# Alan Ott -# Signal 11 Software -# 2010-06-01 -########################################### - -all: hidtest libs - -libs: libhidapi.so - -CC ?= cc -CFLAGS ?= -Wall -g -fPIC - -COBJS = hid.o ../hidtest/test.o -OBJS = $(COBJS) -INCLUDES = -I../hidapi -I/usr/local/include -LDFLAGS = -L/usr/local/lib -LIBS = -lusb -liconv -pthread - - -# Console Test Program -hidtest: $(OBJS) - $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@ $(LIBS) - -# Shared Libs -libhidapi.so: $(COBJS) - $(CC) $(LDFLAGS) -shared -Wl,-soname,$@.0 $^ -o $@ $(LIBS) - -# Objects -$(COBJS): %.o: %.c - $(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@ - - -clean: - rm -f $(OBJS) hidtest libhidapi.so ../hidtest/hidtest.o - -.PHONY: clean libs diff --git a/lib/hidapi/libusb/Makefile.linux b/lib/hidapi/libusb/Makefile.linux deleted file mode 100644 index 4b338ec9b2c..00000000000 --- a/lib/hidapi/libusb/Makefile.linux +++ /dev/null @@ -1,42 +0,0 @@ -########################################### -# Simple Makefile for HIDAPI test program -# -# Alan Ott -# Signal 11 Software -# 2010-06-01 -########################################### - -all: hidtest-libusb libs - -libs: libhidapi-libusb.so - -CC ?= gcc -CFLAGS ?= -Wall -g -fpic - -LDFLAGS ?= -Wall -g - -COBJS_LIBUSB = hid.o -COBJS = $(COBJS_LIBUSB) ../hidtest/test.o -OBJS = $(COBJS) -LIBS_USB = `pkg-config libusb-1.0 --libs` -lrt -lpthread -LIBS = $(LIBS_USB) -INCLUDES ?= -I../hidapi `pkg-config libusb-1.0 --cflags` - - -# Console Test Program -hidtest-libusb: $(COBJS) - $(CC) $(LDFLAGS) $^ $(LIBS_USB) -o $@ - -# Shared Libs -libhidapi-libusb.so: $(COBJS_LIBUSB) - $(CC) $(LDFLAGS) $(LIBS_USB) -shared -fpic -Wl,-soname,$@.0 $^ -o $@ - -# Objects -$(COBJS): %.o: %.c - $(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@ - - -clean: - rm -f $(OBJS) hidtest-libusb libhidapi-libusb.so ../hidtest/hidtest.o - -.PHONY: clean libs diff --git a/lib/hidapi/libusb/hid.c b/lib/hidapi/libusb/hid.c index 0b8aa1e7f34..c9e86c07ad8 100644 --- a/lib/hidapi/libusb/hid.c +++ b/lib/hidapi/libusb/hid.c @@ -49,7 +49,7 @@ #include #endif -#include "hidapi.h" +#include "hidapi_libusb.h" #if defined(__ANDROID__) && __ANDROID_API__ < __ANDROID_API_N__ @@ -484,15 +484,29 @@ static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx) return str; } -static char *make_path(libusb_device *dev, int interface_number) +static char *make_path(libusb_device *dev, int interface_number, int config_number) { - char str[64]; - snprintf(str, sizeof(str), "%04x:%04x:%02x", - libusb_get_bus_number(dev), - libusb_get_device_address(dev), - interface_number); - str[sizeof(str)-1] = '\0'; - + char str[64]; /* max length "000-000.000.000.000.000.000.000:000.000" */ + /* Note that USB3 port count limit is 7; use 8 here for alignment */ + uint8_t port_numbers[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + int num_ports = libusb_get_port_numbers(dev, port_numbers, 8); + + if (num_ports > 0) { + int n = snprintf(str, sizeof("000-000"), "%u-%u", libusb_get_bus_number(dev), port_numbers[0]); + for (uint8_t i = 1; i < num_ports; i++) { + n += snprintf(&str[n], sizeof(".000"), ".%u", port_numbers[i]); + } + n += snprintf(&str[n], sizeof(":000.000"), ":%u.%u", (uint8_t)config_number, (uint8_t)interface_number); + str[n] = '\0'; + } else { + /* USB3.0 specs limit number of ports to 7 and buffer size here is 8 */ + if (num_ports == LIBUSB_ERROR_OVERFLOW) { + LOG("make_path() failed. buffer overflow error\n"); + } else { + LOG("make_path() failed. unknown error\n"); + } + str[0] = '\0'; + } return strdup(str); } @@ -555,12 +569,16 @@ struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, struct libusb_device_descriptor desc; struct libusb_config_descriptor *conf_desc = NULL; int j, k; - int interface_num = 0; int res = libusb_get_device_descriptor(dev, &desc); unsigned short dev_vid = desc.idVendor; unsigned short dev_pid = desc.idProduct; + if ((vendor_id != 0x0 && vendor_id != dev_vid) || + (product_id != 0x0 && product_id != dev_pid)) { + continue; + } + res = libusb_get_active_config_descriptor(dev, &conf_desc); if (res < 0) libusb_get_config_descriptor(dev, 0, &conf_desc); @@ -571,118 +589,124 @@ struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, const struct libusb_interface_descriptor *intf_desc; intf_desc = &intf->altsetting[k]; if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) { - interface_num = intf_desc->bInterfaceNumber; - - /* Check the VID/PID against the arguments */ - if ((vendor_id == 0x0 || vendor_id == dev_vid) && - (product_id == 0x0 || product_id == dev_pid)) { - struct hid_device_info *tmp; + int interface_num = intf_desc->bInterfaceNumber; + struct hid_device_info *tmp; - /* VID/PID match. Create the record. */ - tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); - if (cur_dev) { - cur_dev->next = tmp; - } - else { - root = tmp; - } - cur_dev = tmp; - - /* Fill out the record */ - cur_dev->next = NULL; - cur_dev->path = make_path(dev, interface_num); + /* VID/PID match. Create the record. */ + tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); + if (cur_dev) { + cur_dev->next = tmp; + } + else { + root = tmp; + } + cur_dev = tmp; + + /* Fill out the record */ + cur_dev->next = NULL; + cur_dev->path = make_path(dev, interface_num, conf_desc->bConfigurationValue); + + res = libusb_open(dev, &handle); + + if (res >= 0) { +#ifdef __ANDROID__ + /* There is (a potential) libusb Android backend, in which + device descriptor is not accurate up until the device is opened. + https://github.com/libusb/libusb/pull/874#discussion_r632801373 + A workaround is to re-read the descriptor again. + Even if it is not going to be accepted into libusb master, + having it here won't do any harm, since reading the device descriptor + is as cheap as copy 18 bytes of data. */ + libusb_get_device_descriptor(dev, &desc); +#endif - res = libusb_open(dev, &handle); + /* Serial Number */ + if (desc.iSerialNumber > 0) + cur_dev->serial_number = + get_usb_string(handle, desc.iSerialNumber); - if (res >= 0) { - /* Serial Number */ - if (desc.iSerialNumber > 0) - cur_dev->serial_number = - get_usb_string(handle, desc.iSerialNumber); - - /* Manufacturer and Product strings */ - if (desc.iManufacturer > 0) - cur_dev->manufacturer_string = - get_usb_string(handle, desc.iManufacturer); - if (desc.iProduct > 0) - cur_dev->product_string = - get_usb_string(handle, desc.iProduct); + /* Manufacturer and Product strings */ + if (desc.iManufacturer > 0) + cur_dev->manufacturer_string = + get_usb_string(handle, desc.iManufacturer); + if (desc.iProduct > 0) + cur_dev->product_string = + get_usb_string(handle, desc.iProduct); #ifdef INVASIVE_GET_USAGE { - /* - This section is removed because it is too - invasive on the system. Getting a Usage Page - and Usage requires parsing the HID Report - descriptor. Getting a HID Report descriptor - involves claiming the interface. Claiming the - interface involves detaching the kernel driver. - Detaching the kernel driver is hard on the system - because it will unclaim interfaces (if another - app has them claimed) and the re-attachment of - the driver will sometimes change /dev entry names. - It is for these reasons that this section is - #if 0. For composite devices, use the interface - field in the hid_device_info struct to distinguish - between interfaces. */ - unsigned char data[256]; + /* + This section is removed because it is too + invasive on the system. Getting a Usage Page + and Usage requires parsing the HID Report + descriptor. Getting a HID Report descriptor + involves claiming the interface. Claiming the + interface involves detaching the kernel driver. + Detaching the kernel driver is hard on the system + because it will unclaim interfaces (if another + app has them claimed) and the re-attachment of + the driver will sometimes change /dev entry names. + It is for these reasons that this section is + #if 0. For composite devices, use the interface + field in the hid_device_info struct to distinguish + between interfaces. */ + unsigned char data[256]; #ifdef DETACH_KERNEL_DRIVER - int detached = 0; - /* Usage Page and Usage */ - res = libusb_kernel_driver_active(handle, interface_num); - if (res == 1) { - res = libusb_detach_kernel_driver(handle, interface_num); - if (res < 0) - LOG("Couldn't detach kernel driver, even though a kernel driver was attached."); - else - detached = 1; - } + int detached = 0; + /* Usage Page and Usage */ + res = libusb_kernel_driver_active(handle, interface_num); + if (res == 1) { + res = libusb_detach_kernel_driver(handle, interface_num); + if (res < 0) + LOG("Couldn't detach kernel driver, even though a kernel driver was attached.\n"); + else + detached = 1; + } #endif - res = libusb_claim_interface(handle, interface_num); + res = libusb_claim_interface(handle, interface_num); + if (res >= 0) { + /* Get the HID Report Descriptor. */ + 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); if (res >= 0) { - /* Get the HID Report Descriptor. */ - 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); - if (res >= 0) { - unsigned short page=0, usage=0; - /* Parse the usage and usage page - out of the report descriptor. */ - get_usage(data, res, &page, &usage); - cur_dev->usage_page = page; - cur_dev->usage = usage; - } - else - LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res); - - /* Release the interface */ - res = libusb_release_interface(handle, interface_num); - if (res < 0) - LOG("Can't release the interface.\n"); + unsigned short page=0, usage=0; + /* Parse the usage and usage page + out of the report descriptor. */ + get_usage(data, res, &page, &usage); + cur_dev->usage_page = page; + cur_dev->usage = usage; } else - LOG("Can't claim interface %d\n", res); + LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res); + + /* Release the interface */ + res = libusb_release_interface(handle, interface_num); + if (res < 0) + LOG("Can't release the interface.\n"); + } + else + LOG("Can't claim interface %d\n", res); #ifdef DETACH_KERNEL_DRIVER - /* Re-attach kernel driver if necessary. */ - if (detached) { - res = libusb_attach_kernel_driver(handle, interface_num); - if (res < 0) - LOG("Couldn't re-attach kernel driver.\n"); - } + /* Re-attach kernel driver if necessary. */ + if (detached) { + res = libusb_attach_kernel_driver(handle, interface_num); + if (res < 0) + LOG("Couldn't re-attach kernel driver.\n"); + } #endif } #endif /* INVASIVE_GET_USAGE */ - libusb_close(handle); - } - /* VID/PID */ - cur_dev->vendor_id = dev_vid; - cur_dev->product_id = dev_pid; + libusb_close(handle); + } + /* VID/PID */ + cur_dev->vendor_id = dev_vid; + cur_dev->product_id = dev_pid; - /* Release Number */ - cur_dev->release_number = desc.bcdDevice; + /* Release Number */ + cur_dev->release_number = desc.bcdDevice; - /* Interface Number */ - cur_dev->interface_number = interface_num; - } + /* Interface Number */ + cur_dev->interface_number = interface_num; } } /* altsettings */ } /* interfaces */ @@ -885,13 +909,94 @@ static void *read_thread(void *param) } +static int hidapi_initialize_device(hid_device *dev, const struct libusb_interface_descriptor *intf_desc) +{ + int i =0; + int res = 0; + struct libusb_device_descriptor desc; + libusb_get_device_descriptor(libusb_get_device(dev->device_handle), &desc); + +#ifdef DETACH_KERNEL_DRIVER + /* Detach the kernel driver, but only if the + device is managed by the kernel */ + dev->is_driver_detached = 0; + if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) { + res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber); + if (res < 0) { + LOG("Unable to detach Kernel Driver\n"); + return 0; + } + else { + dev->is_driver_detached = 1; + LOG("Driver successfully detached from kernel.\n"); + } + } +#endif + res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber); + if (res < 0) { + LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res); + return 0; + } + + /* Store off the string descriptor indexes */ + dev->manufacturer_index = desc.iManufacturer; + dev->product_index = desc.iProduct; + dev->serial_index = desc.iSerialNumber; + + /* Store off the interface number */ + dev->interface = intf_desc->bInterfaceNumber; + + dev->input_endpoint = 0; + dev->input_ep_max_packet_size = 0; + dev->output_endpoint = 0; + + /* Find the INPUT and OUTPUT endpoints. An + OUTPUT endpoint is not required. */ + for (i = 0; i < intf_desc->bNumEndpoints; i++) { + const struct libusb_endpoint_descriptor *ep + = &intf_desc->endpoint[i]; + + /* Determine the type and direction of this + endpoint. */ + int is_interrupt = + (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) + == LIBUSB_TRANSFER_TYPE_INTERRUPT; + int is_output = + (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) + == LIBUSB_ENDPOINT_OUT; + int is_input = + (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) + == LIBUSB_ENDPOINT_IN; + + /* Decide whether to use it for input or output. */ + if (dev->input_endpoint == 0 && + is_interrupt && is_input) { + /* Use this endpoint for INPUT */ + dev->input_endpoint = ep->bEndpointAddress; + dev->input_ep_max_packet_size = ep->wMaxPacketSize; + } + if (dev->output_endpoint == 0 && + is_interrupt && is_output) { + /* Use this endpoint for OUTPUT */ + dev->output_endpoint = ep->bEndpointAddress; + } + } + + pthread_create(&dev->thread, NULL, read_thread, dev); + + /* Wait here for the read thread to be initialized. */ + pthread_barrier_wait(&dev->barrier); + return 1; +} + + hid_device * HID_API_EXPORT hid_open_path(const char *path) { hid_device *dev = NULL; - libusb_device **devs; - libusb_device *usb_dev; - int res; + libusb_device **devs = NULL; + libusb_device *usb_dev = NULL; + int res = 0; int d = 0; int good_open = 0; @@ -901,21 +1006,18 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path) dev = new_hid_device(); libusb_get_device_list(usb_context, &devs); - while ((usb_dev = devs[d++]) != NULL) { - struct libusb_device_descriptor desc; + while ((usb_dev = devs[d++]) != NULL && !good_open) { struct libusb_config_descriptor *conf_desc = NULL; - int i,j,k; - libusb_get_device_descriptor(usb_dev, &desc); + int j,k; if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0) continue; - for (j = 0; j < conf_desc->bNumInterfaces; j++) { + for (j = 0; j < conf_desc->bNumInterfaces && !good_open; j++) { const struct libusb_interface *intf = &conf_desc->interface[j]; - for (k = 0; k < intf->num_altsetting; k++) { - const struct libusb_interface_descriptor *intf_desc; - intf_desc = &intf->altsetting[k]; + for (k = 0; k < intf->num_altsetting && !good_open; k++) { + const struct libusb_interface_descriptor *intf_desc = &intf->altsetting[k]; if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) { - char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber); + char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber, conf_desc->bConfigurationValue); if (!strcmp(dev_path, path)) { /* Matched Paths. Open this device */ @@ -926,87 +1028,15 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path) free(dev_path); break; } - good_open = 1; -#ifdef DETACH_KERNEL_DRIVER - /* Detach the kernel driver, but only if the - device is managed by the kernel */ - dev->is_driver_detached = 0; - if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) { - res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber); - if (res < 0) { - libusb_close(dev->device_handle); - LOG("Unable to detach Kernel Driver\n"); - free(dev_path); - good_open = 0; - break; - } - else { - dev->is_driver_detached = 1; - LOG("Driver successfully detached from kernel.\n"); - } - } -#endif - res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber); - if (res < 0) { - LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res); - free(dev_path); + good_open = hidapi_initialize_device(dev, intf_desc); + if (!good_open) libusb_close(dev->device_handle); - good_open = 0; - break; - } - - /* Store off the string descriptor indexes */ - dev->manufacturer_index = desc.iManufacturer; - dev->product_index = desc.iProduct; - dev->serial_index = desc.iSerialNumber; - - /* Store off the interface number */ - dev->interface = intf_desc->bInterfaceNumber; - - /* Find the INPUT and OUTPUT endpoints. An - OUTPUT endpoint is not required. */ - for (i = 0; i < intf_desc->bNumEndpoints; i++) { - const struct libusb_endpoint_descriptor *ep - = &intf_desc->endpoint[i]; - - /* Determine the type and direction of this - endpoint. */ - int is_interrupt = - (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) - == LIBUSB_TRANSFER_TYPE_INTERRUPT; - int is_output = - (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) - == LIBUSB_ENDPOINT_OUT; - int is_input = - (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) - == LIBUSB_ENDPOINT_IN; - - /* Decide whether to use it for input or output. */ - if (dev->input_endpoint == 0 && - is_interrupt && is_input) { - /* Use this endpoint for INPUT */ - dev->input_endpoint = ep->bEndpointAddress; - dev->input_ep_max_packet_size = ep->wMaxPacketSize; - } - if (dev->output_endpoint == 0 && - is_interrupt && is_output) { - /* Use this endpoint for OUTPUT */ - dev->output_endpoint = ep->bEndpointAddress; - } - } - - pthread_create(&dev->thread, NULL, read_thread, dev); - - /* Wait here for the read thread to be initialized. */ - pthread_barrier_wait(&dev->barrier); - } free(dev_path); } } } libusb_free_config_descriptor(conf_desc); - } libusb_free_device_list(devs, 1); @@ -1023,12 +1053,92 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path) } +HID_API_EXPORT hid_device * HID_API_CALL hid_libusb_wrap_sys_device(intptr_t sys_dev, int interface_num) +{ +/* 0x01000107 is a LIBUSB_API_VERSION for 1.0.23 - version when libusb_wrap_sys_device was introduced */ +#if (!defined(HIDAPI_TARGET_LIBUSB_API_VERSION) || HIDAPI_TARGET_LIBUSB_API_VERSION >= 0x01000107) && (LIBUSB_API_VERSION >= 0x01000107) + hid_device *dev = NULL; + struct libusb_config_descriptor *conf_desc = NULL; + const struct libusb_interface_descriptor *selected_intf_desc = NULL; + int res = 0; + int j = 0, k = 0; + + if(hid_init() < 0) + return NULL; + + dev = new_hid_device(); + + res = libusb_wrap_sys_device(usb_context, sys_dev, &dev->device_handle); + if (res < 0) { + LOG("libusb_wrap_sys_device failed: %d %s\n", res, libusb_error_name(res)); + goto err; + } + + res = libusb_get_active_config_descriptor(libusb_get_device(dev->device_handle), &conf_desc); + if (res < 0) + libusb_get_config_descriptor(libusb_get_device(dev->device_handle), 0, &conf_desc); + + if (!conf_desc) { + LOG("Failed to get configuration descriptor: %d %s\n", res, libusb_error_name(res)); + goto err; + } + + /* find matching HID interface */ + for (j = 0; j < conf_desc->bNumInterfaces && !selected_intf_desc; j++) { + const struct libusb_interface *intf = &conf_desc->interface[j]; + for (k = 0; k < intf->num_altsetting; k++) { + const struct libusb_interface_descriptor *intf_desc = &intf->altsetting[k]; + if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) { + if (interface_num < 0 || interface_num == intf_desc->bInterfaceNumber) { + selected_intf_desc = intf_desc; + break; + } + } + } + } + + if (!selected_intf_desc) { + if (interface_num < 0) { + LOG("Sys USB device doesn't contain a HID interface\n"); + } + else { + LOG("Sys USB device doesn't contain a HID interface with number %d\n", interface_num); + } + goto err; + } + + if (!hidapi_initialize_device(dev, selected_intf_desc)) + goto err; + + return dev; + +err: + if (conf_desc) + libusb_free_config_descriptor(conf_desc); + if (dev->device_handle) + libusb_close(dev->device_handle); + free_hid_device(dev); +#else + (void)sys_dev; + (void)interface_num; + LOG("libusb_wrap_sys_device is not available\n"); +#endif + return NULL; +} + + int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) { int res; - int report_number = data[0]; + int report_number; int skipped_report_id = 0; + if (!data || (length ==0)) { + return -1; + } + + report_number = data[0]; + if (report_number == 0x0) { data++; length--; diff --git a/lib/hidapi/libusb/hidapi_libusb.h b/lib/hidapi/libusb/hidapi_libusb.h new file mode 100644 index 00000000000..1f56c2c51a9 --- /dev/null +++ b/lib/hidapi/libusb/hidapi_libusb.h @@ -0,0 +1,54 @@ +/******************************************************* + HIDAPI - Multi-Platform library for + communication with HID devices. + + libusb/hidapi Team + + Copyright 2021, All Rights Reserved. + + At the discretion of the user of this library, + this software may be licensed under the terms of the + GNU General Public License v3, a BSD-Style license, or the + original HIDAPI license as outlined in the LICENSE.txt, + LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt + files located at the root of the source distribution. + These files may also be found in the public source + code repository located at: + https://github.com/libusb/hidapi . +********************************************************/ + +/** @file + * @defgroup API hidapi API + */ + +#ifndef HIDAPI_LIBUSB_H__ +#define HIDAPI_LIBUSB_H__ + +#include + +#include "hidapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + /** @brief Open a HID device using libusb_wrap_sys_device. + See https://libusb.sourceforge.io/api-1.0/group__libusb__dev.html#ga98f783e115ceff4eaf88a60e6439563c, + for details on libusb_wrap_sys_device. + + @ingroup API + @param sys_dev Platform-specific file descriptor that can be recognised by libusb. + @param interface_num USB interface number of the device to be used as HID interface. + Pass -1 to select first HID interface of the device. + + @returns + This function returns a pointer to a #hid_device object on + success or NULL on failure. + */ + HID_API_EXPORT hid_device * HID_API_CALL hid_libusb_wrap_sys_device(intptr_t sys_dev, int interface_num); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/lib/hidapi/linux/.gitignore b/lib/hidapi/linux/.gitignore deleted file mode 100644 index 127bf37d9cf..00000000000 --- a/lib/hidapi/linux/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -Debug -Release -*.exp -*.ilk -*.lib -*.suo -*.vcproj.* -*.ncb -*.suo -*.dll -*.pdb -*.o -*.so -hidtest-hidraw -.deps -.libs -*.lo -*.la diff --git a/lib/hidapi/linux/Makefile-manual b/lib/hidapi/linux/Makefile-manual deleted file mode 100644 index 81d28cf2cb5..00000000000 --- a/lib/hidapi/linux/Makefile-manual +++ /dev/null @@ -1,42 +0,0 @@ -########################################### -# Simple Makefile for HIDAPI test program -# -# Alan Ott -# Signal 11 Software -# 2010-06-01 -########################################### - -all: hidtest-hidraw libs - -libs: libhidapi-hidraw.so - -CC ?= gcc -CFLAGS ?= -Wall -g -fpic - -LDFLAGS ?= -Wall -g - - -COBJS = hid.o ../hidtest/test.o -OBJS = $(COBJS) -LIBS_UDEV = `pkg-config libudev --libs` -lrt -LIBS = $(LIBS_UDEV) -INCLUDES ?= -I../hidapi `pkg-config libusb-1.0 --cflags` - - -# Console Test Program -hidtest-hidraw: $(COBJS) - $(CC) $(LDFLAGS) $^ $(LIBS_UDEV) -o $@ - -# Shared Libs -libhidapi-hidraw.so: $(COBJS) - $(CC) $(LDFLAGS) $(LIBS_UDEV) -shared -fpic -Wl,-soname,$@.0 $^ -o $@ - -# Objects -$(COBJS): %.o: %.c - $(CC) $(CFLAGS) -c $(INCLUDES) $< -o $@ - - -clean: - rm -f $(OBJS) hidtest-hidraw libhidapi-hidraw.so $(COBJS) - -.PHONY: clean libs diff --git a/lib/hidapi/linux/Makefile.am b/lib/hidapi/linux/Makefile.am deleted file mode 100644 index 230eeb75a20..00000000000 --- a/lib/hidapi/linux/Makefile.am +++ /dev/null @@ -1,10 +0,0 @@ -lib_LTLIBRARIES = libhidapi-hidraw.la -libhidapi_hidraw_la_SOURCES = hid.c -libhidapi_hidraw_la_LDFLAGS = $(LTLDFLAGS) -AM_CPPFLAGS = -I$(top_srcdir)/hidapi/ $(CFLAGS_HIDRAW) -libhidapi_hidraw_la_LIBADD = $(LIBS_HIDRAW) - -hdrdir = $(includedir)/hidapi -hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h - -EXTRA_DIST = Makefile-manual diff --git a/lib/hidapi/linux/hid.c b/lib/hidapi/linux/hid.c index 718541e5c19..c211fae20e4 100644 --- a/lib/hidapi/linux/hid.c +++ b/lib/hidapi/linux/hid.c @@ -45,6 +45,29 @@ #include "hidapi.h" +#ifdef HIDAPI_ALLOW_BUILD_WORKAROUND_KERNEL_2_6_39 +/* This definitions first appeared in Linux Kernel 2.6.39 in linux/hidraw.h. + hidapi doesn't support kernels older than that, + so we don't define macros below explicitly, to fail builds on old kernels. + For those who really need this as a workaround (e.g. to be able to build on old build machines), + can workaround by defining the macro above. +*/ +#ifndef HIDIOCSFEATURE +#define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len) +#endif +#ifndef HIDIOCGFEATURE +#define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len) +#endif + +#endif + + +// HIDIOCGINPUT is not defined in Linux kernel headers < 5.11. +// This definition is from hidraw.h in Linux >= 5.11. +// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f43d3870cafa2a0f3854c1819c8385733db8f9ae +#ifndef HIDIOCGINPUT +#define HIDIOCGINPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0A, len) +#endif /* USB HID device property names */ const char *device_string_names[] = { @@ -947,6 +970,12 @@ int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t { int bytes_written; + if (!data || (length == 0)) { + errno = EINVAL; + register_device_error(dev, strerror(errno)); + return -1; + } + bytes_written = write(dev->device_handle, data, length); register_device_error(dev, (bytes_written == -1)? strerror(errno): NULL); @@ -1043,13 +1072,15 @@ int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, return res; } -// Not supported by Linux HidRaw yet int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) { - (void)dev; - (void)data; - (void)length; - return -1; + int res; + + res = ioctl(dev->device_handle, HIDIOCGINPUT(length), data); + if (res < 0) + register_device_error_format(dev, "ioctl (GINPUT): %s", strerror(errno)); + + return res; } void HID_API_EXPORT hid_close(hid_device *dev) diff --git a/lib/hidapi/m4/.gitignore b/lib/hidapi/m4/.gitignore deleted file mode 100644 index 8f79b020444..00000000000 --- a/lib/hidapi/m4/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -# Ignore All, except pkg.m4, and of course this file. -* -!.gitignore -!pkg.m4 -!ax_pthread.m4 diff --git a/lib/hidapi/m4/ax_pthread.m4 b/lib/hidapi/m4/ax_pthread.m4 deleted file mode 100644 index d90de34d14b..00000000000 --- a/lib/hidapi/m4/ax_pthread.m4 +++ /dev/null @@ -1,309 +0,0 @@ -# =========================================================================== -# http://www.gnu.org/software/autoconf-archive/ax_pthread.html -# =========================================================================== -# -# SYNOPSIS -# -# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]]) -# -# DESCRIPTION -# -# This macro figures out how to build C programs using POSIX threads. It -# sets the PTHREAD_LIBS output variable to the threads library and linker -# flags, and the PTHREAD_CFLAGS output variable to any special C compiler -# flags that are needed. (The user can also force certain compiler -# flags/libs to be tested by setting these environment variables.) -# -# Also sets PTHREAD_CC to any special C compiler that is needed for -# multi-threaded programs (defaults to the value of CC otherwise). (This -# is necessary on AIX to use the special cc_r compiler alias.) -# -# NOTE: You are assumed to not only compile your program with these flags, -# but also link it with them as well. e.g. you should link with -# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS -# -# If you are only building threads programs, you may wish to use these -# variables in your default LIBS, CFLAGS, and CC: -# -# LIBS="$PTHREAD_LIBS $LIBS" -# CFLAGS="$CFLAGS $PTHREAD_CFLAGS" -# CC="$PTHREAD_CC" -# -# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant -# has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name -# (e.g. PTHREAD_CREATE_UNDETACHED on AIX). -# -# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the -# PTHREAD_PRIO_INHERIT symbol is defined when compiling with -# PTHREAD_CFLAGS. -# -# ACTION-IF-FOUND is a list of shell commands to run if a threads library -# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it -# is not found. If ACTION-IF-FOUND is not specified, the default action -# will define HAVE_PTHREAD. -# -# Please let the authors know if this macro fails on any platform, or if -# you have any other suggestions or comments. This macro was based on work -# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help -# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by -# Alejandro Forero Cuervo to the autoconf macro repository. We are also -# grateful for the helpful feedback of numerous users. -# -# Updated for Autoconf 2.68 by Daniel Richard G. -# -# LICENSE -# -# Copyright (c) 2008 Steven G. Johnson -# Copyright (c) 2011 Daniel Richard G. -# -# This program is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by the -# Free Software Foundation, either version 3 of the License, or (at your -# option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -# Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program. If not, see . -# -# As a special exception, the respective Autoconf Macro's copyright owner -# gives unlimited permission to copy, distribute and modify the configure -# scripts that are the output of Autoconf when processing the Macro. You -# need not follow the terms of the GNU General Public License when using -# or distributing such scripts, even though portions of the text of the -# Macro appear in them. The GNU General Public License (GPL) does govern -# all other use of the material that constitutes the Autoconf Macro. -# -# This special exception to the GPL applies to versions of the Autoconf -# Macro released by the Autoconf Archive. When you make and distribute a -# modified version of the Autoconf Macro, you may extend this special -# exception to the GPL to apply to your modified version as well. - -#serial 18 - -AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD]) -AC_DEFUN([AX_PTHREAD], [ -AC_REQUIRE([AC_CANONICAL_HOST]) -AC_LANG_PUSH([C]) -ax_pthread_ok=no - -# We used to check for pthread.h first, but this fails if pthread.h -# requires special compiler flags (e.g. on True64 or Sequent). -# It gets checked for in the link test anyway. - -# First of all, check if the user has set any of the PTHREAD_LIBS, -# etcetera environment variables, and if threads linking works using -# them: -if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then - save_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $PTHREAD_CFLAGS" - save_LIBS="$LIBS" - LIBS="$PTHREAD_LIBS $LIBS" - AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS]) - AC_TRY_LINK_FUNC(pthread_join, ax_pthread_ok=yes) - AC_MSG_RESULT($ax_pthread_ok) - if test x"$ax_pthread_ok" = xno; then - PTHREAD_LIBS="" - PTHREAD_CFLAGS="" - fi - LIBS="$save_LIBS" - CFLAGS="$save_CFLAGS" -fi - -# We must check for the threads library under a number of different -# names; the ordering is very important because some systems -# (e.g. DEC) have both -lpthread and -lpthreads, where one of the -# libraries is broken (non-POSIX). - -# Create a list of thread flags to try. Items starting with a "-" are -# C compiler flags, and other items are library names, except for "none" -# which indicates that we try without any flags at all, and "pthread-config" -# which is a program returning the flags for the Pth emulation library. - -ax_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config" - -# The ordering *is* (sometimes) important. Some notes on the -# individual items follow: - -# pthreads: AIX (must check this before -lpthread) -# none: in case threads are in libc; should be tried before -Kthread and -# other compiler flags to prevent continual compiler warnings -# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h) -# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able) -# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread) -# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads) -# -pthreads: Solaris/gcc -# -mthreads: Mingw32/gcc, Lynx/gcc -# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it -# doesn't hurt to check since this sometimes defines pthreads too; -# also defines -D_REENTRANT) -# ... -mt is also the pthreads flag for HP/aCC -# pthread: Linux, etcetera -# --thread-safe: KAI C++ -# pthread-config: use pthread-config program (for GNU Pth library) - -case ${host_os} in - solaris*) - - # On Solaris (at least, for some versions), libc contains stubbed - # (non-functional) versions of the pthreads routines, so link-based - # tests will erroneously succeed. (We need to link with -pthreads/-mt/ - # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather - # a function called by this macro, so we could check for that, but - # who knows whether they'll stub that too in a future libc.) So, - # we'll just look for -pthreads and -lpthread first: - - ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags" - ;; - - darwin*) - ax_pthread_flags="-pthread $ax_pthread_flags" - ;; -esac - -if test x"$ax_pthread_ok" = xno; then -for flag in $ax_pthread_flags; do - - case $flag in - none) - AC_MSG_CHECKING([whether pthreads work without any flags]) - ;; - - -*) - AC_MSG_CHECKING([whether pthreads work with $flag]) - PTHREAD_CFLAGS="$flag" - ;; - - pthread-config) - AC_CHECK_PROG(ax_pthread_config, pthread-config, yes, no) - if test x"$ax_pthread_config" = xno; then continue; fi - PTHREAD_CFLAGS="`pthread-config --cflags`" - PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`" - ;; - - *) - AC_MSG_CHECKING([for the pthreads library -l$flag]) - PTHREAD_LIBS="-l$flag" - ;; - esac - - save_LIBS="$LIBS" - save_CFLAGS="$CFLAGS" - LIBS="$PTHREAD_LIBS $LIBS" - CFLAGS="$CFLAGS $PTHREAD_CFLAGS" - - # Check for various functions. We must include pthread.h, - # since some functions may be macros. (On the Sequent, we - # need a special flag -Kthread to make this header compile.) - # We check for pthread_join because it is in -lpthread on IRIX - # while pthread_create is in libc. We check for pthread_attr_init - # due to DEC craziness with -lpthreads. We check for - # pthread_cleanup_push because it is one of the few pthread - # functions on Solaris that doesn't have a non-functional libc stub. - # We try pthread_create on general principles. - AC_LINK_IFELSE([AC_LANG_PROGRAM([#include - static void routine(void *a) { a = 0; } - static void *start_routine(void *a) { return a; }], - [pthread_t th; pthread_attr_t attr; - pthread_create(&th, 0, start_routine, 0); - pthread_join(th, 0); - pthread_attr_init(&attr); - pthread_cleanup_push(routine, 0); - pthread_cleanup_pop(0) /* ; */])], - [ax_pthread_ok=yes], - []) - - LIBS="$save_LIBS" - CFLAGS="$save_CFLAGS" - - AC_MSG_RESULT($ax_pthread_ok) - if test "x$ax_pthread_ok" = xyes; then - break; - fi - - PTHREAD_LIBS="" - PTHREAD_CFLAGS="" -done -fi - -# Various other checks: -if test "x$ax_pthread_ok" = xyes; then - save_LIBS="$LIBS" - LIBS="$PTHREAD_LIBS $LIBS" - save_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $PTHREAD_CFLAGS" - - # Detect AIX lossage: JOINABLE attribute is called UNDETACHED. - AC_MSG_CHECKING([for joinable pthread attribute]) - attr_name=unknown - for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do - AC_LINK_IFELSE([AC_LANG_PROGRAM([#include ], - [int attr = $attr; return attr /* ; */])], - [attr_name=$attr; break], - []) - done - AC_MSG_RESULT($attr_name) - if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then - AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name, - [Define to necessary symbol if this constant - uses a non-standard name on your system.]) - fi - - AC_MSG_CHECKING([if more special flags are required for pthreads]) - flag=no - case ${host_os} in - aix* | freebsd* | darwin*) flag="-D_THREAD_SAFE";; - osf* | hpux*) flag="-D_REENTRANT";; - solaris*) - if test "$GCC" = "yes"; then - flag="-D_REENTRANT" - else - flag="-mt -D_REENTRANT" - fi - ;; - esac - AC_MSG_RESULT(${flag}) - if test "x$flag" != xno; then - PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS" - fi - - AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT], - ax_cv_PTHREAD_PRIO_INHERIT, [ - AC_LINK_IFELSE([ - AC_LANG_PROGRAM([[#include ]], [[int i = PTHREAD_PRIO_INHERIT;]])], - [ax_cv_PTHREAD_PRIO_INHERIT=yes], - [ax_cv_PTHREAD_PRIO_INHERIT=no]) - ]) - AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"], - AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], 1, [Have PTHREAD_PRIO_INHERIT.])) - - LIBS="$save_LIBS" - CFLAGS="$save_CFLAGS" - - # More AIX lossage: must compile with xlc_r or cc_r - if test x"$GCC" != xyes; then - AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC}) - else - PTHREAD_CC=$CC - fi -else - PTHREAD_CC="$CC" -fi - -AC_SUBST(PTHREAD_LIBS) -AC_SUBST(PTHREAD_CFLAGS) -AC_SUBST(PTHREAD_CC) - -# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND: -if test x"$ax_pthread_ok" = xyes; then - ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1]) - : -else - ax_pthread_ok=no - $2 -fi -AC_LANG_POP -])dnl AX_PTHREAD diff --git a/lib/hidapi/m4/pkg.m4 b/lib/hidapi/m4/pkg.m4 deleted file mode 100644 index 0048a3fa054..00000000000 --- a/lib/hidapi/m4/pkg.m4 +++ /dev/null @@ -1,157 +0,0 @@ -# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- -# -# Copyright © 2004 Scott James Remnant . -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - -# PKG_PROG_PKG_CONFIG([MIN-VERSION]) -# ---------------------------------- -AC_DEFUN([PKG_PROG_PKG_CONFIG], -[m4_pattern_forbid([^_?PKG_[A-Z_]+$]) -m4_pattern_allow([^PKG_CONFIG(_PATH)?$]) -AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl -if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then - AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) -fi -if test -n "$PKG_CONFIG"; then - _pkg_min_version=m4_default([$1], [0.9.0]) - AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) - if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then - AC_MSG_RESULT([yes]) - else - AC_MSG_RESULT([no]) - PKG_CONFIG="" - fi - -fi[]dnl -])# PKG_PROG_PKG_CONFIG - -# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) -# -# Check to see whether a particular set of modules exists. Similar -# to PKG_CHECK_MODULES(), but does not set variables or print errors. -# -# -# Similar to PKG_CHECK_MODULES, make sure that the first instance of -# this or PKG_CHECK_MODULES is called, or make sure to call -# PKG_CHECK_EXISTS manually -# -------------------------------------------------------------- -AC_DEFUN([PKG_CHECK_EXISTS], -[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl -if test -n "$PKG_CONFIG" && \ - AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then - m4_ifval([$2], [$2], [:]) -m4_ifvaln([$3], [else - $3])dnl -fi]) - - -# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) -# --------------------------------------------- -m4_define([_PKG_CONFIG], -[if test -n "$PKG_CONFIG"; then - if test -n "$$1"; then - pkg_cv_[]$1="$$1" - else - PKG_CHECK_EXISTS([$3], - [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`], - [pkg_failed=yes]) - fi -else - pkg_failed=untried -fi[]dnl -])# _PKG_CONFIG - -# _PKG_SHORT_ERRORS_SUPPORTED -# ----------------------------- -AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], -[AC_REQUIRE([PKG_PROG_PKG_CONFIG]) -if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then - _pkg_short_errors_supported=yes -else - _pkg_short_errors_supported=no -fi[]dnl -])# _PKG_SHORT_ERRORS_SUPPORTED - - -# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], -# [ACTION-IF-NOT-FOUND]) -# -# -# Note that if there is a possibility the first call to -# PKG_CHECK_MODULES might not happen, you should be sure to include an -# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac -# -# -# -------------------------------------------------------------- -AC_DEFUN([PKG_CHECK_MODULES], -[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl -AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl -AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl - -pkg_failed=no -AC_MSG_CHECKING([for $1]) - -_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) -_PKG_CONFIG([$1][_LIBS], [libs], [$2]) - -m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS -and $1[]_LIBS to avoid the need to call pkg-config. -See the pkg-config man page for more details.]) - -if test $pkg_failed = yes; then - _PKG_SHORT_ERRORS_SUPPORTED - if test $_pkg_short_errors_supported = yes; then - $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"` - else - $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"` - fi - # Put the nasty error message in config.log where it belongs - echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD - - ifelse([$4], , [AC_MSG_ERROR(dnl -[Package requirements ($2) were not met: - -$$1_PKG_ERRORS - -Consider adjusting the PKG_CONFIG_PATH environment variable if you -installed software in a non-standard prefix. - -_PKG_TEXT -])], - [AC_MSG_RESULT([no]) - $4]) -elif test $pkg_failed = untried; then - ifelse([$4], , [AC_MSG_FAILURE(dnl -[The pkg-config script could not be found or is too old. Make sure it -is in your PATH or set the PKG_CONFIG environment variable to the full -path to pkg-config. - -_PKG_TEXT - -To get pkg-config, see .])], - [$4]) -else - $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS - $1[]_LIBS=$pkg_cv_[]$1[]_LIBS - AC_MSG_RESULT([yes]) - ifelse([$3], , :, [$3]) -fi[]dnl -])# PKG_CHECK_MODULES diff --git a/lib/hidapi/mac/.gitignore b/lib/hidapi/mac/.gitignore deleted file mode 100644 index 7cc3f0d0d68..00000000000 --- a/lib/hidapi/mac/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -Debug -Release -*.exp -*.ilk -*.lib -*.suo -*.vcproj.* -*.ncb -*.suo -*.dll -*.pdb -*.o -hidapi-hidtest -.deps -.libs -*.la -*.lo diff --git a/lib/hidapi/mac/Makefile-manual b/lib/hidapi/mac/Makefile-manual deleted file mode 100644 index dec422764f0..00000000000 --- a/lib/hidapi/mac/Makefile-manual +++ /dev/null @@ -1,27 +0,0 @@ -########################################### -# Simple Makefile for HIDAPI test program -# -# Alan Ott -# Signal 11 Software -# 2010-07-03 -########################################### - -all: hidtest - -CC=gcc -COBJS=hid.o ../hidtest/test.o -OBJS=$(COBJS) -CFLAGS+=-I../hidapi -Wall -g -c -LIBS=-framework IOKit -framework CoreFoundation -framework AppKit - - -hidtest: $(OBJS) - $(CC) -Wall -g $^ $(LIBS) -o hidtest - -$(COBJS): %.o: %.c - $(CC) $(CFLAGS) $< -o $@ - -clean: - rm -f *.o hidtest - -.PHONY: clean diff --git a/lib/hidapi/mac/Makefile.am b/lib/hidapi/mac/Makefile.am deleted file mode 100644 index 23d96e08fb6..00000000000 --- a/lib/hidapi/mac/Makefile.am +++ /dev/null @@ -1,9 +0,0 @@ -lib_LTLIBRARIES = libhidapi.la -libhidapi_la_SOURCES = hid.c -libhidapi_la_LDFLAGS = $(LTLDFLAGS) -AM_CPPFLAGS = -I$(top_srcdir)/hidapi/ - -hdrdir = $(includedir)/hidapi -hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h - -EXTRA_DIST = Makefile-manual diff --git a/lib/hidapi/mac/hid.c b/lib/hidapi/mac/hid.c index d88a9ade4cd..12648d9cfeb 100644 --- a/lib/hidapi/mac/hid.c +++ b/lib/hidapi/mac/hid.c @@ -314,64 +314,6 @@ static wchar_t *dup_wcs(const wchar_t *s) return ret; } -/* hidapi_IOHIDDeviceGetService() - * - * Return the io_service_t corresponding to a given IOHIDDeviceRef, either by: - * - on OS X 10.6 and above, calling IOHIDDeviceGetService() - * - on OS X 10.5, extract it from the IOHIDDevice struct - */ -static io_service_t hidapi_IOHIDDeviceGetService(IOHIDDeviceRef device) -{ - static void *iokit_framework = NULL; - typedef io_service_t (*dynamic_IOHIDDeviceGetService_t)(IOHIDDeviceRef device); - static dynamic_IOHIDDeviceGetService_t dynamic_IOHIDDeviceGetService = NULL; - - /* Use dlopen()/dlsym() to get a pointer to IOHIDDeviceGetService() if it exists. - * If any of these steps fail, dynamic_IOHIDDeviceGetService will be left NULL - * and the fallback method will be used. - */ - if (iokit_framework == NULL) { - iokit_framework = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_LAZY); - - if (iokit_framework != NULL) - dynamic_IOHIDDeviceGetService = (dynamic_IOHIDDeviceGetService_t) dlsym(iokit_framework, "IOHIDDeviceGetService"); - } - - if (dynamic_IOHIDDeviceGetService != NULL) { - /* Running on OS X 10.6 and above: IOHIDDeviceGetService() exists */ - return dynamic_IOHIDDeviceGetService(device); - } - else - { - /* Running on OS X 10.5: IOHIDDeviceGetService() doesn't exist. - * - * Be naughty and pull the service out of the IOHIDDevice. - * IOHIDDevice is an opaque struct not exposed to applications, but its - * layout is stable through all available versions of OS X. - * Tested and working on OS X 10.5.8 i386, x86_64, and ppc. - */ - struct IOHIDDevice_internal { - /* The first field of the IOHIDDevice struct is a - * CFRuntimeBase (which is a private CF struct). - * - * a, b, and c are the 3 fields that make up a CFRuntimeBase. - * See http://opensource.apple.com/source/CF/CF-476.18/CFRuntime.h - * - * The second field of the IOHIDDevice is the io_service_t we're looking for. - */ - uintptr_t a; - uint8_t b[4]; -#if __LP64__ - uint32_t c; -#endif - io_service_t service; - }; - struct IOHIDDevice_internal *tmp = (struct IOHIDDevice_internal *) device; - - return tmp->service; - } -} - /* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */ static int init_hid_manager(void) { @@ -439,7 +381,7 @@ static struct hid_device_info *create_device_info_with_usage(IOHIDDeviceRef dev, struct hid_device_info *cur_dev; io_object_t iokit_dev; kern_return_t res; - io_string_t path; + uint64_t entry_id; if (dev == NULL) { return NULL; @@ -459,13 +401,30 @@ static struct hid_device_info *create_device_info_with_usage(IOHIDDeviceRef dev, /* Fill out the record */ cur_dev->next = NULL; - /* Fill in the path (IOService plane) */ - iokit_dev = hidapi_IOHIDDeviceGetService(dev); - res = IORegistryEntryGetPath(iokit_dev, kIOServicePlane, path); - if (res == KERN_SUCCESS) - cur_dev->path = strdup(path); - else + /* Fill in the path (as a unique ID of the service entry) */ + cur_dev->path = NULL; + iokit_dev = IOHIDDeviceGetService(dev); + if (iokit_dev != MACH_PORT_NULL) { + res = IORegistryEntryGetRegistryEntryID(iokit_dev, &entry_id); + } + else { + res = KERN_INVALID_ARGUMENT; + } + + if (res == KERN_SUCCESS) { + /* max value of entry_id(uint64_t) is 18446744073709551615 which is 20 characters long, + so for (max) "path" string 'DevSrvsID:18446744073709551615' we would need + 9+1+20+1=31 bytes byffer, but allocate 32 for simple alignment */ + cur_dev->path = calloc(1, 32); + if (cur_dev->path != NULL) { + sprintf(cur_dev->path, "DevSrvsID:%llu", entry_id); + } + } + + if (cur_dev->path == NULL) { + /* for whatever reason, trying to keep it a non-NULL string */ cur_dev->path = strdup(""); + } /* Serial Number */ get_serial_number(dev, buf, BUF_LEN); @@ -817,11 +776,33 @@ static void *read_thread(void *param) return NULL; } -/* hid_open_path() - * - * path must be a valid path to an IOHIDDevice in the IOService plane - * Example: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver" - */ +/* \p path must be one of: + - in format 'DevSrvsID:' (as returned by hid_enumerate); + - a valid path to an IOHIDDevice in the IOService plane (as returned by IORegistryEntryGetPath, + e.g.: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver"); + Second format is for compatibility with paths accepted by older versions of HIDAPI. +*/ +static io_registry_entry_t hid_open_service_registry_from_path(const char *path) +{ + if (path == NULL) + return MACH_PORT_NULL; + + /* Get the IORegistry entry for the given path */ + if (strncmp("DevSrvsID:", path, 10) == 0) { + char *endptr; + uint64_t entry_id = strtoull(path + 10, &endptr, 10); + if (*endptr == '\0') { + return IOServiceGetMatchingService(kIOMasterPortDefault, IORegistryEntryIDMatching(entry_id)); + } + } + else { + /* Fallback to older format of the path */ + return IORegistryEntryFromPath(kIOMasterPortDefault, path); + } + + return MACH_PORT_NULL; +} + hid_device * HID_API_EXPORT hid_open_path(const char *path) { hid_device *dev = NULL; @@ -835,7 +816,7 @@ hid_device * HID_API_EXPORT hid_open_path(const char *path) dev = new_hid_device(); /* Get the IORegistry entry for the given path */ - entry = IORegistryEntryFromPath(kIOMasterPortDefault, path); + entry = hid_open_service_registry_from_path(path); if (entry == MACH_PORT_NULL) { /* Path wasn't valid (maybe device was removed?) */ goto return_error; @@ -898,7 +879,13 @@ static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char const unsigned char *data_to_send = data; CFIndex length_to_send = length; IOReturn res; - const unsigned char report_id = data[0]; + unsigned char report_id; + + if (!data || (length == 0)) { + return -1; + } + + report_id = data[0]; if (report_id == 0x0) { /* Not using numbered Reports. diff --git a/lib/hidapi/pc/.gitignore b/lib/hidapi/pc/.gitignore deleted file mode 100644 index 6fd0ef029e1..00000000000 --- a/lib/hidapi/pc/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pc diff --git a/lib/hidapi/pc/hidapi-hidraw.pc.in b/lib/hidapi/pc/hidapi-hidraw.pc.in deleted file mode 100644 index e20558d5a34..00000000000 --- a/lib/hidapi/pc/hidapi-hidraw.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: hidapi-hidraw -Description: C Library for USB/Bluetooth HID device access from Linux, Mac OS X, FreeBSD, and Windows. This is the hidraw implementation. -Version: @VERSION@ -Libs: -L${libdir} -lhidapi-hidraw -Cflags: -I${includedir}/hidapi diff --git a/lib/hidapi/pc/hidapi-libusb.pc.in b/lib/hidapi/pc/hidapi-libusb.pc.in deleted file mode 100644 index 2e49506553f..00000000000 --- a/lib/hidapi/pc/hidapi-libusb.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: hidapi-libusb -Description: C Library for USB HID device access from Linux, Mac OS X, FreeBSD, and Windows. This is the libusb implementation. -Version: @VERSION@ -Libs: -L${libdir} -lhidapi-libusb -Cflags: -I${includedir}/hidapi diff --git a/lib/hidapi/pc/hidapi.pc.in b/lib/hidapi/pc/hidapi.pc.in deleted file mode 100644 index 5835c99bf59..00000000000 --- a/lib/hidapi/pc/hidapi.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: hidapi -Description: C Library for USB/Bluetooth HID device access from Linux, Mac OS X, FreeBSD, and Windows. -Version: @VERSION@ -Libs: -L${libdir} -lhidapi -Cflags: -I${includedir}/hidapi diff --git a/lib/hidapi/udev/69-hid.rules b/lib/hidapi/udev/69-hid.rules new file mode 100644 index 00000000000..a27113ca873 --- /dev/null +++ b/lib/hidapi/udev/69-hid.rules @@ -0,0 +1,36 @@ +# This is a sample udev file for HIDAPI devices which lets unprivileged +# users who are physically present at the system (not remote users) access +# HID devices. + +# If you are using the libusb implementation of hidapi (libusb/hid.c), then +# use something like the following line, substituting the VID and PID with +# those of your device. + +# HIDAPI/libusb +SUBSYSTEMS=="usb", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="003f", TAG+="uaccess" + +# If you are using the hidraw implementation (linux/hid.c), then do something +# like the following, substituting the VID and PID with your device. + +# HIDAPI/hidraw +KERNEL=="hidraw*", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="003f", TAG+="uaccess" + +# Once done, optionally rename this file for your application, and drop it into +# /etc/udev/rules.d/. +# NOTE: these rules must have priorty before 73-seat-late.rules. +# (Small discussion/explanation in systemd repo: +# https://github.com/systemd/systemd/issues/4288#issuecomment-348166161) +# for example, name the file /etc/udev/rules.d/70-my-application-hid.rules. +# Then, replug your device or run: +# sudo udevadm control --reload-rules && sudo udevadm trigger + +# Note that the hexadecimal values for VID and PID are case sensitive and +# must be lower case. + +# TAG+="uaccess" only gives permission to physically present users, which +# is appropriate in most scenarios. If you require access to the device +# from a remote session (e.g. over SSH), add +# GROUP="plugdev", MODE="660" +# to the end of the udev rule lines, add your user to the plugdev group with: +# usermod -aG plugdev USERNAME +# then log out and log back in (or restart the system). diff --git a/lib/hidapi/udev/99-hid.rules b/lib/hidapi/udev/99-hid.rules deleted file mode 100644 index 0385f50b051..00000000000 --- a/lib/hidapi/udev/99-hid.rules +++ /dev/null @@ -1,33 +0,0 @@ -# This is a sample udev file for HIDAPI devices which changes the permissions -# to 0666 (world readable/writable) for a specified device on Linux systems. - - -# If you are using the libusb implementation of hidapi (libusb/hid.c), then -# use something like the following line, substituting the VID and PID with -# those of your device. Note that for kernels before 2.6.24, you will need -# to substitute "usb" with "usb_device". It shouldn't hurt to use two lines -# (one each way) for compatibility with older systems. - -# HIDAPI/libusb -SUBSYSTEM=="usb", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="003f", MODE="0666" - - -# If you are using the hidraw implementation (linux/hid.c), then do something -# like the following, substituting the VID and PID with your device. Busnum 1 -# is USB. - -# HIDAPI/hidraw -KERNEL=="hidraw*", ATTRS{busnum}=="1", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="003f", MODE="0666" - -# Once done, optionally rename this file for your device, and drop it into -# /etc/udev/rules.d and unplug and re-plug your device. This is all that is -# necessary to see the new permissions. Udev does not have to be restarted. - -# Note that the hexadecimal values for VID and PID are case sensitive and -# must be lower case. - -# If you think permissions of 0666 are too loose, then see: -# http://reactivated.net/writing_udev_rules.html for more information on finer -# grained permission setting. For example, it might be sufficient to just -# set the group or user owner for specific devices (for example the plugdev -# group on some systems). diff --git a/lib/hidapi/windows/.gitignore b/lib/hidapi/windows/.gitignore deleted file mode 100644 index c2ad395ec0b..00000000000 --- a/lib/hidapi/windows/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -Debug -Release -.vs/ -*.exp -*.ilk -*.lib -*.suo -*.vcproj.* -*.vcxproj.* -*.ncb -*.suo -*.dll -*.pdb -.deps -.libs -*.lo -*.la diff --git a/lib/hidapi/windows/Makefile-manual b/lib/hidapi/windows/Makefile-manual deleted file mode 100644 index ac471d66dad..00000000000 --- a/lib/hidapi/windows/Makefile-manual +++ /dev/null @@ -1,14 +0,0 @@ - - -OS=$(shell uname) - -ifneq (,$(findstring MINGW,$(OS))) - FILE=Makefile.mingw -endif - -ifeq ($(FILE), ) -all: - $(error Your platform ${OS} is not supported at this time.) -endif - -include $(FILE) diff --git a/lib/hidapi/windows/Makefile.am b/lib/hidapi/windows/Makefile.am deleted file mode 100644 index 97e261ac9ee..00000000000 --- a/lib/hidapi/windows/Makefile.am +++ /dev/null @@ -1,16 +0,0 @@ -lib_LTLIBRARIES = libhidapi.la -libhidapi_la_SOURCES = hid.c -libhidapi_la_LDFLAGS = $(LTLDFLAGS) -AM_CPPFLAGS = -I$(top_srcdir)/hidapi/ -libhidapi_la_LIBADD = $(LIBS) - -hdrdir = $(includedir)/hidapi -hdr_HEADERS = $(top_srcdir)/hidapi/hidapi.h - -EXTRA_DIST = \ - ddk_build \ - hidapi.vcproj \ - hidtest.vcproj \ - Makefile-manual \ - Makefile.mingw \ - hidapi.sln diff --git a/lib/hidapi/windows/Makefile.mingw b/lib/hidapi/windows/Makefile.mingw deleted file mode 100644 index 2407158b383..00000000000 --- a/lib/hidapi/windows/Makefile.mingw +++ /dev/null @@ -1,30 +0,0 @@ -########################################### -# Simple Makefile for HIDAPI test program -# -# Alan Ott -# Signal 11 Software -# 2010-06-01 -########################################### - -all: hidtest libhidapi.dll - -CC=gcc -COBJS=hid.o ../hidtest/test.o -OBJS=$(COBJS) -CFLAGS=-I../hidapi -g -c -LIBS= -lsetupapi -DLL_LDFLAGS = -mwindows -lsetupapi - -hidtest: $(OBJS) - $(CC) -g $^ $(LIBS) -o hidtest - -libhidapi.dll: $(OBJS) - $(CC) -g $^ $(DLL_LDFLAGS) -o libhidapi.dll - -$(COBJS): %.o: %.c - $(CC) $(CFLAGS) $< -o $@ - -clean: - rm *.o ../hidtest/*.o hidtest.exe - -.PHONY: clean diff --git a/lib/hidapi/windows/hid.c b/lib/hidapi/windows/hid.c old mode 100755 new mode 100644 index 57cb78dac8b..9ed98703545 --- a/lib/hidapi/windows/hid.c +++ b/lib/hidapi/windows/hid.c @@ -8,7 +8,7 @@ 8/22/2009 Copyright 2009, All Rights Reserved. - + At the discretion of the user of this library, this software may be licensed under the terms of the GNU General Public License v3, a BSD-Style license, or the @@ -20,6 +20,12 @@ https://github.com/libusb/hidapi . ********************************************************/ +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +// Do not warn about mbsrtowcs and wcsncpy usage. +// https://docs.microsoft.com/cpp/c-runtime-library/security-features-in-the-crt +#define _CRT_SECURE_NO_WARNINGS +#endif + #include #ifndef _NTDEF_ @@ -27,6 +33,7 @@ typedef LONG NTSTATUS; #endif #ifdef __MINGW32__ +#include #include #include #endif @@ -63,18 +70,14 @@ extern "C" { #include #include - +#include +#include #include "hidapi.h" #undef MIN #define MIN(x,y) ((x) < (y)? (x): (y)) -#ifdef _MSC_VER - /* Thanks Microsoft, but I know how to use strncpy(). */ - #pragma warning(disable:4996) -#endif - #ifdef __cplusplus extern "C" { #endif @@ -110,6 +113,7 @@ static struct hid_api_version api_version = { typedef void* PHIDP_PREPARSED_DATA; #define HIDP_STATUS_SUCCESS 0x110000 + typedef void (__stdcall *HidD_GetHidGuid_)(LPGUID hid_guid); typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib); typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len); typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len); @@ -123,6 +127,7 @@ static struct hid_api_version api_version = { typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS *caps); typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers); + static HidD_GetHidGuid_ HidD_GetHidGuid; static HidD_GetAttributes_ HidD_GetAttributes; static HidD_GetSerialNumberString_ HidD_GetSerialNumberString; static HidD_GetManufacturerString_ HidD_GetManufacturerString; @@ -138,19 +143,51 @@ static struct hid_api_version api_version = { static HMODULE lib_handle = NULL; static BOOLEAN initialized = FALSE; + + typedef DWORD RETURN_TYPE; + typedef RETURN_TYPE CONFIGRET; + typedef DWORD DEVNODE, DEVINST; + typedef DEVNODE* PDEVNODE, * PDEVINST; + typedef WCHAR* DEVNODEID_W, * DEVINSTID_W; + +#define CR_SUCCESS (0x00000000) +#define CR_BUFFER_SMALL (0x0000001A) + +#define CM_LOCATE_DEVNODE_NORMAL 0x00000000 + +#define DEVPROP_TYPEMOD_LIST 0x00002000 + +#define DEVPROP_TYPE_STRING 0x00000012 +#define DEVPROP_TYPE_STRING_LIST (DEVPROP_TYPE_STRING|DEVPROP_TYPEMOD_LIST) + + typedef CONFIGRET(__stdcall* CM_Locate_DevNodeW_)(PDEVINST pdnDevInst, DEVINSTID_W pDeviceID, ULONG ulFlags); + typedef CONFIGRET(__stdcall* CM_Get_Parent_)(PDEVINST pdnDevInst, DEVINST dnDevInst, ULONG ulFlags); + typedef CONFIGRET(__stdcall* CM_Get_DevNode_PropertyW_)(DEVINST dnDevInst, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); + typedef CONFIGRET(__stdcall* CM_Get_Device_Interface_PropertyW_)(LPCWSTR pszDeviceInterface, CONST DEVPROPKEY* PropertyKey, DEVPROPTYPE* PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); + + static CM_Locate_DevNodeW_ CM_Locate_DevNodeW = NULL; + static CM_Get_Parent_ CM_Get_Parent = NULL; + static CM_Get_DevNode_PropertyW_ CM_Get_DevNode_PropertyW = NULL; + static CM_Get_Device_Interface_PropertyW_ CM_Get_Device_Interface_PropertyW = NULL; + + static HMODULE cfgmgr32_lib_handle = NULL; #endif /* HIDAPI_USE_DDK */ struct hid_device_ { HANDLE device_handle; BOOL blocking; USHORT output_report_length; + unsigned char *write_buf; size_t input_report_length; + USHORT feature_report_length; + unsigned char *feature_buf; void *last_error_str; DWORD last_error_num; BOOL read_pending; char *read_buf; OVERLAPPED ol; - OVERLAPPED write_ol; + OVERLAPPED write_ol; + struct hid_device_info* device_info; }; static hid_device *new_hid_device() @@ -159,7 +196,10 @@ static hid_device *new_hid_device() dev->device_handle = INVALID_HANDLE_VALUE; dev->blocking = TRUE; dev->output_report_length = 0; + dev->write_buf = NULL; dev->input_report_length = 0; + dev->feature_report_length = 0; + dev->feature_buf = NULL; dev->last_error_str = NULL; dev->last_error_num = 0; dev->read_pending = FALSE; @@ -167,7 +207,8 @@ static hid_device *new_hid_device() memset(&dev->ol, 0, sizeof(dev->ol)); dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); memset(&dev->write_ol, 0, sizeof(dev->write_ol)); - dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*inital state f=nonsignaled*/, NULL); + dev->write_ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*inital state f=nonsignaled*/, NULL); + dev->device_info = NULL; return dev; } @@ -175,10 +216,13 @@ static hid_device *new_hid_device() static void free_hid_device(hid_device *dev) { CloseHandle(dev->ol.hEvent); - CloseHandle(dev->write_ol.hEvent); + CloseHandle(dev->write_ol.hEvent); CloseHandle(dev->device_handle); LocalFree(dev->last_error_str); + free(dev->write_buf); + free(dev->feature_buf); free(dev->read_buf); + hid_free_enumeration(dev->device_info); free(dev); } @@ -194,13 +238,13 @@ static void register_error(hid_device *dev, const char *op) MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&msg, 0/*sz*/, NULL); - + /* Get rid of the CR and LF that FormatMessage() sticks at the end of the message. Thanks Microsoft! */ ptr = msg; while (*ptr) { - if (*ptr == '\r') { - *ptr = 0x0000; + if (*ptr == L'\r') { + *ptr = L'\0'; break; } ptr++; @@ -222,6 +266,7 @@ static int lookup_functions() # pragma GCC diagnostic ignored "-Wcast-function-type" #endif #define RESOLVE(x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) return -1; + RESOLVE(HidD_GetHidGuid); RESOLVE(HidD_GetAttributes); RESOLVE(HidD_GetSerialNumberString); RESOLVE(HidD_GetManufacturerString); @@ -242,6 +287,29 @@ static int lookup_functions() else return -1; + cfgmgr32_lib_handle = LoadLibraryA("cfgmgr32.dll"); + if (cfgmgr32_lib_handle) { +#if defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wcast-function-type" +#endif +#define RESOLVE(x) x = (x##_)GetProcAddress(cfgmgr32_lib_handle, #x); + RESOLVE(CM_Locate_DevNodeW); + RESOLVE(CM_Get_Parent); + RESOLVE(CM_Get_DevNode_PropertyW); + RESOLVE(CM_Get_Device_Interface_PropertyW); +#undef RESOLVE +#if defined(__GNUC__) +# pragma GCC diagnostic pop +#endif + } + else { + CM_Locate_DevNodeW = NULL; + CM_Get_Parent = NULL; + CM_Get_DevNode_PropertyW = NULL; + CM_Get_Device_Interface_PropertyW = NULL; + } + return 0; } #endif @@ -293,50 +361,298 @@ int HID_API_EXPORT hid_exit(void) if (lib_handle) FreeLibrary(lib_handle); lib_handle = NULL; + if (cfgmgr32_lib_handle) + FreeLibrary(cfgmgr32_lib_handle); + cfgmgr32_lib_handle = NULL; initialized = FALSE; #endif return 0; } +static void hid_internal_get_ble_info(struct hid_device_info* dev, DEVINST dev_node) +{ + ULONG len; + CONFIGRET cr; + DEVPROPTYPE property_type; + + static DEVPROPKEY DEVPKEY_NAME = { { 0xb725f130, 0x47ef, 0x101a, 0xa5, 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac }, 10 }; // DEVPROP_TYPE_STRING + static DEVPROPKEY PKEY_DeviceInterface_Bluetooth_DeviceAddress = { { 0x2BD67D8B, 0x8BEB, 0x48D5, 0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A }, 1 }; // DEVPROP_TYPE_STRING + static DEVPROPKEY PKEY_DeviceInterface_Bluetooth_Manufacturer = { { 0x2BD67D8B, 0x8BEB, 0x48D5, 0x87, 0xE0, 0x6C, 0xDA, 0x34, 0x28, 0x04, 0x0A }, 4 }; // DEVPROP_TYPE_STRING + + /* Manufacturer String */ + len = 0; + cr = CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_Manufacturer, &property_type, NULL, &len, 0); + if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) { + free(dev->manufacturer_string); + dev->manufacturer_string = (wchar_t*)calloc(len, sizeof(BYTE)); + CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_Manufacturer, &property_type, (PBYTE)dev->manufacturer_string, &len, 0); + } + + /* Serial Number String (MAC Address) */ + len = 0; + cr = CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_DeviceAddress, &property_type, NULL, &len, 0); + if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) { + free(dev->serial_number); + dev->serial_number = (wchar_t*)calloc(len, sizeof(BYTE)); + CM_Get_DevNode_PropertyW(dev_node, &PKEY_DeviceInterface_Bluetooth_DeviceAddress, &property_type, (PBYTE)dev->serial_number, &len, 0); + } + + /* Get devnode grandparent to reach out Bluetooth LE device node */ + cr = CM_Get_Parent(&dev_node, dev_node, 0); + if (cr != CR_SUCCESS) + return; + + /* Product String */ + len = 0; + cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_NAME, &property_type, NULL, &len, 0); + if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) { + free(dev->product_string); + dev->product_string = (wchar_t*)calloc(len, sizeof(BYTE)); + CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_NAME, &property_type, (PBYTE)dev->product_string, &len, 0); + } +} + +/* USB Device Interface Number. + It can be parsed out of the Hardware ID if a USB device is has multiple interfaces (composite device). + See https://docs.microsoft.com/windows-hardware/drivers/hid/hidclass-hardware-ids-for-top-level-collections + and https://docs.microsoft.com/windows-hardware/drivers/install/standard-usb-identifiers + + hardware_id is always expected to be uppercase. +*/ +static int hid_internal_get_interface_number(const wchar_t* hardware_id) +{ + int interface_number; + wchar_t *startptr, *endptr; + const wchar_t *interface_token = L"&MI_"; + + startptr = wcsstr(hardware_id, interface_token); + if (!startptr) + return -1; + + startptr += wcslen(interface_token); + interface_number = wcstol(startptr, &endptr, 16); + if (endptr == startptr) + return -1; + + return interface_number; +} + +static void hid_internal_get_info(struct hid_device_info* dev) +{ + const char *tmp = NULL; + wchar_t *interface_path = NULL, *device_id = NULL, *compatible_ids = NULL, *hardware_ids = NULL; + mbstate_t state; + ULONG len; + CONFIGRET cr; + DEVPROPTYPE property_type; + DEVINST dev_node; + + static DEVPROPKEY DEVPKEY_Device_InstanceId = { { 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57 }, 256 }; // DEVPROP_TYPE_STRING + static DEVPROPKEY DEVPKEY_Device_HardwareIds = { { 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}, 3 }; // DEVPROP_TYPE_STRING_LIST + static DEVPROPKEY DEVPKEY_Device_CompatibleIds = { { 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}, 4 }; // DEVPROP_TYPE_STRING_LIST + + if (!CM_Get_Device_Interface_PropertyW || + !CM_Locate_DevNodeW || + !CM_Get_Parent || + !CM_Get_DevNode_PropertyW) + goto end; + + tmp = dev->path; + + len = (ULONG)strlen(tmp); + interface_path = (wchar_t*)calloc(len + 1, sizeof(wchar_t)); + memset(&state, 0, sizeof(state)); + + if (mbsrtowcs(interface_path, &tmp, len, &state) == (size_t)-1) + goto end; + + /* Get the device id from interface path */ + len = 0; + cr = CM_Get_Device_Interface_PropertyW(interface_path, &DEVPKEY_Device_InstanceId, &property_type, NULL, &len, 0); + if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING) { + device_id = (wchar_t*)calloc(len, sizeof(BYTE)); + cr = CM_Get_Device_Interface_PropertyW(interface_path, &DEVPKEY_Device_InstanceId, &property_type, (PBYTE)device_id, &len, 0); + } + if (cr != CR_SUCCESS) + goto end; + + /* Open devnode from device id */ + cr = CM_Locate_DevNodeW(&dev_node, (DEVINSTID_W)device_id, CM_LOCATE_DEVNODE_NORMAL); + if (cr != CR_SUCCESS) + goto end; + + /* Get the hardware ids from devnode */ + len = 0; + cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_HardwareIds, &property_type, NULL, &len, 0); + if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING_LIST) { + hardware_ids = (wchar_t*)calloc(len, sizeof(BYTE)); + cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_HardwareIds, &property_type, (PBYTE)hardware_ids, &len, 0); + } + if (cr != CR_SUCCESS) + goto end; + + // Search for interface number in hardware ids + for (wchar_t* hardware_id = hardware_ids; *hardware_id; hardware_id += wcslen(hardware_id) + 1) { + /* Normalize to upper case */ + for (wchar_t* p = hardware_id; *p; ++p) *p = towupper(*p); + + dev->interface_number = hid_internal_get_interface_number(hardware_id); + + if (dev->interface_number != -1) + break; + } + + /* Get devnode parent */ + cr = CM_Get_Parent(&dev_node, dev_node, 0); + if (cr != CR_SUCCESS) + goto end; + + /* Get the compatible ids from parent devnode */ + len = 0; + cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_CompatibleIds, &property_type, NULL, &len, 0); + if (cr == CR_BUFFER_SMALL && property_type == DEVPROP_TYPE_STRING_LIST) { + compatible_ids = (wchar_t*)calloc(len, sizeof(BYTE)); + cr = CM_Get_DevNode_PropertyW(dev_node, &DEVPKEY_Device_CompatibleIds, &property_type, (PBYTE)compatible_ids, &len, 0); + } + if (cr != CR_SUCCESS) + goto end; + + /* Now we can parse parent's compatible IDs to find out the device bus type */ + for (wchar_t* compatible_id = compatible_ids; *compatible_id; compatible_id += wcslen(compatible_id) + 1) { + /* Normalize to upper case */ + for (wchar_t* p = compatible_id; *p; ++p) *p = towupper(*p); + + /* Bluetooth LE devices */ + if (wcsstr(compatible_id, L"BTHLEDEVICE") != NULL) { + /* HidD_GetProductString/HidD_GetManufacturerString/HidD_GetSerialNumberString is not working for BLE HID devices + Request this info via dev node properties instead. + https://docs.microsoft.com/answers/questions/401236/hidd-getproductstring-with-ble-hid-device.html */ + hid_internal_get_ble_info(dev, dev_node); + break; + } + } +end: + free(interface_path); + free(device_id); + free(hardware_ids); + free(compatible_ids); +} + +static struct hid_device_info *hid_get_device_info(const char *path, HANDLE handle) +{ + struct hid_device_info *dev = NULL; /* return object */ + + BOOL res; + HIDD_ATTRIBUTES attrib; + PHIDP_PREPARSED_DATA pp_data = NULL; + HIDP_CAPS caps; + + #define WSTR_LEN 512 + wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */ + + /* Create the record. */ + dev = (struct hid_device_info*)calloc(1, sizeof(struct hid_device_info)); + + /* Fill out the record */ + dev->next = NULL; + + if (path) { + size_t len = strlen(path); + dev->path = (char*)calloc(len + 1, sizeof(char)); + memcpy(dev->path, path, len + 1); + } + else + dev->path = NULL; + + attrib.Size = sizeof(HIDD_ATTRIBUTES); + res = HidD_GetAttributes(handle, &attrib); + if (res) { + /* VID/PID */ + dev->vendor_id = attrib.VendorID; + dev->product_id = attrib.ProductID; + + /* Release Number */ + dev->release_number = attrib.VersionNumber; + } + + /* Get the Usage Page and Usage for this device. */ + res = HidD_GetPreparsedData(handle, &pp_data); + if (res) { + NTSTATUS nt_res = HidP_GetCaps(pp_data, &caps); + if (nt_res == HIDP_STATUS_SUCCESS) { + dev->usage_page = caps.UsagePage; + dev->usage = caps.Usage; + } + + HidD_FreePreparsedData(pp_data); + } + + /* Serial Number */ + wstr[0] = L'\0'; + res = HidD_GetSerialNumberString(handle, wstr, sizeof(wstr)); + wstr[WSTR_LEN - 1] = L'\0'; + dev->serial_number = _wcsdup(wstr); + + /* Manufacturer String */ + wstr[0] = L'\0'; + res = HidD_GetManufacturerString(handle, wstr, sizeof(wstr)); + wstr[WSTR_LEN - 1] = L'\0'; + dev->manufacturer_string = _wcsdup(wstr); + + /* Product String */ + wstr[0] = L'\0'; + res = HidD_GetProductString(handle, wstr, sizeof(wstr)); + wstr[WSTR_LEN - 1] = L'\0'; + dev->product_string = _wcsdup(wstr); + + hid_internal_get_info(dev); + + return dev; +} + struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id) { BOOL res; struct hid_device_info *root = NULL; /* return object */ struct hid_device_info *cur_dev = NULL; + GUID interface_class_guid; /* Windows objects for interacting with the driver. */ - GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} }; SP_DEVINFO_DATA devinfo_data; SP_DEVICE_INTERFACE_DATA device_interface_data; SP_DEVICE_INTERFACE_DETAIL_DATA_A *device_interface_detail_data = NULL; HDEVINFO device_info_set = INVALID_HANDLE_VALUE; + char driver_name[256]; int device_index = 0; - int i; if (hid_init() < 0) return NULL; + /* Retrieve HID Interface Class GUID + https://docs.microsoft.com/windows-hardware/drivers/install/guid-devinterface-hid */ + HidD_GetHidGuid(&interface_class_guid); + /* Initialize the Windows objects. */ memset(&devinfo_data, 0x0, sizeof(devinfo_data)); devinfo_data.cbSize = sizeof(SP_DEVINFO_DATA); device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); /* Get information for all the devices belonging to the HID class. */ - device_info_set = SetupDiGetClassDevsA(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); - + device_info_set = SetupDiGetClassDevsA(&interface_class_guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); + /* Iterate over each device in the HID class, looking for the right one. */ - + for (;;) { - HANDLE write_handle = INVALID_HANDLE_VALUE; + HANDLE read_handle = INVALID_HANDLE_VALUE; DWORD required_size = 0; HIDD_ATTRIBUTES attrib; res = SetupDiEnumDeviceInterfaces(device_info_set, NULL, - &InterfaceClassGuid, + &interface_class_guid, device_index, &device_interface_data); - + if (!res) { /* A return of FALSE from this function means that there are no more devices. */ @@ -373,49 +689,34 @@ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned shor goto cont; } - /* Make sure this device is of Setup Class "HIDClass" and has a - driver bound to it. */ - for (i = 0; ; i++) { - char driver_name[256]; - - /* Populate devinfo_data. This function will return failure - when there are no more interfaces left. */ - res = SetupDiEnumDeviceInfo(device_info_set, i, &devinfo_data); - if (!res) - goto cont; - - res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data, - SPDRP_CLASS, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL); - if (!res) - goto cont; - - if ((strcmp(driver_name, "HIDClass") == 0) || - (strcmp(driver_name, "Mouse") == 0) || - (strcmp(driver_name, "Keyboard") == 0)) { - /* See if there's a driver bound. */ - res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data, - SPDRP_DRIVER, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL); - if (res) - break; - } - } + /* Populate devinfo_data. This function will return failure + when the device with such index doesn't exist. We've already checked it does. */ + res = SetupDiEnumDeviceInfo(device_info_set, device_index, &devinfo_data); + if (!res) + goto cont; + + + /* Make sure this device has a driver bound to it. */ + res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data, + SPDRP_DRIVER, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL); + if (!res) + goto cont; //wprintf(L"HandleName: %s\n", device_interface_detail_data->DevicePath); - /* Open a handle to the device */ - write_handle = open_device(device_interface_detail_data->DevicePath, FALSE); + /* Open read-only handle to the device */ + read_handle = open_device(device_interface_detail_data->DevicePath, FALSE); - /* Check validity of write_handle. */ - if (write_handle == INVALID_HANDLE_VALUE) { + /* Check validity of read_handle. */ + if (read_handle == INVALID_HANDLE_VALUE) { /* Unable to open the device. */ //register_error(dev, "CreateFile"); - goto cont_close; - } - + goto cont; + } /* Get the Vendor ID and Product ID for this device. */ attrib.Size = sizeof(HIDD_ATTRIBUTES); - HidD_GetAttributes(write_handle, &attrib); + HidD_GetAttributes(read_handle, &attrib); //wprintf(L"Product/Vendor: %x %x\n", attrib.ProductID, attrib.VendorID); /* Check the VID/PID to see if we should add this @@ -423,17 +724,13 @@ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned shor if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) && (product_id == 0x0 || attrib.ProductID == product_id)) { - #define WSTR_LEN 512 - const char *str; - struct hid_device_info *tmp; - PHIDP_PREPARSED_DATA pp_data = NULL; - HIDP_CAPS caps; - NTSTATUS nt_res; - wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */ - size_t len; - /* VID/PID match. Create the record. */ - tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); + struct hid_device_info *tmp = hid_get_device_info(device_interface_detail_data->DevicePath, read_handle); + + if (tmp == NULL) { + goto cont_close; + } + if (cur_dev) { cur_dev->next = tmp; } @@ -441,84 +738,10 @@ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned shor root = tmp; } cur_dev = tmp; - - /* Get the Usage Page and Usage for this device. */ - res = HidD_GetPreparsedData(write_handle, &pp_data); - if (res) { - nt_res = HidP_GetCaps(pp_data, &caps); - if (nt_res == HIDP_STATUS_SUCCESS) { - cur_dev->usage_page = caps.UsagePage; - cur_dev->usage = caps.Usage; - } - - HidD_FreePreparsedData(pp_data); - } - - /* Fill out the record */ - cur_dev->next = NULL; - str = device_interface_detail_data->DevicePath; - if (str) { - len = strlen(str); - cur_dev->path = (char*) calloc(len+1, sizeof(char)); - strncpy(cur_dev->path, str, len+1); - cur_dev->path[len] = '\0'; - } - else - cur_dev->path = NULL; - - /* Serial Number */ - wstr[0]= 0x0000; - res = HidD_GetSerialNumberString(write_handle, wstr, sizeof(wstr)); - wstr[WSTR_LEN-1] = 0x0000; - if (res) { - cur_dev->serial_number = _wcsdup(wstr); - } - - /* Manufacturer String */ - wstr[0]= 0x0000; - res = HidD_GetManufacturerString(write_handle, wstr, sizeof(wstr)); - wstr[WSTR_LEN-1] = 0x0000; - if (res) { - cur_dev->manufacturer_string = _wcsdup(wstr); - } - - /* Product String */ - wstr[0]= 0x0000; - res = HidD_GetProductString(write_handle, wstr, sizeof(wstr)); - wstr[WSTR_LEN-1] = 0x0000; - if (res) { - cur_dev->product_string = _wcsdup(wstr); - } - - /* VID/PID */ - cur_dev->vendor_id = attrib.VendorID; - cur_dev->product_id = attrib.ProductID; - - /* Release Number */ - cur_dev->release_number = attrib.VersionNumber; - - /* Interface Number. It can sometimes be parsed out of the path - on Windows if a device has multiple interfaces. See - http://msdn.microsoft.com/en-us/windows/hardware/gg487473 or - search for "Hardware IDs for HID Devices" at MSDN. If it's not - in the path, it's set to -1. */ - cur_dev->interface_number = -1; - if (cur_dev->path) { - char *interface_component = strstr(cur_dev->path, "&mi_"); - if (interface_component) { - char *hex_str = interface_component + 4; - char *endptr = NULL; - cur_dev->interface_number = strtol(hex_str, &endptr, 16); - if (endptr == hex_str) { - /* The parsing failed. Set interface_number to -1. */ - cur_dev->interface_number = -1; - } - } - } } cont_close: - CloseHandle(write_handle); + CloseHandle(read_handle); cont: /* We no longer need the detail data. It can be freed */ free(device_interface_detail_data); @@ -531,7 +754,6 @@ struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned shor SetupDiDestroyDeviceInfoList(device_info_set); return root; - } void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs) @@ -556,7 +778,7 @@ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsi struct hid_device_info *devs, *cur_dev; const char *path_to_open = NULL; hid_device *handle = NULL; - + devs = hid_enumerate(vendor_id, product_id); cur_dev = devs; while (cur_dev) { @@ -582,75 +804,64 @@ HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsi } hid_free_enumeration(devs); - + return handle; } HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path) { - hid_device *dev; - HIDP_CAPS caps; + hid_device *dev = NULL; + HANDLE device_handle = INVALID_HANDLE_VALUE; PHIDP_PREPARSED_DATA pp_data = NULL; - BOOLEAN res; - NTSTATUS nt_res; - - if (hid_init() < 0) { - return NULL; - } + HIDP_CAPS caps; - dev = new_hid_device(); + if (hid_init() < 0) + goto end_of_function; /* Open a handle to the device */ - dev->device_handle = open_device(path, TRUE); + device_handle = open_device(path, TRUE); /* Check validity of write_handle. */ - if (dev->device_handle == INVALID_HANDLE_VALUE) { + if (device_handle == INVALID_HANDLE_VALUE) { /* System devices, such as keyboards and mice, cannot be opened in read-write mode, because the system takes exclusive control over them. This is to prevent keyloggers. However, feature reports can still be sent and received. Retry opening the device, but without read/write access. */ - dev->device_handle = open_device(path, FALSE); + device_handle = open_device(path, FALSE); /* Check the validity of the limited device_handle. */ - if (dev->device_handle == INVALID_HANDLE_VALUE) { - /* Unable to open the device, even without read-write mode. */ - register_error(dev, "CreateFile"); - goto err; - } + if (device_handle == INVALID_HANDLE_VALUE) + goto end_of_function; } /* Set the Input Report buffer size to 64 reports. */ - res = HidD_SetNumInputBuffers(dev->device_handle, 64); - if (!res) { - register_error(dev, "HidD_SetNumInputBuffers"); - goto err; - } + if (!HidD_SetNumInputBuffers(device_handle, 64)) + goto end_of_function; /* Get the Input Report length for the device. */ - res = HidD_GetPreparsedData(dev->device_handle, &pp_data); - if (!res) { - register_error(dev, "HidD_GetPreparsedData"); - goto err; - } - nt_res = HidP_GetCaps(pp_data, &caps); - if (nt_res != HIDP_STATUS_SUCCESS) { - register_error(dev, "HidP_GetCaps"); - goto err_pp_data; - } + if (!HidD_GetPreparsedData(device_handle, &pp_data)) + goto end_of_function; + + if (HidP_GetCaps(pp_data, &caps) != HIDP_STATUS_SUCCESS) + goto end_of_function; + + dev = new_hid_device(); + + dev->device_handle = device_handle; + device_handle = INVALID_HANDLE_VALUE; + dev->output_report_length = caps.OutputReportByteLength; dev->input_report_length = caps.InputReportByteLength; - HidD_FreePreparsedData(pp_data); - + dev->feature_report_length = caps.FeatureReportByteLength; dev->read_buf = (char*) malloc(dev->input_report_length); + dev->device_info = hid_get_device_info(path, dev->device_handle); - return dev; +end_of_function: + CloseHandle(device_handle); + HidD_FreePreparsedData(pp_data); -err_pp_data: - HidD_FreePreparsedData(pp_data); -err: - free_hid_device(dev); - return NULL; + return dev; } int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length) @@ -662,26 +873,31 @@ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char * unsigned char *buf; + if (!data || (length==0)) { + register_error(dev, "Zero length buffer"); + return function_result; + } + /* Make sure the right number of bytes are passed to WriteFile. Windows expects the number of bytes which are in the _longest_ report (plus one for the report number) bytes even if the data is a report which is shorter than that. Windows gives us this value in caps.OutputReportByteLength. If a user passes in fewer bytes than this, - create a temporary buffer which is the proper size. */ + use cached temporary buffer which is the proper size. */ if (length >= dev->output_report_length) { /* The user passed the right number of bytes. Use the buffer as-is. */ buf = (unsigned char *) data; } else { - /* Create a temporary buffer and copy the user's data - into it, padding the rest with zeros. */ - buf = (unsigned char *) malloc(dev->output_report_length); + if (dev->write_buf == NULL) + dev->write_buf = (unsigned char *) malloc(dev->output_report_length); + buf = dev->write_buf; memcpy(buf, data, length); memset(buf + length, 0, dev->output_report_length - length); length = dev->output_report_length; } res = WriteFile(dev->device_handle, buf, (DWORD) length, NULL, &dev->write_ol); - + if (!res) { if (GetLastError() != ERROR_IO_PENDING) { /* WriteFile() failed. Return error. */ @@ -714,9 +930,6 @@ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char * } end_of_function: - if (buf != data) - free(buf); - return function_result; } @@ -737,7 +950,7 @@ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char memset(dev->read_buf, 0, dev->input_report_length); ResetEvent(ev); res = ReadFile(dev->device_handle, dev->read_buf, (DWORD) dev->input_report_length, &bytes_read, &dev->ol); - + if (!res) { if (GetLastError() != ERROR_IO_PENDING) { /* ReadFile() has failed. @@ -746,11 +959,11 @@ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char dev->read_pending = FALSE; goto end_of_function; } - overlapped = TRUE; - } + overlapped = TRUE; + } } else { - overlapped = TRUE; + overlapped = TRUE; } if (overlapped) { @@ -788,13 +1001,13 @@ int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char memcpy(data, dev->read_buf, copy_len); } } - + end_of_function: if (!res) { register_error(dev, "GetOverlappedResult"); return -1; } - + return (int) copy_len; } @@ -811,7 +1024,29 @@ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonbloc int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) { - BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, (DWORD) length); + BOOL res = FALSE; + unsigned char *buf; + size_t length_to_send; + + /* Windows expects at least caps.FeatureReportByteLength bytes passed + to HidD_SetFeature(), even if the report is shorter. Any less sent and + the function fails with error ERROR_INVALID_PARAMETER set. Any more + and HidD_SetFeature() silently truncates the data sent in the report + to caps.FeatureReportByteLength. */ + if (length >= dev->feature_report_length) { + buf = (unsigned char *) data; + length_to_send = length; + } else { + if (dev->feature_buf == NULL) + dev->feature_buf = (unsigned char *) malloc(dev->feature_report_length); + buf = dev->feature_buf; + memcpy(buf, data, length); + memset(buf + length, 0, dev->feature_report_length - length); + length_to_send = dev->feature_report_length; + } + + res = HidD_SetFeature(dev->device_handle, (PVOID)buf, (DWORD) length_to_send); + if (!res) { register_error(dev, "HidD_SetFeature"); return -1; @@ -820,25 +1055,16 @@ int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const u return (int) length; } - -int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) +static int hid_get_report(hid_device *dev, DWORD report_type, unsigned char *data, size_t length) { BOOL res; -#if 0 - res = HidD_GetFeature(dev->device_handle, data, length); - if (!res) { - register_error(dev, "HidD_GetFeature"); - return -1; - } - return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */ -#else - DWORD bytes_returned; + DWORD bytes_returned = 0; OVERLAPPED ol; memset(&ol, 0, sizeof(ol)); res = DeviceIoControl(dev->device_handle, - IOCTL_HID_GET_FEATURE, + report_type, data, (DWORD) length, data, (DWORD) length, &bytes_returned, &ol); @@ -846,7 +1072,7 @@ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned if (!res) { if (GetLastError() != ERROR_IO_PENDING) { /* DeviceIoControl() failed. Return error. */ - register_error(dev, "Send Feature Report DeviceIoControl"); + register_error(dev, "Get Input/Feature Report DeviceIoControl"); return -1; } } @@ -856,66 +1082,30 @@ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/); if (!res) { /* The operation failed. */ - register_error(dev, "Send Feature Report GetOverLappedResult"); + register_error(dev, "Get Input/Feature Report GetOverLappedResult"); return -1; } - /* bytes_returned does not include the first byte which contains the - report ID. The data buffer actually contains one more byte than - bytes_returned. */ - bytes_returned++; + /* When numbered reports aren't used, + bytes_returned seem to include only what is actually received from the device + (not including the first byte with 0, as an indication "no numbered reports"). */ + if (data[0] == 0x0) { + bytes_returned++; + } return bytes_returned; -#endif } +int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) +{ + /* We could use HidD_GetFeature() instead, but it doesn't give us an actual length, unfortunately */ + return hid_get_report(dev, IOCTL_HID_GET_FEATURE, data, length); +} int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length) { - BOOL res; -#if 0 - res = HidD_GetInputReport(dev->device_handle, data, length); - if (!res) { - register_error(dev, "HidD_GetInputReport"); - return -1; - } - return length; -#else - DWORD bytes_returned; - - OVERLAPPED ol; - memset(&ol, 0, sizeof(ol)); - - res = DeviceIoControl(dev->device_handle, - IOCTL_HID_GET_INPUT_REPORT, - data, (DWORD) length, - data, (DWORD) length, - &bytes_returned, &ol); - - if (!res) { - if (GetLastError() != ERROR_IO_PENDING) { - /* DeviceIoControl() failed. Return error. */ - register_error(dev, "Send Input Report DeviceIoControl"); - return -1; - } - } - - /* Wait here until the write is done. This makes - hid_get_feature_report() synchronous. */ - res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/); - if (!res) { - /* The operation failed. */ - register_error(dev, "Send Input Report GetOverLappedResult"); - return -1; - } - - /* bytes_returned does not include the first byte which contains the - report ID. The data buffer actually contains one more byte than - bytes_returned. */ - bytes_returned++; - - return bytes_returned; -#endif + /* We could use HidD_GetInputReport() instead, but it doesn't give us an actual length, unfortunately */ + return hid_get_report(dev, IOCTL_HID_GET_INPUT_REPORT, data, length); } void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev) @@ -928,39 +1118,33 @@ void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev) int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) { - BOOL res; - - res = HidD_GetManufacturerString(dev->device_handle, string, sizeof(wchar_t) * (DWORD) MIN(maxlen, MAX_STRING_WCHARS)); - if (!res) { - register_error(dev, "HidD_GetManufacturerString"); + if (!dev->device_info || !string || !maxlen) return -1; - } + + wcsncpy(string, dev->device_info->manufacturer_string, maxlen); + string[maxlen] = L'\0'; return 0; } int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) { - BOOL res; - - res = HidD_GetProductString(dev->device_handle, string, sizeof(wchar_t) * (DWORD) MIN(maxlen, MAX_STRING_WCHARS)); - if (!res) { - register_error(dev, "HidD_GetProductString"); + if (!dev->device_info || !string || !maxlen) return -1; - } + + wcsncpy(string, dev->device_info->product_string, maxlen); + string[maxlen] = L'\0'; return 0; } int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) { - BOOL res; - - res = HidD_GetSerialNumberString(dev->device_handle, string, sizeof(wchar_t) * (DWORD) MIN(maxlen, MAX_STRING_WCHARS)); - if (!res) { - register_error(dev, "HidD_GetSerialNumberString"); + if (!dev->device_info || !string || !maxlen) return -1; - } + + wcsncpy(string, dev->device_info->serial_number, maxlen); + string[maxlen] = L'\0'; return 0; } @@ -995,7 +1179,7 @@ HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) /*#define PICPGM*/ /*#define S11*/ #define P32 -#ifdef S11 +#ifdef S11 unsigned short VendorID = 0xa0a0; unsigned short ProductID = 0x0001; #endif @@ -1025,7 +1209,7 @@ int __cdecl main(int argc, char* argv[]) memset(buf,0x00,sizeof(buf)); buf[0] = 0; buf[1] = 0x81; - + /* Open the device. */ int handle = open(VendorID, ProductID, L"12345"); diff --git a/lib/hidapi/windows/hidapi.sln b/lib/hidapi/windows/hidapi.sln deleted file mode 100644 index aeb2660e678..00000000000 --- a/lib/hidapi/windows/hidapi.sln +++ /dev/null @@ -1,41 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28307.136 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hidapi", "hidapi.vcxproj", "{A107C21C-418A-4697-BB10-20C3AA60E2E4}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hidtest", "hidtest.vcxproj", "{23E9FF6A-49D1-4993-B2B5-BBB992C6C712}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|Win32.ActiveCfg = Debug|Win32 - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|Win32.Build.0 = Debug|Win32 - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|x64.ActiveCfg = Debug|x64 - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Debug|x64.Build.0 = Debug|x64 - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|Win32.ActiveCfg = Release|Win32 - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|Win32.Build.0 = Release|Win32 - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|x64.ActiveCfg = Release|x64 - {A107C21C-418A-4697-BB10-20C3AA60E2E4}.Release|x64.Build.0 = Release|x64 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Debug|Win32.ActiveCfg = Debug|Win32 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Debug|Win32.Build.0 = Debug|Win32 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Debug|x64.ActiveCfg = Debug|x64 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Debug|x64.Build.0 = Debug|x64 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Release|Win32.ActiveCfg = Release|Win32 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Release|Win32.Build.0 = Release|Win32 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Release|x64.ActiveCfg = Release|x64 - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {8749E535-9C65-4A89-840E-78D7578C7866} - EndGlobalSection -EndGlobal diff --git a/lib/hidapi/windows/hidapi.vcproj b/lib/hidapi/windows/hidapi.vcproj deleted file mode 100644 index ee9569c7d4e..00000000000 --- a/lib/hidapi/windows/hidapi.vcproj +++ /dev/null @@ -1,201 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/lib/hidapi/windows/hidapi.vcxproj b/lib/hidapi/windows/hidapi.vcxproj deleted file mode 100644 index c793017bf72..00000000000 --- a/lib/hidapi/windows/hidapi.vcxproj +++ /dev/null @@ -1,160 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {A107C21C-418A-4697-BB10-20C3AA60E2E4} - hidapi - Win32Proj - - - - DynamicLibrary - v140 - Unicode - true - - - DynamicLibrary - v140 - Unicode - true - - - DynamicLibrary - v140 - Unicode - - - DynamicLibrary - v140 - Unicode - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>14.0.25431.1 - - - - - - - - Disabled - ..\hidapi;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_WINDOWS;_USRDLL;HIDAPI_EXPORTS;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - - Level3 - EditAndContinue - - - setupapi.lib;%(AdditionalDependencies) - true - Windows - MachineX86 - - - - - Disabled - ..\hidapi;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_WINDOWS;_USRDLL;HIDAPI_EXPORTS;%(PreprocessorDefinitions) - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - - - setupapi.lib;%(AdditionalDependencies) - true - Windows - - - - - MaxSpeed - true - ..\hidapi;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_WINDOWS;_USRDLL;HIDAPI_EXPORTS;%(PreprocessorDefinitions) - MultiThreaded - true - - Level3 - ProgramDatabase - - - setupapi.lib;%(AdditionalDependencies) - true - Windows - true - true - MachineX86 - - - - - MaxSpeed - true - ..\hidapi;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_WINDOWS;_USRDLL;HIDAPI_EXPORTS;%(PreprocessorDefinitions) - MultiThreaded - true - - - Level3 - ProgramDatabase - - - setupapi.lib;%(AdditionalDependencies) - true - Windows - true - true - - - - - - - - - - - - diff --git a/lib/hidapi/windows/hidtest.vcproj b/lib/hidapi/windows/hidtest.vcproj deleted file mode 100644 index abee0eb2b99..00000000000 --- a/lib/hidapi/windows/hidtest.vcproj +++ /dev/null @@ -1,196 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/lib/hidapi/windows/hidtest.vcxproj b/lib/hidapi/windows/hidtest.vcxproj deleted file mode 100644 index b3d8fbc1de2..00000000000 --- a/lib/hidapi/windows/hidtest.vcxproj +++ /dev/null @@ -1,156 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {23E9FF6A-49D1-4993-B2B5-BBB992C6C712} - hidtest - - - - Application - v140 - MultiByte - true - - - Application - v140 - MultiByte - true - - - Application - v140 - MultiByte - - - Application - v140 - MultiByte - - - - - - - - - - - - - - - - - - - <_ProjectFileVersion>14.0.25431.1 - - - - - - - - Disabled - ..\hidapi;%(AdditionalIncludeDirectories) - true - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - hidapi.lib;%(AdditionalDependencies) - $(SolutionDir)$(Configuration);%(AdditionalLibraryDirectories) - true - Console - MachineX86 - - - - - Disabled - ..\hidapi;%(AdditionalIncludeDirectories) - EnableFastChecks - MultiThreadedDebugDLL - Level3 - EditAndContinue - - - hidapi.lib;%(AdditionalDependencies) - $(SolutionDir)$(Platform)\$(Configuration);%(AdditionalLibraryDirectories) - true - Console - - - - - MaxSpeed - true - ..\hidapi;%(AdditionalIncludeDirectories) - MultiThreaded - true - Level3 - ProgramDatabase - - - hidapi.lib;%(AdditionalDependencies) - $(SolutionDir)$(Configuration);%(AdditionalLibraryDirectories) - true - Console - true - true - MachineX86 - - - - - MaxSpeed - true - ..\hidapi;%(AdditionalIncludeDirectories) - MultiThreaded - true - Level3 - ProgramDatabase - - - hidapi.lib;%(AdditionalDependencies) - $(SolutionDir)$(Platform)\$(Configuration);%(AdditionalLibraryDirectories) - true - Console - true - true - - - - - - - - {a107c21c-418a-4697-bb10-20c3aa60e2e4} - false - - - - - - diff --git a/src/controllers/hid/hidiothread.cpp b/src/controllers/hid/hidiothread.cpp index 37b37ba10ed..03f7535553b 100644 --- a/src/controllers/hid/hidiothread.cpp +++ b/src/controllers/hid/hidiothread.cpp @@ -148,8 +148,6 @@ QByteArray HidIoThread::getInputReport(quint8 reportID) { auto hidDeviceLock = lockMutex(&m_hidDeviceAndPollMutex); m_pPollData[m_pollingBufferIndex][0] = reportID; - // FIXME: implement upstream for hidraw backend on Linux - // https://github.com/libusb/hidapi/issues/259 int bytesRead = hid_get_input_report( m_pHidDevice, m_pPollData[m_pollingBufferIndex], kBufferSize); if (bytesRead <= kReportIdSize) {